import uuid
from decimal import Decimal
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models


class Budget(models.Model):
    class BudgetType(models.TextChoices):
        ANNUAL_COMPANY = "ANNUAL_COMPANY", "Annual Company Budget"
        OPERATING = "OPERATING", "Operating Budget"
        CAPEX = "CAPEX", "Capital Expenditure Budget"
        PROJECT = "PROJECT", "Project Budget"
        SITE = "SITE", "Site Budget"
        DEPARTMENT = "DEPARTMENT", "Department Budget"
        MATERIAL = "MATERIAL", "Material Budget"
        LABOR = "LABOR", "Labor Budget"
        EQUIPMENT = "EQUIPMENT", "Equipment Budget"
        SUBCONTRACT = "SUBCONTRACT", "Subcontract Budget"
        CASH_FLOW = "CASH_FLOW", "Cash Flow Budget"
        CONTINGENCY = "CONTINGENCY", "Contingency Budget"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        SUBMITTED = "SUBMITTED", "Submitted"
        APPROVED = "APPROVED", "Approved"
        LOCKED = "LOCKED", "Locked"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="budgets")
    budget_code = models.CharField(max_length=40)
    title = models.CharField(max_length=200)
    budget_type = models.CharField(max_length=24, choices=BudgetType.choices, default=BudgetType.PROJECT)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT, related_name="budgets")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="budgets")
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    department = models.ForeignKey("accounting.Department", on_delete=models.PROTECT, null=True, blank=True)
    current_version_no = models.PositiveSmallIntegerField(default=1)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT, db_index=True)
    notes = models.TextField(blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_budgets")
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="approved_budgets"
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "budgets"
        unique_together = [("company", "budget_code")]
        ordering = ["-created_at"]

    def __str__(self) -> str:
        return f"{self.budget_code} — {self.title} (v{self.current_version_no})"


class BudgetVersion(models.Model):
    """Immutable historical & baseline versions preserved across revisions."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    budget = models.ForeignKey(Budget, on_delete=models.CASCADE, related_name="versions")
    version_no = models.PositiveSmallIntegerField(default=1)
    is_baseline = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    revision_reason = models.CharField(max_length=255, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    approved_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "budget_versions"
        unique_together = [("budget", "version_no")]
        ordering = ["-version_no"]


class BudgetLine(models.Model):
    class CostCategory(models.TextChoices):
        MATERIAL = "MATERIAL", "Materials"
        LABOR = "LABOR", "Labor"
        EQUIPMENT = "EQUIPMENT", "Equipment"
        SUBCONTRACT = "SUBCONTRACT", "Subcontract"
        OVERHEAD = "OVERHEAD", "Overheads"
        CAPEX = "CAPEX", "Capital Expenditure"
        CONTINGENCY = "CONTINGENCY", "Contingency"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    budget_version = models.ForeignKey(BudgetVersion, on_delete=models.CASCADE, related_name="lines")
    cost_category = models.CharField(max_length=20, choices=CostCategory.choices, default=CostCategory.MATERIAL)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.PROTECT, null=True, blank=True)
    boq_item = models.ForeignKey("accounting.BoqItem", on_delete=models.PROTECT, null=True, blank=True)
    account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, null=True, blank=True)
    description = models.CharField(max_length=200, blank=True)
    approved_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    month_breakdown = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)

    class Meta:
        db_table = "budget_lines"
        ordering = ["cost_category", "id"]

    def __str__(self) -> str:
        return f"{self.budget_version.budget.budget_code} · {self.cost_category} ({self.approved_amount})"


class BudgetCommitment(models.Model):
    """Open commitments reserved by POs/Work Orders and relieved upon 3-way match / voucher posting."""

    class Status(models.TextChoices):
        OPEN = "OPEN", "Open Commitment"
        PARTIALLY_RELIEVED = "PARTIALLY_RELIEVED", "Partially Relieved"
        CLOSED = "CLOSED", "Closed / Converted to Actual"
        CANCELLED = "CANCELLED", "Cancelled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="budget_commitments")
    budget_line = models.ForeignKey(BudgetLine, on_delete=models.PROTECT, related_name="commitments")
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    source_type = models.CharField(max_length=32, default="PURCHASE_ORDER")
    source_id = models.UUIDField(db_index=True)
    source_ref = models.CharField(max_length=64)
    committed_amount = models.DecimalField(max_digits=18, decimal_places=2)
    relieved_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.OPEN)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "budget_commitments"
        ordering = ["-created_at"]

    @property
    def open_amount(self) -> Decimal:
        if self.status in (self.Status.CLOSED, self.Status.CANCELLED):
            return Decimal("0.00")
        rem = self.committed_amount - self.relieved_amount
        return rem if rem > Decimal("0.00") else Decimal("0.00")


class BudgetTransfer(models.Model):
    class Status(models.TextChoices):
        PENDING = "PENDING", "Pending Approval"
        EXECUTED = "EXECUTED", "Approved & Executed"
        REJECTED = "REJECTED", "Rejected"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="budget_transfers")
    transfer_no = models.CharField(max_length=40)
    from_budget_line = models.ForeignKey(BudgetLine, on_delete=models.PROTECT, related_name="outgoing_transfers")
    to_budget_line = models.ForeignKey(BudgetLine, on_delete=models.PROTECT, related_name="incoming_transfers")
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    reason = models.CharField(max_length=255)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "budget_transfers"
        unique_together = [("company", "transfer_no")]
        ordering = ["-created_at"]

    def clean(self):
        if self.amount <= 0:
            raise ValidationError("Transfer amount must be positive.")


class ForecastScenario(models.Model):
    class ScenarioKind(models.TextChoices):
        CONSERVATIVE = "CONSERVATIVE", "Conservative"
        EXPECTED = "EXPECTED", "Expected / Baseline"
        OPTIMISTIC = "OPTIMISTIC", "Optimistic"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="forecast_scenarios")
    project = models.ForeignKey("projects.Project", on_delete=models.CASCADE, null=True, blank=True)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT)
    name = models.CharField(max_length=120)
    scenario_kind = models.CharField(max_length=20, choices=ScenarioKind.choices, default=ScenarioKind.EXPECTED)
    projected_revenue = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    projected_cost = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    projected_margin = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    cashflow_projection = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    notes = models.TextField(blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "forecast_scenarios"
        ordering = ["-created_at"]

