"""Endpoints de catálogos de referencia y participantes del proceso (R-T-01, R-T-10).

Incluye el CRUD de catálogos de referencia (T2026-07-081/082): SAT/ISO globales
(Aduanasoft) y catálogos propios de cada cliente (tenant).
"""

from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session

from core.database import get_core_db
from core.security import get_current_user

from ..accounts.models import Account
from ..suppliers.models import Supplier
from . import service as catalog_service
from .data import INCOTERMS, PARTICIPANT_ROLES
from .dto import CatalogItemCreate, CatalogItemResponse, CatalogItemUpdate, CatalogMeta

router = APIRouter()


@router.get("/catalogs/incoterms")
def list_incoterms(
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
):
    """Catálogo de Incoterms 2020 (R-T-10)."""
    return INCOTERMS


@router.get("/catalogs/participant-roles")
def list_participant_roles(
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
):
    """Catálogo de roles/actores del proceso, incluida la autoridad aduanera (R-T-01)."""
    return PARTICIPANT_ROLES


# ----------------------------------------------------------------------------
# Catálogos de referencia (CRUD) — T2026-07-081/082
# ----------------------------------------------------------------------------


@router.get("/catalogs", response_model=list[CatalogMeta])
def list_catalog_meta(
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Lista los catálogos disponibles (global + del tenant) con su conteo."""
    return catalog_service.list_meta(db, current_user["tenant_id"])


@router.get("/catalogs/{catalog}", response_model=list[CatalogItemResponse])
def list_catalog_items(
    catalog: str,
    company_id: int = Query(..., description="Company ID"),
    parent_code: str | None = Query(None, description="Filtra dependientes (ej. Estado por País)"),
    include_inactive: bool = Query(False),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Opciones de un catálogo (global + del tenant), activas y ordenadas."""
    return catalog_service.list_items(
        db, catalog, current_user["tenant_id"], parent_code=parent_code, include_inactive=include_inactive
    )


@router.post(
    "/catalogs/{catalog}", response_model=CatalogItemResponse, status_code=status.HTTP_201_CREATED
)
def create_catalog_item(
    catalog: str,
    data: CatalogItemCreate,
    company_id: int = Query(..., description="Company ID"),
    scope: str | None = Query("tenant", description="'tenant' (cliente) o 'global' (Aduanasoft, hub_admin)"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Inserta una opción en un catálogo."""
    return catalog_service.create_item(db, catalog, data, current_user, scope=scope)


@router.patch("/catalogs/{catalog}/{item_id}", response_model=CatalogItemResponse)
def update_catalog_item(
    catalog: str,
    item_id: int,
    data: CatalogItemUpdate,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Edita una opción de catálogo."""
    return catalog_service.update_item(db, catalog, item_id, data, current_user)


@router.delete("/catalogs/{catalog}/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_catalog_item(
    catalog: str,
    item_id: int,
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Borra una opción de catálogo (los catálogos base del sistema no se borran)."""
    catalog_service.delete_item(db, catalog, item_id, current_user)


@router.get("/participants")
def list_participants(
    company_id: int = Query(..., description="Company ID"),
    role: str | None = Query(None, description="Filtra por rol/clasificación"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Vista unificada de participantes del proceso: clientes/prospectos (cuentas) y
    actores externos (proveedores por clasificación), en un solo catálogo (R-T-01)."""
    tenant_id = current_user["tenant_id"]
    result: list[dict] = []

    accounts = (
        db.query(Account)
        .filter(
            Account.tenant_id == tenant_id,
            Account.company_id == company_id,
            Account.deleted_at.is_(None),
        )
        .all()
    )
    for acc in accounts:
        acc_role = getattr(acc, "record_type", None) or "cliente"
        if role and role not in (acc_role, "exportador", "importador"):
            # Las cuentas representan exportador/importador/cliente; sólo se omiten
            # cuando el filtro pide explícitamente un rol de proveedor.
            if role not in ("exportador", "importador", "cliente", "prospecto"):
                continue
        result.append({
            "id": acc.id,
            "source": "account",
            "name": acc.name,
            "role": acc_role,
            "roles": [acc_role],
        })

    suppliers = (
        db.query(Supplier)
        .filter(
            Supplier.tenant_id == tenant_id,
            Supplier.company_id == company_id,
            Supplier.deleted_at.is_(None),
        )
        .all()
    )
    for sup in suppliers:
        classifications = sup.classifications or []
        if role and role not in classifications:
            continue
        result.append({
            "id": sup.id,
            "source": "supplier",
            "name": sup.name,
            "role": classifications[0] if classifications else "proveedor",
            "roles": classifications,
        })

    return result
