from __future__ import annotations

import logging
from typing import Any

from fastapi import (
    APIRouter,
    Depends,
    HTTPException,
    Query,
)

from app.modules.auth.presentation.auth import require_role
from app.core.postgres.erp_client import ErpDatabaseClient

from .schemas import TakeoffItemUpdateRequest

logger = logging.getLogger("dscons.api.takeoff.manage")
router = APIRouter()


@router.put(
    "/items/{item_id}",
    summary="Chỉnh sửa chi tiết một dòng công tác bóc tách khối lượng",
)
def update_takeoff_item(
    item_id: str,
    req: TakeoffItemUpdateRequest,
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "manager", "engineer"])
    ),
) -> dict[str, Any]:
    """Cập nhật số lượng, đơn giá, công thức đo tính của một đầu mục."""
    client = ErpDatabaseClient()
    payload = req.model_dump(exclude_none=True)
    if not payload:
        raise HTTPException(status_code=400, detail="Không có dữ liệu thay đổi")

    # Recalculate total_amount_vnd if quantity or unit_price changed
    if "quantity" in payload or "unit_price_vnd" in payload:
        qty = payload.get("quantity")
        price = payload.get("unit_price_vnd")
        if qty is not None and price is not None:
            payload["total_amount_vnd"] = qty * price

    updated = client.update_drawing_takeoff_item(item_id, payload)
    if not updated:
        raise HTTPException(
            status_code=404, detail="Không tìm thấy dòng bóc tách để cập nhật"
        )

    return {
        "status": "success",
        "message": "Đã cập nhật thành công dòng bóc tách",
        "data": updated,
    }


@router.delete(
    "/clear-all",
    summary="Xóa toàn bộ hồ sơ bóc tách bản vẽ cũ (Dành riêng cho Super Admin / Ban Giám Đốc)",
)
def clear_all_takeoffs(
    project_id: str | None = Query(
        None,
        description="Mã UUID dự án cần xóa toàn bộ bản vẽ (để trống nếu xóa tất cả)",
    ),
    current_user: dict[str, Any] = Depends(require_role(["superadmin", "director"])),
) -> dict[str, Any]:
    """Xóa hàng loạt hồ sơ bóc tách bản vẽ cũ."""
    client = ErpDatabaseClient()
    deleted_count = client.delete_all_drawing_takeoffs(project_id=project_id)
    return {
        "status": "success",
        "message": f"Đã xóa thành công {deleted_count} hồ sơ bóc tách bản vẽ",
        "deleted_count": deleted_count,
    }


@router.delete(
    "/{takeoff_id}",
    summary="Xóa hồ sơ bóc tách bản vẽ",
)
def delete_takeoff(
    takeoff_id: str,
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "manager", "engineer"])
    ),
) -> dict[str, Any]:
    """Xóa hồ sơ bóc tách bản vẽ."""
    client = ErpDatabaseClient()
    ok = client.delete_drawing_takeoff(takeoff_id)
    if not ok:
        raise HTTPException(status_code=404, detail="Không tìm thấy hồ sơ để xóa")
    return {"status": "success", "message": "Đã xóa hồ sơ bóc tách bản vẽ"}


@router.post(
    "/{takeoff_id}/cancel",
    summary="Dừng khẩn cấp tiến trình bóc tách bản vẽ đang chạy hoặc bị treo",
)
def cancel_takeoff(
    takeoff_id: str,
    current_user: dict[str, Any] = Depends(
        require_role(["superadmin", "director", "manager", "engineer"])
    ),
) -> dict[str, Any]:
    """Dừng khẩn cấp tiến trình bóc tách bản vẽ đang chạy và đưa trạng thái về 'failed'."""
    client = ErpDatabaseClient()
    takeoff = client.get_drawing_takeoff(takeoff_id)
    if not takeoff:
        raise HTTPException(status_code=404, detail="Không tìm thấy hồ sơ bản vẽ")

    user_name = (
        current_user.get("full_name") or current_user.get("email") or "Quản trị viên"
    )
    updated = client.update_drawing_takeoff(
        takeoff_id,
        {
            "takeoff_status": "failed",
            "ai_report_message": f"Tiến trình bóc tách đã bị dừng theo yêu cầu của {user_name}. Sếp có thể bấm 'Bóc Tách Lại AI Vision' để chạy lại.",
        },
    )
    return {
        "status": "success",
        "message": "Đã dừng tiến trình bóc tách thành công",
        "takeoff": updated,
    }
