"""REST API router for State Published Prices & Bidding Market Price Comparison."""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter, File, Form, HTTPException, Query, UploadFile, status
from pydantic import BaseModel, Field

from app.modules.inventory.application.state_price_sync_service import StatePriceSyncService

router = APIRouter(
    prefix="/v1/material-prices",
    tags=["Material Price Benchmarks & State Comparison"],
)

service = StatePriceSyncService()


class CustomStatePriceRequest(BaseModel):
    publish_period: str = Field(..., json_schema_extra={"example": "2026-08"})
    region_code: str = Field(..., json_schema_extra={"example": "HAI_PHONG_KHU_VUC_2"})
    material_group: str = Field(..., json_schema_extra={"example": "AGGREGATE"})
    material_code: str = Field(..., json_schema_extra={"example": "TBG-CAT-VANG-BT"})
    material_name: str = Field(
        ..., json_schema_extra={"example": "Cát vàng hạt lớn đổ bê tông"}
    )
    specifications: str | None = Field(None, json_schema_extra={"example": "Mk >= 2.0"})
    unit: str = Field(..., json_schema_extra={"example": "m3"})
    state_unit_price_vnd: float = Field(..., json_schema_extra={"example": 710000.0})
    document_reference: str = Field(
        ...,
        json_schema_extra={
            "example": "Thông báo số 558/TB-SXD ngày 07/08/2026 của Sở Xây dựng Hải Phòng"
        },
    )
    effective_date: str = Field(..., json_schema_extra={"example": "2026-08-01"})
    notes: str | None = None


@router.get("/comparison", response_model=dict[str, Any])
async def get_price_comparison(
    period: str = Query(
        default="2026-08", description="Kỳ thông báo giá (YYYY-MM hoặc YYYY-QX)"
    ),
    region: str = Query(
        default="HAI_PHONG_KHU_VUC_2",
        description="Mã phân vùng (HAI_PHONG_KHU_VUC_2 / HAI_PHONG_KHU_VUC_1)",
    ),
    material_group: str | None = Query(
        default=None,
        description="Lọc theo nhóm vật tư (AGGREGATE, STEEL, CEMENT, CONCRETE, FUEL_OIL, EQUIPMENT_SHIFT...)",
    ),
) -> dict[str, Any]:
    """Lấy bảng đối soát chi tiết song song giữa Đơn giá Nhà nước (Sở Xây Dựng Hải Phòng) và Đơn giá Thị trường DSCons."""
    try:
        data = service.get_price_comparison(
            publish_period=period, region_code=region, material_group=material_group
        )
        return {"status": "success", "data": data}
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Lỗi truy xuất bảng so sánh đơn giá: {exc!s}",
        ) from exc


@router.get("/periods", response_model=dict[str, Any])
async def get_published_periods() -> dict[str, Any]:
    """Lấy danh sách các kỳ Thông báo giá Sở Xây dựng có sẵn trong hệ thống."""
    try:
        periods = service.get_available_periods()
        return {"status": "success", "data": periods}
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Lỗi truy xuất danh mục kỳ thông báo giá: {exc!s}",
        ) from exc


@router.get("/full-catalog", response_model=dict[str, Any])
async def get_full_state_price_catalog(
    period: str = Query(default="2026-08", description="Kỳ thông báo giá (YYYY-MM)"),
    region: str = Query(
        default="HAI_PHONG_KHU_VUC_2",
        description="Phân vùng (HAI_PHONG_KHU_VUC_2 / HAI_PHONG_KHU_VUC_1)",
    ),
    material_group: str | None = Query(
        default=None,
        description="Lọc theo nhóm vật tư (AGGREGATE, STEEL, CEMENT, CONCRETE, EQUIPMENT_SHIFT, LABOR...)",
    ),
    search: str | None = Query(
        default=None,
        description="Tìm kiếm theo từ khóa tên vật liệu, quy cách, mã hiệu",
    ),
    page: int = Query(default=1, ge=1, description="Số trang"),
    limit: int = Query(
        default=200, ge=1, le=1000, description="Số bản ghi trên 1 trang"
    ),
) -> dict[str, Any]:
    """Lấy BẢNG GIÁ CÔNG BỐ SỞ XÂY DỰNG ĐẦY ĐỦ (Toàn bộ 100+ danh mục công bố chính thức từ Sở Xây dựng TP Hải Phòng)."""
    try:
        catalog = service.get_full_state_price_catalog(
            publish_period=period,
            region_code=region,
            material_group=material_group,
            search_query=search,
            page=page,
            limit=limit,
        )
        return {"status": "success", "data": catalog}
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Lỗi truy xuất bảng giá công bố Sở Xây Dựng đầy đủ: {exc!s}",
        ) from exc


@router.get("/export-full-excel")
async def export_full_state_prices_excel(
    period: str = Query(default="2026-08", description="Kỳ thông báo giá (YYYY-MM)"),
    region: str = Query(
        default="HAI_PHONG_KHU_VUC_2",
        description="Phân vùng (HAI_PHONG_KHU_VUC_2 / HAI_PHONG_KHU_VUC_1)",
    ),
):
    """Xuất toàn bộ Bảng giá công bố chính thức Sở Xây dựng Hải Phòng ra file Excel (.xlsx) chuẩn doanh nghiệp."""
    from fastapi import Response

    try:
        excel_bytes = service.export_full_state_prices_to_excel(
            publish_period=period, region_code=region
        )
        filename = f"Bang_Gia_SXD_Hai_Phong_{period}_{region}.xlsx"
        return Response(
            content=excel_bytes,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            headers={
                "Content-Disposition": f'attachment; filename="{filename}"',
            },
        )
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Lỗi xuất file Excel bảng giá công bố Sở Xây Dựng: {exc!s}",
        ) from exc


@router.post("/custom-item", response_model=dict[str, Any])
async def add_or_update_custom_state_price(
    req: CustomStatePriceRequest,
) -> dict[str, Any]:
    """Thêm mới hoặc cập nhật một mục đơn giá công bố Sở Xây Dựng công bố."""
    try:
        from datetime import datetime
        from decimal import Decimal

        eff_date = datetime.strptime(req.effective_date, "%Y-%m-%d").date()
        saved = service.add_or_update_custom_item(
            publish_period=req.publish_period,
            region_code=req.region_code,
            material_group=req.material_group,
            material_code=req.material_code,
            material_name=req.material_name,
            specifications=req.specifications,
            unit=req.unit,
            state_unit_price_vnd=req.state_unit_price_vnd,
            document_reference=req.document_reference,
            effective_date=eff_date,
            notes=req.notes,
        )

        return {
            "status": "success",
            "message": "Đã lưu bản ghi đơn giá Nhà nước thành công!",
            "data": saved,
        }
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Lỗi lưu đơn giá Nhà nước: {exc!s}",
        ) from exc


@router.post("/import-appendix-file")
async def import_official_appendix_file(
    file: UploadFile = File(...),
    period: str = Form(default="2026-08"),
    region: str = Form(default="HAI_PHONG_KHU_VUC_2"),
    document_reference: str | None = Form(default=None),
) -> dict[str, Any]:
    """Upload và import trực tiếp file Phụ lục công bố giá Sở Xây dựng Hải Phòng (.xlsx, .csv)."""
    try:
        content = await file.read()
        res = service.import_appendix_from_excel_or_csv(
            file_bytes=content,
            filename=file.filename or "appendix.xlsx",
            publish_period=period,
            region_code=region,
            document_reference=document_reference,
        )
        return res
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Lỗi xử lý file Phụ lục Sở Xây dựng: {exc!s}",
        ) from exc


@router.post("/sync-from-price-ref")
async def sync_state_prices_from_price_ref() -> dict[str, Any]:
    """Quét và đồng bộ toàn bộ các tệp Phụ lục thông báo giá chính thức trong thư mục Price_Ref vào cơ sở dữ liệu."""
    try:
        from app.modules.inventory.application.official_sxd_ingestion_engine import (
            official_sxd_ingestion_engine,
        )

        upserted_count = official_sxd_ingestion_engine.ingest_to_postgres()
        return {
            "status": "success",
            "message": f"Đã quét và nạp thành công {upserted_count:,} danh mục vật tư, ca máy và nhân công trực tiếp từ thư mục Price_Ref!",
            "total_items": upserted_count,
        }
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Lỗi đồng bộ dữ liệu từ Price_Ref: {exc!s}",
        ) from exc


@router.post("/crawl-and-sync")
async def crawl_and_sync_sxd_material_prices(
    max_announcements: int = Query(
        default=3, ge=1, le=10, description="Số lượng thông báo giá tối đa cần crawl"
    ),
) -> dict[str, Any]:
    """Kích hoạt crawler AIHawk Stealth thu thập tự động thông báo giá Sở Xây dựng và đồng bộ vào CSDL."""
    try:
        from app.modules.inventory.application.crawl_and_sync_sxd_prices_use_case import (
            CrawlAndSyncSxdPricesUseCase,
        )

        use_case = CrawlAndSyncSxdPricesUseCase()
        result = await use_case.execute(max_announcements=max_announcements)
        return result
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Lỗi thu thập giá Sở Xây dựng: {exc!s}",
        ) from exc

