from __future__ import annotations

import re
from typing import Any, Dict

from fmatch.core.heuristics import AU_STATE_MAP, CA_PROVINCE_MAP, US_STATE_MAP

_NAME_LOOKUP = {}
for mapping in (US_STATE_MAP, CA_PROVINCE_MAP, AU_STATE_MAP):
    for key, code in mapping.items():
        if len(key) <= 2:
            continue
        cleaned = re.sub(r"[^a-z]", "", key)
        _NAME_LOOKUP[cleaned] = code

_OVERRIDES = {
    "districtcolumbia": "DC",
    "washingtondc": "DC",
    "washingtondistrictcolumbia": "DC",
}

_NAME_LOOKUP.update(_OVERRIDES)


def state_name_to_code(value: str) -> Dict[str, Any]:
    text = (value or "").strip()
    if not text:
        return {"value": ""}

    key = re.sub(r"[^a-z]", "", text.lower())
    code = _NAME_LOOKUP.get(key)
    if code:
        return {"value": code}

    key = re.sub(r"(state|territory)$", "", key)
    key = key.strip()
    code = _NAME_LOOKUP.get(key)
    return {"value": code or ""}
