from __future__ import annotations

"""Domain Entities and Value Objects for Warehouse Dispatch & Material Loss/Variance Analytics.
Adheres strictly to DSCons DDD Hexagonal Architecture, Decimal(18, 4) financial precision,
and Vietnam Construction Norms (Thông tư 12/2021/TT-BXD & Định mức 2026).
"""

from datetime import date, datetime
from decimal import Decimal
from enum import Enum
from typing import Optional
from uuid import UUID, uuid4
from pydantic import BaseModel, Field


class VarianceAlertStatus(str, Enum):
    SAFE = "SAFE"                 # Hao hụt <= Định mức chuẩn (Kiểm soát tốt / Tiết kiệm)
    WARNING = "WARNING"           # Hao hụt chênh lệch tiệm cận ngưỡng tối đa
    EXCEEDED = "EXCEEDED"         # Hao hụt vượt định mức nhà nước (Cảnh báo lãng phí/thất thoát)
    NO_ESTIMATE = "NO_ESTIMATE"   # Xuất độc lập, chưa có dự toán liên kết


# Bảng tra cứu định mức hao hụt khâu thi công quy chuẩn (TT12/2021/TT-BXD & Định mức 2026)
NORM_WASTAGE_PERCENTAGES: dict[str, Decimal] = {
    "STEEL": Decimal("2.5"),             # Thép cốt bê tông gia công & lắp dựng (1.5% - 2.5%)
    "CEMENT": Decimal("2.5"),            # Xi măng trộn vữa/bê tông (2.5%)
    "AGGREGATE": Decimal("4.0"),         # Cát vàng, đá dăm, cấp phối đá dăm (3.0% - 5.0%)
    "CONCRETE": Decimal("2.0"),          # Bê tông thương phẩm đổ tại chỗ (1.5% - 2.5%)
    "BRICK": Decimal("3.0"),             # Gạch xây các loại (2.5% - 3.5%)
    "PIPES_FITTINGS": Decimal("1.5"),    # Ống nhựa & phụ kiện (1.0% - 2.0%)
    "FINISHING_PAINT": Decimal("3.0"),   # Sơn & vật liệu chống thấm Sika (2.0% - 4.0%)
    "FUEL_OIL": Decimal("1.0"),          # Nhiên liệu xăng dầu ca máy (0.5% - 1.5%)
    "SAFETY_EQUIPMENT": Decimal("0.0"),  # Đồ bảo hộ / công cụ tái sử dụng
    "OTHER_SUPPLIES": Decimal("2.0"),    # Vật tư khác mặc định 2.0%
}


class WarehouseDispatch(BaseModel):
    """Thực thể Phiếu Xuất Kho Vật Tư Công Trường (Linh hoạt, không cứng nhắc)."""
    id: UUID = Field(default_factory=uuid4)
    inventory_item_id: UUID
    dispatch_code: str
    project_id: Optional[UUID] = None
    wbs_id: Optional[UUID] = None
    takeoff_item_id: Optional[UUID] = None
    dispatch_date: date = Field(default_factory=date.today)
    quantity_dispatched: Decimal = Field(..., max_digits=18, decimal_places=4)
    unit: str
    unit_price_vnd: Decimal = Field(default=Decimal("0.0000"), max_digits=18, decimal_places=4)
    total_value_vnd: Decimal = Field(default=Decimal("0.0000"), max_digits=18, decimal_places=4)
    recipient_name: Optional[str] = None
    transport_vehicle: Optional[str] = None
    purpose: Optional[str] = None
    notes: Optional[str] = None
    created_at: datetime = Field(default_factory=datetime.now)
    updated_at: datetime = Field(default_factory=datetime.now)


class MaterialVarianceItem(BaseModel):
    """Đối tượng giá trị (Value Object) so sánh 3 chiều Dự Toán - Thực Xuất - Quyết Toán & Hao Hụt."""
    material_group: str
    material_name: str
    unit: str
    estimated_quantity: Decimal = Field(default=Decimal("0.0000"), max_digits=18, decimal_places=4)  # Q_đt
    settled_quantity: Decimal = Field(default=Decimal("0.0000"), max_digits=18, decimal_places=4)    # Q_qt
    dispatched_quantity: Decimal = Field(default=Decimal("0.0000"), max_digits=18, decimal_places=4) # Q_tx
    norm_wastage_pct: Decimal = Field(default=Decimal("2.5"), max_digits=8, decimal_places=2)       # Định mức %
    actual_wastage_quantity: Decimal = Field(default=Decimal("0.0000"), max_digits=18, decimal_places=4) # Hao hụt KL
    actual_wastage_pct: Decimal = Field(default=Decimal("0.00"), max_digits=8, decimal_places=2)        # % Thực tế
    variance_status: VarianceAlertStatus = VarianceAlertStatus.SAFE
    unit_price_vnd: Decimal = Field(default=Decimal("0.0000"), max_digits=18, decimal_places=4)
    wastage_cost_vnd: Decimal = Field(default=Decimal("0.0000"), max_digits=18, decimal_places=4)
    evaluation_message: str = ""
