"""
Carga de conjuntos FK para validación de import CSV de vehículos (transportes).
Clarion: GTipoTransportes, GPaises (Pais_Ame), GEstados (Descripcion / Clave_Ame), relación Estado-País.
"""
from typing import Set, Tuple, Optional
import logging

from core.database import CoreSessionLocal

logger = logging.getLogger(__name__)


def load_vehicles_fk_sets(
    tenant_id: Optional[int] = None,
    company_id: Optional[int] = None,
) -> Tuple[
    Set[str],
    Set[str],
    Set[str],
    Set[Tuple[str, str]],
]:
    """
    Carga conjuntos para validación CSV de vehículos (paridad Clarion).
    Devuelve:
    - valid_transport_codes: códigos de transport_types (GTipoTransportes)
    - valid_country_ame: claves americana de países (GPaises.Pais_Ame), mayúsculas
    - state_descriptions_upper: descripciones y mex_key en mayúsculas (GEstados)
    - state_country_set: (ame_key_pais, token_upper) para description o mex_key
    """
    valid_transport_codes: Set[str] = set()
    valid_country_ame: Set[str] = set()
    state_descriptions_upper: Set[str] = set()
    state_country_set: Set[Tuple[str, str]] = set()

    try:
        with CoreSessionLocal() as session:
            from api.v1.modules.public.reference_data.transport_types.models import TransportType
            from api.v1.modules.public.reference_data.countries.models import Country
            from api.v1.modules.public.reference_data.states.models import State

            for row in session.query(TransportType.transport_code).all():
                if row[0]:
                    valid_transport_codes.add((row[0] or "").strip().upper())

            for row in session.query(Country.ame_key).all():
                if row[0]:
                    valid_country_ame.add((row[0] or "").strip().upper())

            for state in session.query(State).all():
                country = (
                    session.query(Country)
                    .filter(Country.m3_key == state.m3_key)
                    .first()
                )
                ame = None
                if country and (country.ame_key or "").strip():
                    ame = (country.ame_key or "").strip().upper()

                desc = (state.description or "").strip()
                if desc:
                    state_descriptions_upper.add(desc.upper())
                    if ame:
                        state_country_set.add((ame, desc.upper()))

                mex_key = (state.mex_key or "").strip()
                if mex_key:
                    mk = mex_key.upper()
                    state_descriptions_upper.add(mk)
                    if ame:
                        state_country_set.add((ame, mk))

    except Exception as e:
        logger.warning("Vehicles import: could not load FK sets: %s", e)

    return (
        valid_transport_codes,
        valid_country_ame,
        state_descriptions_upper,
        state_country_set,
    )
