"""
Carga de conjuntos FK para validaci?n/mapeo de import CSV de clases de materiales.
Clarion: Tipo Activo Fijo, U.M., Fracci?n Mex (GFracGenSifra + hist?rico), Fracci?n Ame (GFracAme), C?digo Producto CP (si existe).
"""
from typing import Set, Tuple

from core.database import CoreSessionLocal


def load_classes_fk_sets(
    tenant_id: int,
    company_id: int,
) -> Tuple[Set[str], Set[str], Set[str], Set[str], Set[str]]:
    """
    Carga todos los conjuntos necesarios para validaci?n CSV de clases (paridad Clarion).
    Devuelve (valid_material_keys, valid_uom_codes, valid_fraction_mex_8, valid_fraction_ame, valid_product_codes_cp).
    - valid_fraction_mex_8: c?digos de 8 caracteres v?lidos (TariffFraction + HistoricalTariffFraction).
    - valid_fraction_ame: c?digos de fracci?n americana (USTariffFraction por tenant/company).
    - valid_product_codes_cp: c?digos de producto/servicio CP (vac?o si no existe cat?logo).
    """
    valid_material_keys: Set[str] = set()
    valid_uom_codes: Set[str] = set()
    valid_fraction_mex_8: Set[str] = set()
    valid_fraction_ame: Set[str] = set()
    valid_product_codes_cp: Set[str] = set()
    try:
        with CoreSessionLocal() as session:
            from api.v1.modules.public.reference_data.material_types.models import MaterialType
            from api.v1.modules.a76.general_catalogs.units_of_measure.models import UnitOfMeasure
            from api.v1.modules.a76.general_catalogs.fractions.tariff_fractions.models import TariffFraction
            from api.v1.modules.a76.general_catalogs.fractions.historical_tariff_fractions.models import HistoricalTariffFraction
            for m in session.query(MaterialType.key).all():
                if m[0]:
                    valid_material_keys.add(m[0])
            for u in (
                session.query(UnitOfMeasure.code)
                .filter(
                    UnitOfMeasure.tenant_id == tenant_id,
                    UnitOfMeasure.company_id == company_id,
                )
                .all()
            ):
                if u[0]:
                    valid_uom_codes.add(u[0])

            for row in session.query(TariffFraction.code).all():
                if row[0]:
                    code = row[0].strip()
                    valid_fraction_mex_8.add(code[:8])

            for row in (
                session.query(HistoricalTariffFraction.historical_fraction)
                .filter(
                    HistoricalTariffFraction.tenant_id == tenant_id,
                    HistoricalTariffFraction.company_id == company_id,
                    HistoricalTariffFraction.historical_fraction.isnot(None),
                )
                .distinct()
                .all()
            ):
                if row[0] and row[0].strip():
                    valid_fraction_mex_8.add(row[0].strip()[:8])

            # Fracci?n americana: validaci?n por fila contra SITAR (no se precarga el cat?logo completo).

    except Exception as e:
        import logging
        logging.getLogger(__name__).warning("Classes import: could not load FK sets: %s", e)
    return (
        valid_material_keys,
        valid_uom_codes,
        valid_fraction_mex_8,
        valid_fraction_ame,
        valid_product_codes_cp,
    )
