from __future__ import annotations

import logging
from typing import Any
from fastapi import APIRouter, Depends, HTTPException

from app.modules.auth.presentation.auth import get_current_user
from app.modules.invoices.application.invoice_processing.boq_material_allocation_service import (
    BoQMaterialAllocationService,
)

logger = logging.getLogger("BoQAllocationRoutes")

router = APIRouter(
    prefix="/v1/erp/boq-allocations",
    tags=["ERP BoQ Material Allocations"],
)


@router.get("/projects/{project_id}/materials")
def get_project_boq_materials(
    project_id: str,
    current_user: dict[str, Any] = Depends(get_current_user),
):
    """Lấy danh sách định mức vật tư BoQ và hạn mức còn lại của dự án."""
    service = BoQMaterialAllocationService()
    items = service.get_project_boq_materials(project_id)
    return {
        "status": "success",
        "project_id": project_id,
        "materials": items,
        "total_materials_count": len(items),
    }


@router.post("/batch-allocate")
def trigger_batch_allocation(
    current_user: dict[str, Any] = Depends(get_current_user),
):
    """Kích hoạt tiến trình tự động phân bổ toàn bộ hóa đơn Trụ Cột 1 vào dự án."""
    service = BoQMaterialAllocationService()
    try:
        stats = service.batch_allocate_construction_invoices()
        return {
            "status": "success",
            "message": "Hoàn tất phân bổ vật tư dựa trên dự toán BoQ",
            "stats": stats,
        }
    except Exception as e:
        logger.error(f"Lỗi phân bổ BoQ: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/summary")
def get_allocation_summary(
    current_user: dict[str, Any] = Depends(get_current_user),
):
    """Tổng hợp tình hình phân bổ vật tư và cảnh báo vượt định mức BoQ."""
    service = BoQMaterialAllocationService()
    return service.get_allocation_summary()

