"""Siembra de catálogos globales (Aduanasoft) del CRM.

Idempotente: inserta solo las claves que aún no existen (tenant_id NULL). Se
puede correr múltiples veces sin duplicar. Para ejecutarlo en un entorno:

    docker compose exec backend python -m api.v1.modules.crm.catalogs.seed
"""

import logging

from sqlalchemy.orm import Session

from .models import CatalogItem
from .seed_data import GLOBAL_CATALOGS

logger = logging.getLogger(__name__)


def seed_global_catalogs(db: Session) -> dict:
    """Inserta los catálogos globales que falten. Devuelve un resumen {catalog: nuevos}."""
    summary: dict[str, int] = {}
    for catalog, meta in GLOBAL_CATALOGS.items():
        is_system = bool(meta.get("is_system", False))
        existing = {
            row.code
            for row in db.query(CatalogItem.code).filter(
                CatalogItem.catalog == catalog, CatalogItem.tenant_id.is_(None)
            )
        }
        added = 0
        for order, item in enumerate(meta["items"]):
            if item["code"] in existing:
                continue
            db.add(
                CatalogItem(
                    catalog=catalog,
                    code=item["code"],
                    label=item["label"],
                    parent_catalog=item.get("parent_catalog"),
                    parent_code=item.get("parent_code"),
                    extra=item.get("extra"),
                    tenant_id=None,
                    sort_order=order,
                    is_active=True,
                    is_system=is_system,
                )
            )
            added += 1
        if added:
            summary[catalog] = added
    db.commit()
    total = sum(summary.values())
    logger.info("seed_global_catalogs: %s nuevas filas en %s catálogos", total, len(summary))
    return summary


def _run() -> None:
    from core.database import CoreSessionLocal

    db = CoreSessionLocal()
    try:
        result = seed_global_catalogs(db)
        print("Catálogos sembrados (nuevos):", result or "0 (ya estaban todos)")
    finally:
        db.close()


if __name__ == "__main__":
    _run()
