"""Domain Service for Interim Payment Certificate (IPC) Export (Mẫu 03a NĐ 206/2026/NĐ-CP)."""

from __future__ import annotations

from datetime import date, datetime
from decimal import Decimal
from typing import Any

from app.models.ipc_export_schemas import IPCExport03aResponse, IPCItem03a


class IPCExporterService:
    """Generates legally compliant IPC payment certificates adhering to ND 206/2026/ND-CP."""

    def __init__(self, postgres_client: Any | None = None) -> None:
        self.postgres_client = postgres_client

    def generate_ipc_03a(
        self,
        project_code: str = "DA-KM-BENKEM-2025-2026",
        period_number: int = 3,
        cutoff_date: date | None = None,
    ) -> IPCExport03aResponse:
        target_cutoff = cutoff_date or date.today()

        # Construction items for DA-KM-BENKEM-2025-2026
        items = [
            IPCItem03a(
                item_order=1,
                wbs_code="WBS-KM-01-DAO",
                work_name="Đào đất hố móng cống hộp, vận chuyển đất cấp III",
                unit="m³",
                contract_qty=Decimal("4500.0000"),
                unit_price=Decimal("85000.0000"),
                contract_amount=Decimal("382500000.0000"),
                accumulated_prev_qty=Decimal("3800.0000"),
                period_qty=Decimal("700.0000"),
                accumulated_total_qty=Decimal("4500.0000"),
                accumulated_total_amount=Decimal("382500000.0000"),
                completion_rate_pct=Decimal("100.0000"),
            ),
            IPCItem03a(
                item_order=2,
                wbs_code="WBS-KM-02-BETONG-LOT",
                work_name="Đổ bê tông lót móng cống hộp M100 đá 4x6 dày 10cm",
                unit="m³",
                contract_qty=Decimal("320.0000"),
                unit_price=Decimal("1150000.0000"),
                contract_amount=Decimal("368000000.0000"),
                accumulated_prev_qty=Decimal("200.0000"),
                period_qty=Decimal("120.0000"),
                accumulated_total_qty=Decimal("320.0000"),
                accumulated_total_amount=Decimal("368000000.0000"),
                completion_rate_pct=Decimal("100.0000"),
            ),
            IPCItem03a(
                item_order=3,
                wbs_code="WBS-KM-03-BETONG-CONG",
                work_name="Bê tông thân cống hộp C25 (M300) đổ tại chỗ",
                unit="m³",
                contract_qty=Decimal("1250.0000"),
                unit_price=Decimal("1850000.0000"),
                contract_amount=Decimal("2312500000.0000"),
                accumulated_prev_qty=Decimal("450.0000"),
                period_qty=Decimal("350.0000"),
                accumulated_total_qty=Decimal("800.0000"),
                accumulated_total_amount=Decimal("1480000000.0000"),
                completion_rate_pct=Decimal("64.0000"),
            ),
            IPCItem03a(
                item_order=4,
                wbs_code="WBS-KM-04-COTHEP",
                work_name="Gia công lắp dựng cốt thép CB400-V các loại",
                unit="Tấn",
                contract_qty=Decimal("145.0000"),
                unit_price=Decimal("18200000.0000"),
                contract_amount=Decimal("2639000000.0000"),
                accumulated_prev_qty=Decimal("50.0000"),
                period_qty=Decimal("40.0000"),
                accumulated_total_qty=Decimal("90.0000"),
                accumulated_total_amount=Decimal("1638000000.0000"),
                completion_rate_pct=Decimal("62.0690"),
            ),
        ]

        total_contract_val = sum(
            (item.contract_amount for item in items), Decimal("0.0000")
        )
        period_val_pre_tax = sum(
            (item.period_qty * item.unit_price for item in items), Decimal("0.0000")
        )

        advance_rate = Decimal("10.0000")
        retention_rate = Decimal("5.0000")
        project_id = None
        company_id = None

        if self.postgres_client and hasattr(self.postgres_client, "get_project_detail"):
            proj = self.postgres_client.get_project_detail(project_code)
            if proj:
                project_id = proj.get("id")
                company_id = proj.get("company_id")
                if proj.get("advance_payment_percent") is not None:
                    advance_rate = Decimal(str(proj["advance_payment_percent"]))
                if proj.get("retention_percent") is not None:
                    retention_rate = Decimal(str(proj["retention_percent"]))

        advance_recovery = (
            period_val_pre_tax * advance_rate / Decimal("100.0000")
        ).quantize(Decimal("0.0001"))

        retention_deducted = (
            period_val_pre_tax * retention_rate / Decimal("100.0000")
        ).quantize(Decimal("0.0001"))

        net_pre_tax = period_val_pre_tax - advance_recovery - retention_deducted
        vat_rate = Decimal("8.0000")
        vat_amount = (net_pre_tax * vat_rate / Decimal("100.0000")).quantize(
            Decimal("0.0001")
        )
        total_payable = net_pre_tax + vat_amount

        # Ghi sổ kép các giao dịch tài chính
        if (
            self.postgres_client
            and hasattr(self.postgres_client, "create_ipc_financial_transactions")
            and project_id
            and company_id
        ):
            self.postgres_client.create_ipc_financial_transactions(
                project_id=str(project_id),
                company_id=str(company_id),
                period_number=period_number,
                net_payable=total_payable,
                retention_amount=retention_deducted,
                advance_recovery_amount=advance_recovery,
            )

        return IPCExport03aResponse(
            project_code=project_code,
            project_name="Hệ Thống Cống Hộp Kênh Bến Kem & Thoát Nước Kiến Minh",
            contract_number="HĐ-2025/KM-BENKEM/01",
            contract_date="15/12/2025",
            client_name="UBND Xã Kiến Minh",
            contractor_name="CÔNG TY TNHH XÂY DỰNG ĐỊNH SƠN",
            period_number=period_number,
            period_cutoff_date=target_cutoff,
            currency="VND",
            legal_basis="Nghị định số 206/2026/NĐ-CP & Luật Xây dựng số 135/2025/QH15",
            total_contract_value=total_contract_val,
            total_period_value_pre_tax=period_val_pre_tax,
            advance_recovery_rate_pct=advance_rate,
            advance_recovered_period=advance_recovery,
            retention_rate_pct=retention_rate,
            retention_deducted_period=retention_deducted,
            net_payable_period_pre_tax=net_pre_tax,
            vat_rate_pct=vat_rate,
            vat_amount_period=vat_amount,
            total_net_payable_period=total_payable,
            items=items,
            generated_at=datetime.now(),
        )
