"""Pydantic schemas for the 4 Core Business Pillars of Cong ty TNHH Xay Dung Dinh Son (0202111150)."""

from __future__ import annotations

from datetime import date
from decimal import Decimal
from enum import Enum
from typing import Any

from pydantic import BaseModel, Field


# ---------------------------------------------------------
# ENUMS
# ---------------------------------------------------------
class BusinessPillarCode(str, Enum):
    PILLAR_1_EPC = "PILLAR_1_EPC"  # Thi cong Xay lap & Thuy loi (15 Du an)
    PILLAR_2_FLEET = (
        "PILLAR_2_FLEET"  # Van tai Xe Ben & Logistics (Thoat Nuoc HP 0200149705)
    )
    PILLAR_3_EQUIPMENT = (
        "PILLAR_3_EQUIPMENT"  # Cho thue May moc & Ca may (Loan Khai 0201889988)
    )
    PILLAR_4_MATERIALS = (
        "PILLAR_4_MATERIALS"  # Mua ban Vat tu & San lap (Trung Kien 0201805660)
    )


class DispatchOrderStatus(str, Enum):
    SCHEDULED = "SCHEDULED"
    IN_TRANSIT = "IN_TRANSIT"
    DELIVERED = "DELIVERED"
    RECONCILED = "RECONCILED"
    CANCELLED = "CANCELLED"


class ShiftLogVerificationStatus(str, Enum):
    PENDING_VERIFICATION = "PENDING_VERIFICATION"
    MATCHED = "MATCHED"
    DISCREPANCY = "DISCREPANCY"
    APPROVED = "APPROVED"


class QualityCertStatus(str, Enum):
    VALID = "VALID"
    MISSING = "MISSING"
    EXPIRED = "EXPIRED"
    REJECTED = "REJECTED"


# ---------------------------------------------------------
# TRỤ CỘT 1: THI CÔNG XÂY LẮP & THỦY LỢI (EPC)
# ---------------------------------------------------------
class IPCItemPayload(BaseModel):
    item_order: int
    wbs_code: str
    work_name: str
    unit: str
    contract_qty: Decimal = Field(default=Decimal("0.0000"))
    unit_price: Decimal = Field(default=Decimal("0.0000"))
    period_qty: Decimal = Field(default=Decimal("0.0000"))
    accumulated_prev_qty: Decimal = Field(default=Decimal("0.0000"))


class IPC03aExportRequest(BaseModel):
    project_code: str = "DA-KM-BENKEM-2025-2026"
    period_number: int = 3
    cutoff_date: date | None = None
    advance_recovery_rate_pct: Decimal = Field(default=Decimal("10.0000"))
    retention_rate_pct: Decimal = Field(default=Decimal("5.0000"))
    vat_rate_pct: Decimal = Field(default=Decimal("8.0000"))


class IPCDocumentDetail(BaseModel):
    certificate_code: str
    project_code: str
    project_name: str
    investor_name: str
    contractor_name: str = "CÔNG TY TNHH XÂY DỰNG ĐỊNH SƠN"
    contractor_tax_id: str = "0202111150"
    period_number: int
    cutoff_date: date
    legal_basis: str = (
        "Nghị định 206/2026/NĐ-CP & Luật Xây dựng 2025 (Luật 135/2025/QH15)"
    )
    items: list[dict[str, Any]]
    total_contract_value: Decimal
    period_work_value_pre_tax: Decimal
    accumulated_work_value_pre_tax: Decimal
    advance_recovery_amount: Decimal
    retention_deducted_amount: Decimal
    net_payable_pre_tax: Decimal
    vat_amount: Decimal
    total_net_payable_with_vat: Decimal
    currency: str = "VND"


class ThreeWayMatchDetailResponse(BaseModel):
    match_id: str
    project_code: str
    project_name: str
    wbs_code: str
    boq_quantity: Decimal
    site_acceptance_quantity: Decimal
    invoice_billed_quantity: Decimal
    material_consumed_quantity: Decimal
    unit_price: Decimal
    quantity_variance: Decimal
    amount_variance: Decimal
    status: str
    is_compliant: bool
    explanation: str


# ---------------------------------------------------------
# TRỤ CỘT 2: DỊCH VỤ VẬN TẢI & XE BEN LOGISTICS
# ---------------------------------------------------------
class DispatchOrderCreateRequest(BaseModel):
    truck_plate: str  # e.g., "15C-389.22"
    driver_name: str
    partner_tax_id: str = "0200149705"  # Cty Thoát Nước Hải Phòng
    partner_name: str = "Công ty TNHH MTV Thoát nước Hải Phòng"
    cargo_type: str = "Bùn thải nạo vét cống ngầm"
    source_location: str = "Mương An Kim Hải / Cống hộp Lê Chân"
    dump_location: str = "Bãi đổ bùn thải Đình Vũ"
    scheduled_trips: int = 4
    estimated_volume_m3: Decimal = Decimal("48.0000")


class DispatchOrderRecord(BaseModel):
    order_code: str
    dispatch_date: date
    truck_plate: str
    driver_name: str
    partner_tax_id: str
    partner_name: str
    cargo_type: str
    source_location: str
    dump_location: str
    scheduled_trips: int
    completed_trips: int
    weighed_volume_m3: Decimal
    fuel_standard_liters: Decimal
    fuel_actual_liters: Decimal
    fuel_variance_pct: Decimal
    status: DispatchOrderStatus
    notes: str = ""


class SludgeTransportReconciliation(BaseModel):
    partner_tax_id: str = "0200149705"
    partner_name: str = "Công ty TNHH MTV Thoát nước Hải Phòng"
    billing_period: str = "2026-Q1"
    total_trips: int
    total_volume_weighed_m3: Decimal
    unit_price_per_m3: Decimal = Field(default=Decimal("145000.0000"))
    total_amount_pre_tax: Decimal
    invoiced_amount: Decimal
    amount_variance: Decimal
    reconciliation_status: str
    discrepancy_explanation: str


# ---------------------------------------------------------
# TRỤ CỘT 3: CHO THUÊ MÁY MÓC & CA MÁY CƠ GIỚI
# ---------------------------------------------------------
class ShiftLogCreateRequest(BaseModel):
    equipment_code: str  # e.g., "EXC-KOBELCO-02"
    partner_tax_id: str = "0201889988"  # Cty Loan Khải
    operator_name: str
    shift_date: date
    hours_worked: Decimal = Field(default=Decimal("8.0000"))
    work_description: str = "Đào móng kênh dẫn và bạt taluy đắp bờ"
    fuel_consumed_liters: Decimal = Field(default=Decimal("152.0000"))
    hourly_rate_vnd: Decimal = Field(default=Decimal("650000.0000"))


class RentalContractReconciliation(BaseModel):
    partner_tax_id: str = "0201889988"
    partner_name: str = "Công ty TNHH Vận tải và Thương mại Loan Khải"
    equipment_code: str
    equipment_name: str
    total_shift_hours_logged: Decimal
    operator_timesheet_hours: Decimal
    invoiced_rental_hours: Decimal
    hourly_rate: Decimal
    total_earned_vnd: Decimal
    invoiced_amount_vnd: Decimal
    hours_discrepancy: Decimal
    oee_percentage: Decimal
    status: ShiftLogVerificationStatus
    notes: str


# ---------------------------------------------------------
# TRỤ CỘT 4: MUA BÁN VẬT TƯ & SAN LẤP
# ---------------------------------------------------------
class MaterialLossAuditRecord(BaseModel):
    supplier_tax_id: str = "0201805660"
    supplier_name: str = "Công ty Cổ phần Xây dựng Thương mại và Dịch vụ Trung Kiên"
    material_code: str  # e.g., "MAT-CAT-DEN"
    material_name: str  # Cát đen san lấp
    unit: str  # m3, tấn
    purchased_quantity: Decimal
    site_received_quantity: Decimal
    actual_loss_quantity: Decimal
    actual_loss_rate_pct: Decimal
    standard_loss_norm_pct: Decimal = Field(
        default=Decimal("3.0000")
    )  # Định mức hao hụt 12/2021/BXD
    loss_variance_pct: Decimal
    is_within_norm: bool
    financial_loss_impact_vnd: Decimal


class QualityCertificateAuditItem(BaseModel):
    invoice_number: str
    material_name: str
    supplier_tax_id: str
    supplier_name: str
    co_cq_status: QualityCertStatus
    concrete_r28_test_status: QualityCertStatus
    steel_tensile_test_status: QualityCertStatus
    payment_cleared: bool
    audit_notes: str


class QualityCertAuditSummaryResponse(BaseModel):
    total_invoices_audited: int
    fully_compliant_count: int
    missing_cocq_count: int
    missing_lab_test_count: int
    held_payments_value_vnd: Decimal
    records: list[QualityCertificateAuditItem]
