"""MODELCONTRACT-01: Medium 전용 GPU tensor preparation 설정 경계."""
import configparser
import io

# Model I/O and the deployed engine must change together.
MODEL_INPUT_CONTRACTS = {
    ('det', 'RFDETRMedium'): ('fp16', True),
    ('pose', 'RFDETRKeypointPreview'): ('fp16', True),
    ('det', 'RFDETRFireSmoke'): ('fp16', True),
    ('det', 'Awiros_person_and_head_detection'): ('fp16', True),
}


def model_input_contract(role: str, model_name: str) -> tuple[str, bool]:
    return MODEL_INPUT_CONTRACTS.get((role, model_name), ('fp32', False))

NATIVE_PREPROCESS = '''preprocess {
    network_format: MEDIA_FORMAT_NONE
    tensor_order: TENSOR_ORDER_LINEAR
    tensor_name: "input"
    maintain_aspect_ratio: 0
    frame_scaling_hw: FRAME_SCALING_HW_DEFAULT
    frame_scaling_filter: 1
    normalize { scale_factor: 0.00392156862 channel_offsets: [0, 0, 0] }
  }'''


def medium_preprocess_config(unique_id: int, *, fp16_input: bool = False, resolution: int = 576) -> str:
    if resolution not in (512,576):
        raise ValueError('Unsupported preprocessing resolution')
    config = configparser.ConfigParser()
    config['property'] = {
        'enable': '1', 'target-unique-ids': str(unique_id), 'unique-id': str(unique_id),
        'network-input-order': '0', 'process-on-frame': '1', 'gpu-id': '0',
        'maintain-aspect-ratio': '0', 'processing-width': '576', 'processing-height': '576',
        'scaling-buf-pool-size': '4', 'tensor-buf-pool-size': '4',
        'network-input-shape': '1;3;576;576', 'network-color-format': '0',
        'tensor-data-type': '7' if fp16_input else '0', 'tensor-name': 'input', 'scaling-pool-memory-type': '2',
        'scaling-pool-compute-hw': '1', 'scaling-filter': '1',
        'custom-lib-path': '/opt/contextra/lib/libcontextra_medium_preprocess.so',
        'custom-tensor-preparation-function': 'CustomTensorPreparation',
    }
    config['group-0'] = {
        'src-ids': '0', 'process-on-roi': '0',
        'custom-input-transformation-function': 'CustomTransformation',
    }
    config['property'].update({'processing-width':str(resolution),'processing-height':str(resolution),
                              'network-input-shape':f'1;3;{resolution};{resolution}'})
    if resolution == 512:
        config['property']['custom-lib-path']='/opt/contextra/lib/libcontextra_crowd_preprocess.so'
    output = io.StringIO()
    config.write(output)
    return output.getvalue()
