from __future__ import annotations

from typing import Any


GLOBAL_DEFAULT_ALIASES = {
    "guidance_phrase": {
        "fluoro": "fluoroscopy_guidance_phrase",
        "fluoroscopy": "fluoroscopy_guidance_phrase",
        "default": "ultrasound_guidance_phrase",
    },
    "monitoring": {
        "rfa": "default_monitoring_rfa",
        "radiofrequency": "default_monitoring_rfa",
        "infusion": "default_monitoring_infusion",
        "ketamine": "default_monitoring_infusion",
        "default": "default_monitoring_injection",
    },
}


def _has_value(value: Any) -> bool:
    return value is not None and str(value).strip() != ""


def _form_context(form: dict[str, Any]) -> str:
    parts = [
        form.get("form_id", ""),
        form.get("title", ""),
        form.get("family", ""),
        form.get("category", ""),
        form.get("form_type", ""),
    ]
    return " ".join(str(part).lower() for part in parts)


def _global_default_key(field_key: str, form: dict[str, Any]) -> str:
    alias = GLOBAL_DEFAULT_ALIASES.get(field_key)
    if not alias:
        return field_key

    context = _form_context(form)
    for token, mapped_key in alias.items():
        if token != "default" and token in context:
            return mapped_key
    return alias["default"]


def resolve_field_value(
    *,
    field: dict[str, Any],
    form: dict[str, Any],
    global_defaults: dict[str, Any],
    encounter_values: dict[str, Any] | None = None,
) -> str:
    encounter_values = encounter_values or {}
    key = field["key"]

    if _has_value(encounter_values.get(key)):
        return str(encounter_values[key])

    if field.get("default_layer") == "No Default":
        return ""

    form_defaults = form.get("defaults") or form.get("procedure_defaults") or {}
    if field.get("default_layer") == "Per-Form Default" and _has_value(form_defaults.get(key)):
        return str(form_defaults[key])

    global_key = _global_default_key(key, form)
    if field.get("default_layer") == "Global Default" and _has_value(global_defaults.get(global_key)):
        return str(global_defaults[global_key])

    if _has_value(form_defaults.get(key)):
        return str(form_defaults[key])
    if _has_value(global_defaults.get(global_key)):
        return str(global_defaults[global_key])
    return ""


def resolve_defaults(
    form: dict[str, Any],
    global_defaults: dict[str, Any],
    encounter_values: dict[str, Any] | None = None,
) -> dict[str, str]:
    return {
        field["key"]: resolve_field_value(
            field=field,
            form=form,
            global_defaults=global_defaults,
            encounter_values=encounter_values,
        )
        for field in form.get("fields", [])
    }
