from __future__ import annotations

"""Nạp định mức vật tư dự toán thực tế (BoQ Quotas) cho các dự án đang thi công của Định Sơn."""

import logging
from decimal import Decimal
from app.core.postgres.erp_client import ErpDatabaseClient

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger("IngestRealBoQQuotas")

REAL_BOQ_DATA = [
    # 1. Dự án Nhà văn hóa Thôn Đại Thắng (DA-2608281122 - Dân dụng)
    {
        "project_code": "DA-2608281122",
        "materials": [
            {
                "material_code": "MAT-TON-045",
                "material_name": "Tôn mạ màu dày 0.45 mm",
                "material_group": "ROOFING",
                "unit": "kg",
                "boq_quantity": Decimal("730.0000"),
                "unit_price_boq_vnd": Decimal("24200.0000"),
                "total_budget_boq_vnd": Decimal("17666000.0000"),
            },
            {
                "material_code": "MAT-THEP-HOP",
                "material_name": "Thép hộp mạ kẽm 40x80x1.8x6000",
                "material_group": "STEEL",
                "unit": "kg",
                "boq_quantity": Decimal("410.0000"),
                "unit_price_boq_vnd": Decimal("16100.0000"),
                "total_budget_boq_vnd": Decimal("6601000.0000"),
            },
            {
                "material_code": "MAT-XM-PCB30",
                "material_name": "Xi măng bao PCB30",
                "material_group": "CEMENT",
                "unit": "kg",
                "boq_quantity": Decimal("35000.0000"),
                "unit_price_boq_vnd": Decimal("1566.6700"),
                "total_budget_boq_vnd": Decimal("54833450.0000"),
            },
            {
                "material_code": "MAT-GACH-XAY",
                "material_name": "Gạch xây không nung",
                "material_group": "BRICK",
                "unit": "Viên",
                "boq_quantity": Decimal("25000.0000"),
                "unit_price_boq_vnd": Decimal("1400.0000"),
                "total_budget_boq_vnd": Decimal("35000000.0000"),
            },
            {
                "material_code": "MAT-CAT-VANG",
                "material_name": "Cát vàng xây trát và bê tông",
                "material_group": "SAND",
                "unit": "m3",
                "boq_quantity": Decimal("45.0000"),
                "unit_price_boq_vnd": Decimal("380000.0000"),
                "total_budget_boq_vnd": Decimal("17100000.0000"),
            },
            {
                "material_code": "MAT-CAT-DEN",
                "material_name": "Cát đen san nền móng K=0.90",
                "material_group": "SAND",
                "unit": "m3",
                "boq_quantity": Decimal("80.0000"),
                "unit_price_boq_vnd": Decimal("215000.0000"),
                "total_budget_boq_vnd": Decimal("17200000.0000"),
            },
            {
                "material_code": "MAT-DA-1X2",
                "material_name": "Đá 1x2 đổ bê tông mác 250",
                "material_group": "STONE",
                "unit": "m3",
                "boq_quantity": Decimal("35.0000"),
                "unit_price_boq_vnd": Decimal("320000.0000"),
                "total_budget_boq_vnd": Decimal("11200000.0000"),
            },
            {
                "material_code": "MAT-THEP-CB400",
                "material_name": "Thép thanh vằn CB400 kết cấu",
                "material_group": "STEEL",
                "unit": "kg",
                "boq_quantity": Decimal("4500.0000"),
                "unit_price_boq_vnd": Decimal("16450.0000"),
                "total_budget_boq_vnd": Decimal("74025000.0000"),
            },
        ],
    },
    # 2. Dự án Hệ thống cống hộp kênh Bến Kem (DA-KM-BENKEM-2025-2026 - Hạ tầng & Thủy lợi)
    {
        "project_code": "DA-KM-BENKEM-2025-2026",
        "materials": [
            {
                "material_code": "MAT-XM-PCB40-BK",
                "material_name": "Xi măng PCB40 chịu mặn Hoàng Thạch",
                "material_group": "CEMENT",
                "unit": "kg",
                "boq_quantity": Decimal("120000.0000"),
                "unit_price_boq_vnd": Decimal("1650.0000"),
                "total_budget_boq_vnd": Decimal("198000000.0000"),
            },
            {
                "material_code": "MAT-THEP-TRON-BK",
                "material_name": "Cốt thép tròn vằn D16-D22 CB400 cống hộp",
                "material_group": "STEEL",
                "unit": "kg",
                "boq_quantity": Decimal("28000.0000"),
                "unit_price_boq_vnd": Decimal("16200.0000"),
                "total_budget_boq_vnd": Decimal("453600000.0000"),
            },
            {
                "material_code": "MAT-DA-1X2-BK",
                "material_name": "Đá 1x2 đổ bê tông cống hộp M250",
                "material_group": "STONE",
                "unit": "m3",
                "boq_quantity": Decimal("180.0000"),
                "unit_price_boq_vnd": Decimal("320000.0000"),
                "total_budget_boq_vnd": Decimal("57600000.0000"),
            },
            {
                "material_code": "MAT-CAT-VANG-BK",
                "material_name": "Cát vàng hạt lớn bê tông cống",
                "material_group": "SAND",
                "unit": "m3",
                "boq_quantity": Decimal("150.0000"),
                "unit_price_boq_vnd": Decimal("420000.0000"),
                "total_budget_boq_vnd": Decimal("63000000.0000"),
            },
            {
                "material_code": "MAT-CONG-HOP-BK",
                "material_name": "Cấu kiện cống hộp bê tông cốt thép",
                "material_group": "PIPE",
                "unit": "m",
                "boq_quantity": Decimal("250.0000"),
                "unit_price_boq_vnd": Decimal("1450000.0000"),
                "total_budget_boq_vnd": Decimal("362500000.0000"),
            },
            {
                "material_code": "MAT-COC-TRE-BK",
                "material_name": "Cọc tre tươi gia cố đáy móng cống L=2.5m",
                "material_group": "TIMBER",
                "unit": "cọc",
                "boq_quantity": Decimal("3500.0000"),
                "unit_price_boq_vnd": Decimal("18000.0000"),
                "total_budget_boq_vnd": Decimal("63000000.0000"),
            },
        ],
    },
    # 3. Gói thầu số 04: Nạo vét, tu bổ đê kè Sông Đa Độ (DA-DADO-THUYLDT-2022-2026 - Thủy lợi)
    {
        "project_code": "DA-DADO-THUYLDT-2022-2026",
        "materials": [
            {
                "material_code": "MAT-DA-HOC-DD",
                "material_name": "Đá hộc kè mái đê chống xói lở",
                "material_group": "STONE",
                "unit": "m3",
                "boq_quantity": Decimal("500.0000"),
                "unit_price_boq_vnd": Decimal("380000.0000"),
                "total_budget_boq_vnd": Decimal("190000000.0000"),
            },
            {
                "material_code": "MAT-VAI-DIA-DD",
                "material_name": "Vải địa kỹ thuật không dệt ART25",
                "material_group": "GEOTEXTILE",
                "unit": "m2",
                "boq_quantity": Decimal("2500.0000"),
                "unit_price_boq_vnd": Decimal("21500.0000"),
                "total_budget_boq_vnd": Decimal("53750000.0000"),
            },
            {
                "material_code": "MAT-RO-DA-DD",
                "material_name": "Rọ đá mạ kẽm bọc nhựa PVC 2x1x0.5m",
                "material_group": "WIRE_MESH",
                "unit": "cái",
                "boq_quantity": Decimal("350.0000"),
                "unit_price_boq_vnd": Decimal("260000.0000"),
                "total_budget_boq_vnd": Decimal("91000000.0000"),
            },
            {
                "material_code": "MAT-CAT-SAN-DD",
                "material_name": "Cát đắp hoàn trả bờ đê K=0.90",
                "material_group": "SAND",
                "unit": "m3",
                "boq_quantity": Decimal("1200.0000"),
                "unit_price_boq_vnd": Decimal("215000.0000"),
                "total_budget_boq_vnd": Decimal("258000000.0000"),
            },
            {
                "material_code": "MAT-BAT-XAC-RAN-DD",
                "material_name": "Bạt xác rắn chống sạt lở bờ kênh",
                "material_group": "GEOTEXTILE",
                "unit": "m2",
                "boq_quantity": Decimal("1500.0000"),
                "unit_price_boq_vnd": Decimal("12000.0000"),
                "total_budget_boq_vnd": Decimal("18000000.0000"),
            },
        ],
    },
]


def ingest_boq_data():
    db = ErpDatabaseClient()
    logger.info("Bắt đầu nạp định mức vật tư dự toán thực tế vào erp_project_boq_materials...")

    inserted_count = 0
    with db.get_connection() as conn:
        with conn.cursor() as cur:
            for p_data in REAL_BOQ_DATA:
                p_code = p_data["project_code"]
                cur.execute("SELECT id FROM projects WHERE project_code = %s LIMIT 1;", (p_code,))
                row = cur.fetchone()
                if not row:
                    logger.warning(f"Không tìm thấy dự án {p_code} trong CSDL!")
                    continue
                proj_id = str(row["id"])

                insert_sql = """
                    INSERT INTO erp_project_boq_materials (
                        project_id, material_code, material_name, material_group, unit,
                        boq_quantity, unit_price_boq_vnd, total_budget_boq_vnd,
                        invoiced_quantity, invoiced_amount_vnd, allowed_loss_percent, status
                    ) VALUES (
                        %s, %s, %s, %s, %s,
                        %s, %s, %s,
                        0.0000, 0.0000, 3.00, 'active'
                    )
                    ON CONFLICT (project_id, material_code) DO UPDATE
                    SET material_name = EXCLUDED.material_name,
                        material_group = EXCLUDED.material_group,
                        unit = EXCLUDED.unit,
                        boq_quantity = EXCLUDED.boq_quantity,
                        unit_price_boq_vnd = EXCLUDED.unit_price_boq_vnd,
                        total_budget_boq_vnd = EXCLUDED.total_budget_boq_vnd,
                        updated_at = CURRENT_TIMESTAMP;
                """
                for mat in p_data["materials"]:
                    cur.execute(
                        insert_sql,
                        (
                            proj_id,
                            mat["material_code"],
                            mat["material_name"],
                            mat["material_group"],
                            mat["unit"],
                            mat["boq_quantity"],
                            mat["unit_price_boq_vnd"],
                            mat["total_budget_boq_vnd"],
                        ),
                    )
                    inserted_count += 1
                logger.info(f"Đã nạp {len(p_data['materials'])} định mức vật tư cho dự án [{p_code}]")

        conn.commit()

    logger.info(f"Hoàn thành nạp {inserted_count} định mức vật tư BoQ vào CSDL!")


if __name__ == "__main__":
    ingest_boq_data()
