"""seed_initial_data

Revision ID: 8c9bad3da37f
Revises: 9db46c604463
Create Date: 2026-05-01 22:01:50.174319

"""
# pylint: disable=no-member

from typing import Sequence, Union

from alembic import op
from api.v1.modules.public.reference_data.code_pedimento_regimens.seed import (
    seed as code_pedimento_regimens_seed,
)
from api.v1.modules.public.reference_data.containers.seed import (
    seed as container_types_seed,
)
from api.v1.modules.public.reference_data.countries.seed import seed as countries_seed
from api.v1.modules.public.reference_data.currency_types.seed import (
    seed as currency_types_seed,
)
from api.v1.modules.public.reference_data.customs_sections.seed import (
    seed as customs_sections_seed,
)
from api.v1.modules.public.reference_data.customs_warehouses.seed import (
    seed as customs_warehouses_seed,
)
from api.v1.modules.public.reference_data.incoterms.seed import seed as incoterms_seed
from api.v1.modules.public.reference_data.invoice_types.seed import (
    seed as invoice_types_seed,
)
from api.v1.modules.public.reference_data.material_types.seed import (
    seed as material_types_seed,
)
from api.v1.modules.public.reference_data.payment_methods.seed import (
    seed as payment_methods_seed,
)
from api.v1.modules.public.reference_data.pedimento_codes.seed import (
    seed as pedimento_codes_seed,
)
from api.v1.modules.public.reference_data.pedimento_regimens.seed import (
    seed as pedimento_regimens_seed,
)
from api.v1.modules.public.reference_data.states.seed import seed as states_seed
from api.v1.modules.public.reference_data.transport_modes.seed import (
    seed as transport_modes_seed,
)
from api.v1.modules.public.reference_data.pedimento_transport_catalog.seed import (
    seed as pedimento_transport_catalog_seed,
)
from api.v1.modules.public.reference_data.transport_types.seed import (
    seed as transport_types_seed,
)
from api.v1.modules.public.reference_data.valuation_methods.seed import (
    seed as valuation_methods_seed,
)
from api.v1.modules.a76.general_catalogs.units_of_measure.seed import (
    seed as units_of_measure_seed,
)
from api.v1.modules.a76.general_catalogs.units_of_measure.seed_ace import (
    seed as ace_seed,
)
from api.v1.modules.a76.general_catalogs.units_of_measure.seed_oma import (
    seed as oma_seed,
)
from api.v1.modules.a76.general_catalogs.units_of_measure.seed_ame import (
    seed as ame_seed,
)
from api.v1.modules.a76.general_catalogs.units_of_measure.seed_adua import (
    seed as adua_seed,
)
from api.v1.modules.a76.general_catalogs.fractions.tariff_fractions.seed import (
    seed as tariff_fractions_seed,
)
from api.v1.modules.public.reference_data.trailer_types.seed import (
    seed as trailer_types_seed,
)
from api.v1.modules.core.permissions.seed_v2 import registry

from api.v1.modules.public.reference_data.license_exceptions.seed import seed_license_exceptions
from api.v1.modules.public.reference_data.agency_tariff_codes.seed import seed_agency_tariff_codes
from api.v1.modules.public.reference_data.identifiers.seed import seed_identifiers
from api.v1.modules.public.reference_data.carta_porte_codes.seed import seed_carta_porte
from sqlalchemy.orm import Session

# revision identifiers, used by Alembic.
revision: str = "8c9bad3da37f"
down_revision: Union[str, Sequence[str], None] = "9db46c604463"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Catálogos de referencia y permisos base (datos)."""

    def format_value(val):
        if val is None or str(val).strip() == "" or str(val).upper() == "NONE":
            return "NULL"
        return f"'{str(val).replace(chr(39), chr(39)*2)}'"

    # --- SEEDS PUBLIC (Tablas base) ---
    values_pc = ", ".join(
        [
            f"('{code}', '{desc.replace(chr(39), chr(39)*2)}')"
            for code, desc in pedimento_codes_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO pedimento_codes (code, description) VALUES 
        {values_pc}
        ON CONFLICT (code) DO NOTHING;
    """
    )

    values_pr = ", ".join(
        [
            f"('{code}', '{desc.replace(chr(39), chr(39)*2)}')"
            for code, desc in pedimento_regimens_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.pedimento_regimens (code, description) VALUES
        {values_pr}
        ON CONFLICT (code) DO NOTHING;
    """
    )

    values_cpr = ", ".join(
        [
            f"('{ped_code}', '{reg_code}', '{type_code}')"
            for ped_code, reg_code, type_code in code_pedimento_regimens_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.code_pedimento_regimens (pedimento_code, regimen_code, type_code) VALUES
        {values_cpr}
    """
    )

    values_c = ", ".join(
        [
            f"('{key}', '{desc.replace(chr(39), chr(39)*2)}')"
            for key, desc in container_types_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.containers (key, description) VALUES
        {values_c}
        ON CONFLICT (key) DO NOTHING;
    """
    )

    values_country = ", ".join(
        [
            f"('{m3_key}', '{mex_key}', '{ame_key}', '{desc_es.replace(chr(39), chr(39)*2)}', '{desc_en.replace(chr(39), chr(39)*2)}')"
            for m3_key, mex_key, ame_key, desc_es, desc_en in countries_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.countries (m3_key, mex_key, ame_key, description_es, description_en) VALUES
         {values_country}
        ON CONFLICT (m3_key) DO NOTHING;
    """
    )

    values_ct = ", ".join(
        [
            f"('{code}', '{currency_name.replace(chr(39), chr(39)*2)}', '{country_desc.replace(chr(39), chr(39)*2)}')"
            for code, currency_name, country_desc in currency_types_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.currency_types (code, currency_name, country_description) VALUES
        {values_ct}
        ON CONFLICT (code) DO NOTHING;
    """
    )

    values_cs = ", ".join(
        [
            f"('{code}', '{name.replace(chr(39), chr(39)*2)}')"
            for code, name in customs_sections_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.customs_sections (customs_code, section_name) VALUES
        {values_cs}
        ON CONFLICT (customs_code) DO NOTHING;
    """
    )

    values_cw = ", ".join(
        [
            f"('{key}', '{customs.replace(chr(39), chr(39)*2)}', '{fiscalized_warehouse.replace(chr(39), chr(39)*2)}')"
            for key, customs, fiscalized_warehouse in customs_warehouses_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.customs_warehouses (key, customs, fiscalized_warehouse)
        VALUES
        {values_cw}
        ON CONFLICT (key, customs) DO NOTHING;
    """
    )

    values_incoterms = ", ".join(
        [
            f"('{code}', '{desc_es.replace(chr(39), chr(39)*2)}', '{desc_en.replace(chr(39), chr(39)*2)}')"
            for code, desc_es, desc_en in incoterms_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.incoterms (code, description_es, description_en) VALUES
        {values_incoterms}
        ON CONFLICT (code) DO NOTHING;
    """
    )

    values_it = ", ".join(
        [
            f"('{key}', '{desc.replace(chr(39), chr(39)*2)}', '{note.replace(chr(39), chr(39)*2)}', '{type.replace(chr(39), chr(39)*2)}', '{operation.replace(chr(39), chr(39)*2)}')"
            for key, desc, note, type, operation in invoice_types_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.invoice_types (key, description, note, type, operation) VALUES
        {values_it}
        ON CONFLICT (key) DO NOTHING;
    """
    )

    values_mt = ", ".join(
        [
            f"('{key}', '{desc.replace(chr(39), chr(39)*2)}', '{category.replace(chr(39), chr(39)*2)}')"
            for key, desc, category in material_types_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.material_types (key, description, type) VALUES
        {values_mt}
        ON CONFLICT (key) DO NOTHING;
    """
    )

    values_pm = ", ".join(
        [
            f"('{key}', '{desc.replace(chr(39), chr(39)*2)}')"
            for key, desc in payment_methods_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.payment_methods (key, description) VALUES
        {values_pm}
        ON CONFLICT (key) DO NOTHING;
    """
    )

    values_tm = ", ".join(
        [
            f"('{key}', '{name.replace(chr(39), chr(39)*2)}')"
            for key, name in transport_modes_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.transport_modes (key, name) VALUES
        {values_tm}
        ON CONFLICT (key) DO NOTHING;
    """
    )

    values_ptc = ", ".join(
        [
            f"('{code}', '{en.replace(chr(39), chr(39)*2)}', '{es.replace(chr(39), chr(39)*2)}', '{pdc}')"
            for code, en, es, pdc in pedimento_transport_catalog_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.pedimento_transport_catalog (code, transport_en, transport_es, payment_date_code) VALUES
        {values_ptc}
        ON CONFLICT (code) DO NOTHING;
    """
    )

    values_tt = ", ".join(
        [
            f"('{code}', '{desc.replace(chr(39), chr(39)*2)}')"
            for code, desc in transport_types_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.transport_types (transport_code, description) VALUES
        {values_tt}
        ON CONFLICT (transport_code) DO NOTHING;
    """
    )

    values_trailer = ", ".join(
        [
            f"('{code}', '{desc.replace(chr(39), chr(39)*2)}')"
            for code, desc in trailer_types_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.trailer_type (trailer_type_key, description) VALUES
        {values_trailer}
        ON CONFLICT (trailer_type_key) DO NOTHING;
    """
    )

    values_vm = ", ".join(
        [
            f"('{key}', '{desc.replace(chr(39), chr(39)*2)}')"
            for key, desc in valuation_methods_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.valuation_methods (key, description) VALUES
        {values_vm}
        ON CONFLICT (key) DO NOTHING;
    """
    )

    # --- SEEDS A76 (Unidades de Medida) ---
    val_ace = ", ".join(
        [f"({format_value(c)}, {format_value(d)})" for c, d in ace_seed]
    )
    op.execute(
        f"INSERT INTO a76.unit_of_measure_ace (code, description) VALUES {val_ace} ON CONFLICT ON CONSTRAINT uq_uom_ace_code DO NOTHING;"
    )

    val_oma = ", ".join(
        [f"({format_value(c)}, {format_value(d)})" for c, d in oma_seed]
    )
    op.execute(
        f"INSERT INTO a76.unit_of_measure_oma (code, description) VALUES {val_oma} ON CONFLICT ON CONSTRAINT uq_uom_oma_code DO NOTHING;"
    )

    val_ame = ", ".join(
        [f"({format_value(c)}, {format_value(d)})" for c, d in ame_seed]
    )
    op.execute(
        f"INSERT INTO a76.unit_of_measure_american (code, description) VALUES {val_ame} ON CONFLICT ON CONSTRAINT uq_uom_american_code DO NOTHING;"
    )

    val_adua = ", ".join(
        [f"({format_value(code)}, {format_value(desc)}, {format_value(a76_code)})" for code, desc, a76_code in adua_seed]
    )
    op.execute(
        f"INSERT INTO a76.unit_of_measure_customs (code, description, a76_unit_code) VALUES {val_adua} ON CONFLICT ON CONSTRAINT uq_uom_customs_code DO NOTHING;"
    )

    additional_customs = set()
    additional_american = set()
    additional_ace = set()
    additional_oma = set()

    existing_customs = {code for code, desc, a76_code in adua_seed}
    existing_american = {c for c, d in ame_seed}
    existing_ace = {c for c, d in ace_seed}
    existing_oma = {c for c, d in oma_seed}

    for code, desc, desc_en, customs, american, ace, oma in units_of_measure_seed:
        if customs and customs.strip() and customs not in existing_customs:
            additional_customs.add((customs, f"Auto-generated from {code}"))
        if american and american.strip() and american not in existing_american:
            additional_american.add((american, f"Auto-generated from {code}"))
        if ace and ace.strip() and ace not in existing_ace:
            additional_ace.add((ace, f"Auto-generated from {code}"))
        if oma and oma.strip() and oma not in existing_oma:
            additional_oma.add((oma, f"Auto-generated from {code}"))

    if additional_customs:
        val_add_customs = ", ".join(
            [f"({format_value(c)}, {format_value(d)}, NULL)" for c, d in additional_customs]
        )
        op.execute(
            f"INSERT INTO a76.unit_of_measure_customs (code, description, a76_unit_code) VALUES {val_add_customs} ON CONFLICT ON CONSTRAINT uq_uom_customs_code DO NOTHING;"
        )

    if additional_american:
        val_add_american = ", ".join(
            [f"({format_value(c)}, {format_value(d)})" for c, d in additional_american]
        )
        op.execute(
            f"INSERT INTO a76.unit_of_measure_american (code, description) VALUES {val_add_american} ON CONFLICT ON CONSTRAINT uq_uom_american_code DO NOTHING;"
        )

    if additional_ace:
        val_add_ace = ", ".join(
            [f"({format_value(c)}, {format_value(d)})" for c, d in additional_ace]
        )
        op.execute(
            f"INSERT INTO a76.unit_of_measure_ace (code, description) VALUES {val_add_ace} ON CONFLICT ON CONSTRAINT uq_uom_ace_code DO NOTHING;"
        )

    if additional_oma:
        val_add_oma = ", ".join(
            [f"({format_value(c)}, {format_value(d)})" for c, d in additional_oma]
        )
        op.execute(
            f"INSERT INTO a76.unit_of_measure_oma (code, description) VALUES {val_add_oma} ON CONFLICT ON CONSTRAINT uq_uom_oma_code DO NOTHING;"
        )

    # --- SEEDS CORE (Permissions) ---
    all_permissions = registry.get_all()

    values_permissions = ", ".join(
        [
            f"({format_value(p.code)}, {format_value(p.description)}, {format_value(p.module)}, {format_value(p.action)})"
            for p in all_permissions
        ]
    )

    if values_permissions:
        op.execute(
            f"""
            INSERT INTO core.permissions (code, description, module, action)
            VALUES {values_permissions}
            ON CONFLICT (code) DO NOTHING;
        """
        )

    values_states = ", ".join(
        [
            f"('{m3_key}', '{description.replace(chr(39), chr(39)*2)}', {format_value(mex_key)})"
            for m3_key, description, mex_key in states_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO public.states (m3_key, description, mex_key)
        VALUES {values_states}
        ON CONFLICT (m3_key, description) DO NOTHING;
    """
    )

    values_tariff_fractions = ", ".join(
        [
            f"({format_value(code)}, {format_value(fraction)}, {format_value(description)}, "
            f"{format_value(nico)}, {format_value(umt)}, {format_value(adv_impo)}, {format_value(adv_expo)})"
            for code, fraction, description, nico, umt, adv_impo, adv_expo in tariff_fractions_seed
        ]
    )
    op.execute(
        f"""
        INSERT INTO a76.tariff_fractions (code, fraction, description, nico, umt, adv_impo, adv_expo)
        VALUES {values_tariff_fractions}
        ON CONFLICT (code) DO NOTHING;
    """
    )

    bind = op.get_bind()
    session = Session(bind=bind)
    seed_license_exceptions(session)
    seed_agency_tariff_codes(session)
    seed_identifiers(session)
    seed_carta_porte(session)


def downgrade() -> None:
    """Los datos de catálogo no se revierten automáticamente."""
    pass
