from __future__ import annotations

import os
from typing import Any, Dict

# Lazy import for LLM provider to avoid GCP credential discovery at startup
_llm_provider_getter = None

def _get_llm_provider():
    """Lazy loader for get_llm_provider to avoid startup hang."""
    global _llm_provider_getter
    if _llm_provider_getter is None:
        from ..providers import get_llm_provider as _glp
        _llm_provider_getter = _glp
    return _llm_provider_getter()

from fmatch.core import map_state_code
from fmatch.core.heuristics import normalize_country_code


def normalize_state(text: str, *, country: str | None = None) -> Dict[str, Any]:
    requested_country = country or os.getenv("DEFAULT_COUNTRY", "US")
    normalized_country = (
        normalize_country_code(requested_country)
        or (requested_country or "US").strip().upper()
        or "US"
    )
    mapped = map_state_code(text, requested_country)

    if mapped:
        return {"value": mapped}

    # Fallback to LLM if enabled
    if os.getenv("TRANSFORM_ENABLE_LLM_FALLBACK", "true").lower() == "true":
        provider = _get_llm_provider()
        if provider:
            schema = {
                "type": "object",
                "properties": {"name": {"type": "string"}},
                "required": ["name"],
            }
            prompt = (
                f"Map the region to its official postal/ISO subdivision full name for {normalized_country}. "
                'Output JSON: {"name":"<NAME>"}. Only return a valid subdivision name.\n'
                f'Input: "{text}"'
            )
            try:
                out = provider.generate_json(prompt, schema=schema, num_predict=32)
                mapped = (out.get("value", {}) or {}).get("name")
                if mapped:
                    return {"value": mapped}
            except Exception:
                pass

    return {"value": ""}
