import os


def _parse_bool(value):
    if isinstance(value, bool):
        return value
    text = str(value).strip().lower()
    return text in {"1", "true", "yes", "on"}


def _parse_int(value):
    return int(str(value).strip())


def _parse_str(value):
    return str(value)


def _parse_source(value):
    text = str(value).strip()
    if text and text.lstrip("+-").isdigit():
        return int(text)
    return text


def _apply_env_overrides(namespace, spec):
    for env_name, (key, parser) in spec.items():
        if env_name not in os.environ:
            continue
        namespace[key] = parser(os.environ[env_name])


def apply_config_env_overrides(namespace):
    _apply_env_overrides(
        namespace,
        {
            "FPV_MODEL_PATH": ("MODEL_PATH", _parse_str),
            "FPV_SOURCE": ("SOURCE", _parse_source),
            "FPV_VIDEO_REALTIME": ("VIDEO_REALTIME", _parse_bool),
            "FPV_SHOW_OUTPUT": ("SHOW_OUTPUT", _parse_bool),
            "FPV_SAVE_INFER_VIDEO": ("SAVE_INFER_VIDEO", _parse_bool),
            "FPV_OUT_VIDEO_PATH": ("OUT_VIDEO_PATH", _parse_str),
            "FPV_GUIDANCE_EXPORT_ENABLE": ("GUIDANCE_EXPORT_ENABLE", _parse_bool),
            "FPV_GUIDANCE_EXPORT_PATH": ("GUIDANCE_EXPORT_PATH", _parse_str),
        },
    )


def apply_intercept_env_overrides(namespace):
    _apply_env_overrides(
        namespace,
        {
            "FPV_AUTOPILOT_ENABLE": ("AUTOPILOT_ENABLE", _parse_bool),
            "FPV_AUTOPILOT_BACKEND": ("AUTOPILOT_BACKEND", _parse_str),
            "FPV_AUTOPILOT_JSON_PATH": ("AUTOPILOT_JSON_PATH", _parse_str),
            "FPV_MAVLINK_CONNECTION": ("MAVLINK_CONNECTION", _parse_str),
            "FPV_MSP_PORT": ("MSP_PORT", _parse_str),
            "FPV_PROTO_UDP_ENABLE": ("PROTO_UDP_ENABLE", _parse_bool),
            "FPV_PROTO_UDP_HOST": ("PROTO_UDP_HOST", _parse_str),
            "FPV_PROTO_UDP_PORT": ("PROTO_UDP_PORT", _parse_int),
            "FPV_PROTO_UDP_DESCRIPTOR": ("PROTO_UDP_DESCRIPTOR", _parse_int),
        },
    )
