"""
Endpoints API para fracciones arancelarias americanas (solo lectura; fuente SITAR).
"""

from datetime import datetime, timezone
from typing import Any, Dict, Optional

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

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

from api.v1.modules.sitar.fracciones_usa.catalog_resolve import (
    american_fraction_ad_valorem_from_row,
    canonical_code_from_sitar_row,
)
from api.v1.modules.sitar.fracciones_usa.schemas import FraccionesUSAResponse
from api.v1.modules.sitar.fracciones_usa.service import FraccionesUSAService

from .dto import USTariffFractionResponseDTO


def _sitar_row_to_us_response_payload(item: FraccionesUSAResponse) -> dict:
    """Build payload for USTariffFractionResponseDTO.model_validate (SITAR row)."""
    canon = canonical_code_from_sitar_row(item)
    now = datetime.now(timezone.utc)
    return {
        "id": item.CONSECUTIVO,
        "code": canon,
        "fraction": item.FRACCION_CON_PUNTO or item.FRACCION_MOSTRAR or canon,
        "prefix": item.FRACCION_SIN_PUNTO,
        "type_code": str(item.NIVEL) if item.NIVEL is not None else None,
        "ad_valorem": american_fraction_ad_valorem_from_row(item),
        "fixed_cost": None,
        "unit_of_measure": item.UNIDADCANTIDAD,
        "description": item.DESCRIPCION,
        "created_at": now,
        "updated_at": now,
    }


main_router = APIRouter(
    prefix="/us-tariff-fractions",
    tags=["a76 / general catalogs / us tariff fractions"],
)


@main_router.api_route(
    "/imports",
    methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
    include_in_schema=False,
)
@main_router.api_route(
    "/imports/{path:path}",
    methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
    include_in_schema=False,
)
async def us_tariff_imports_disabled(path: str = ""):
    raise HTTPException(
        status_code=status.HTTP_410_GONE,
        detail="CSV import for US tariff fractions is disabled; catalog is read-only from SITAR.",
    )


@main_router.get(
    "/",
    response_model=Dict[str, Any],
    summary="List US Tariff Fractions",
    description="Paginated list from SITAR fracciones-usa (read-only).",
)
async def list_us_tariff_fractions(
    company_id: int = Query(..., description="Company ID"),
    page: int = Query(1, ge=1, description="Page number"),
    page_size: int = Query(50, ge=1, le=10000, description="Page size"),
    search: Optional[str] = Query(None, description="Search in code or description"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["frac_sitar_us.view"]
    )

    skip = (page - 1) * page_size
    try:
        svc = FraccionesUSAService.get_instance()
    except ValueError:
        return {
            "items": [],
            "total": 0,
            "page": page,
            "page_size": page_size,
            "pages": 0,
        }

    search_term = None
    search_description = None
    if search:
        clean = search.replace(".", "")
        if clean.isdigit() and len(clean) >= 4:
            search_term = search
        else:
            search_description = search

    try:
        sitar_items, total = await svc.search_with_total(
            fraccion=search_term,
            descripcion=search_description,
            skip=skip,
            limit=page_size,
        )
    except Exception:
        return {
            "items": [],
            "total": 0,
            "page": page,
            "page_size": page_size,
            "pages": 0,
        }

    items = [
        USTariffFractionResponseDTO.model_validate(_sitar_row_to_us_response_payload(row))
        for row in sitar_items
    ]

    return {
        "items": items,
        "total": total,
        "page": page,
        "page_size": page_size,
        "pages": (total + page_size - 1) // page_size,
    }


@main_router.post("/")
async def create_us_tariff_fraction_disabled():
    raise HTTPException(
        status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
        detail="US tariff fractions are read-only (SITAR).",
    )


@main_router.put("/{fraction_id}")
async def update_us_tariff_fraction_disabled(fraction_id: int):
    raise HTTPException(
        status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
        detail="US tariff fractions are read-only (SITAR).",
    )


@main_router.delete("/{fraction_id}")
async def delete_us_tariff_fraction_disabled(fraction_id: int):
    raise HTTPException(
        status_code=status.HTTP_405_METHOD_NOT_ALLOWED,
        detail="US tariff fractions are read-only (SITAR).",
    )


router = main_router
