"""
Carga de conjuntos FK para validación de import CSV de conductores.
Clarion: GTransportista (ClaveTrans), GPaises (Pais_Ame).
"""
from typing import Set, Tuple, Optional, Dict
import logging

from core.database import CoreSessionLocal

logger = logging.getLogger(__name__)


def load_drivers_fk_sets(
    tenant_id: Optional[int] = None,
    company_id: Optional[int] = None,
) -> Tuple[Set[str], Set[str], Dict[str, str]]:
    """
    Carga conjuntos para validación CSV de conductores (paridad Clarion).
    Devuelve:
    - valid_transporter_keys: todas las claves de transportistas en mayúsculas (a76.transporter)
    - valid_country_ame: claves americana de países (GPaises.Pais_Ame / Country.ame_key), mayúsculas
    - transporter_key_actual: dict clave_upper -> clave real en BD (para insert con mismo caso que en transporter)
    """
    valid_transporter_keys: Set[str] = set()
    valid_country_ame: Set[str] = set()
    transporter_key_actual: Dict[str, str] = {}

    try:
        with CoreSessionLocal() as session:
            from api.v1.modules.a76.transportation.transporters.models import Transporter
            from api.v1.modules.public.reference_data.countries.models import Country

            # Solo transportistas del tenant/company del upload (paridad con Driver.tenant_id/company_id)
            q = session.query(Transporter.transporter_key).filter(
                Transporter.tenant_id == tenant_id,
                Transporter.company_id == company_id,
            )
            for row in q.all():
                if row[0]:
                    raw = (row[0] or "").strip()
                    upper = raw.upper()
                    valid_transporter_keys.add(upper)
                    transporter_key_actual[upper] = raw

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

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

    logger.info(
        "Drivers import FK: %d transportistas (claves: %s), %d paises",
        len(valid_transporter_keys),
        sorted(valid_transporter_keys)[:20] if len(valid_transporter_keys) <= 20 else sorted(valid_transporter_keys)[:10] + ["..."],
        len(valid_country_ame),
    )
    return (valid_transporter_keys, valid_country_ame, transporter_key_actual)
