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

from .project_master import CostCode, Project


class ProjectContract(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.OneToOneField(Project, on_delete=models.CASCADE, related_name="contract")
    contract_no = models.CharField(max_length=80)
    original_contract_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    approved_contract_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    approved_cost_budget = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    retention_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("5.00"))
    retention_ceiling = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    retention_on_vat = models.BooleanField(default=False)
    mobilization_advance_permitted = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    mobilization_advance_received = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    advance_recovery_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("10.00"))
    advance_guarantee_ref = models.CharField(max_length=80, blank=True)
    performance_guarantee_ref = models.CharField(max_length=80, blank=True)
    insurance_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    insurance_policy_no = models.CharField(max_length=80, blank=True)
    insurance_expiry_date = models.DateField(null=True, blank=True)
    liquidated_damages_rate_pct = models.DecimalField(max_digits=6, decimal_places=3, default=Decimal("0.050"))
    liquidated_damages_cap_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("10.00"))
    price_escalation_enabled = models.BooleanField(default=False)
    price_escalation_formula = models.CharField(max_length=255, blank=True)
    tax_treatment = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    payment_terms = models.CharField(max_length=255, default="Monthly Interim Payment Certificate (30 Days)")
    contract_conditions = models.TextField(blank=True)
    clauses = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    is_closed = models.BooleanField(default=False)
    version = models.PositiveIntegerField(default=1)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "project_contracts"

    def recalculate_approved_value(self, save: bool = True) -> Decimal:
        approved_vars = self.project.variations.filter(status=ProjectVariationOrder.Status.APPROVED)
        additions = sum((v.additional_value for v in approved_vars), Decimal("0.00"))
        reductions = sum((v.reduction_value for v in approved_vars), Decimal("0.00"))
        self.approved_contract_value = max(Decimal("0.00"), self.original_contract_value + additions - reductions)
        if save:
            self.save(update_fields=["approved_contract_value", "updated_at"])
            Project.objects.filter(pk=self.project_id).update(approved_contract_value=self.approved_contract_value)
        return self.approved_contract_value


class ProjectContractAmendment(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    contract = models.ForeignKey(ProjectContract, on_delete=models.CASCADE, related_name="amendments")
    amendment_no = models.CharField(max_length=48)
    version = models.PositiveIntegerField(default=1)
    previous_approved_value = models.DecimalField(max_digits=18, decimal_places=2)
    new_approved_value = models.DecimalField(max_digits=18, decimal_places=2)
    time_extension_days = models.IntegerField(default=0)
    summary = models.CharField(max_length=255)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    approved_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_contract_amendments"
        ordering = ["-version", "-approved_at"]


class ProjectVariationOrder(models.Model):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        SUBMITTED = "SUBMITTED", "Pending Client Approval"
        APPROVED = "APPROVED", "Approved"
        REJECTED = "REJECTED", "Rejected"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="variations")
    variation_no = models.CharField(max_length=48)
    contract_ref = models.CharField(max_length=80, blank=True)
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True)
    reason = models.CharField(max_length=255, blank=True)
    boq_changes = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    additional_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    reduction_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    time_extension_days = models.IntegerField(default=0)
    cost_budget_impact = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT, db_index=True)
    client_approval_ref = models.CharField(max_length=80, blank=True)
    contract_amendment_no = models.CharField(max_length=48, blank=True)
    supporting_doc_ref = models.CharField(max_length=255, blank=True)
    submitted_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="submitted_variations"
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="approved_variations"
    )
    approved_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_variations"
        unique_together = [("project", "variation_no")]
        ordering = ["-created_at"]

    @property
    def net_value_impact(self) -> Decimal:
        return self.additional_value - self.reduction_value


class ProjectMilestone(models.Model):
    class MilestoneKind(models.TextChoices):
        CONTRACT_SIGNING = "CONTRACT_SIGNING", "Contract Signing"
        ADVANCE_PAYMENT = "ADVANCE_PAYMENT", "Advance Payment"
        SITE_HANDOVER = "SITE_HANDOVER", "Site Handover"
        MOBILIZATION = "MOBILIZATION", "Mobilization"
        COMMENCEMENT = "COMMENCEMENT", "Commencement"
        FOUNDATION = "FOUNDATION", "Foundation Completion"
        STRUCTURAL = "STRUCTURAL", "Structural Completion"
        DELIVERY = "DELIVERY", "Major Delivery Milestone"
        TESTING_COMMISSIONING = "TESTING_COMMISSIONING", "Testing & Commissioning"
        PRACTICAL_COMPLETION = "PRACTICAL_COMPLETION", "Practical Completion"
        FINAL_HANDOVER = "FINAL_HANDOVER", "Final Handover"
        DEFECTS_LIABILITY = "DEFECTS_LIABILITY", "Defects Liability Completion"
        FINAL_SETTLEMENT = "FINAL_SETTLEMENT", "Final Account Settlement"

    class ApprovalStatus(models.TextChoices):
        PENDING = "PENDING", "Pending"
        IN_PROGRESS = "IN_PROGRESS", "In Progress"
        SUBMITTED = "SUBMITTED", "Submitted for Approval"
        APPROVED = "APPROVED", "Approved / Completed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="milestones")
    milestone_kind = models.CharField(max_length=28, choices=MilestoneKind.choices, default=MilestoneKind.DELIVERY)
    title = models.CharField(max_length=160)
    planned_date = models.DateField(null=True, blank=True)
    revised_date = models.DateField(null=True, blank=True)
    actual_date = models.DateField(null=True, blank=True)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    completion_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    evidence_ref = models.CharField(max_length=255, blank=True)
    approval_status = models.CharField(max_length=16, choices=ApprovalStatus.choices, default=ApprovalStatus.PENDING)
    sequence = models.PositiveSmallIntegerField(default=1)

    class Meta:
        db_table = "project_milestones"
        ordering = ["sequence", "planned_date"]


class ProjectRetention(models.Model):
    class Direction(models.TextChoices):
        RECEIVABLE = "RECEIVABLE", "Client Retention Receivable"
        PAYABLE = "PAYABLE", "Contractor Retention Payable"

    class Status(models.TextChoices):
        HELD = "HELD", "Held"
        PARTIAL = "PARTIAL", "Partially Released"
        RELEASED = "RELEASED", "Fully Released"
        DISPUTED = "DISPUTED", "Disputed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="retention_records")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, null=True, blank=True)
    retention_schedule = models.ForeignKey(
        "party_hub.RetentionSchedule", on_delete=models.SET_NULL, null=True, blank=True
    )
    direction = models.CharField(max_length=16, choices=Direction.choices, default=Direction.RECEIVABLE)
    retention_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("5.00"))
    retention_ceiling = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    eligible_certified_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    deducted_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    released_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    release_milestone = models.CharField(max_length=160, default="Practical Completion & DLP Expiry")
    defects_liability_months = models.PositiveSmallIntegerField(default=12)
    expected_release_date = models.DateField(null=True, blank=True)
    actual_release_date = models.DateField(null=True, blank=True)
    is_disputed = models.BooleanField(default=False)
    dispute_notes = models.CharField(max_length=255, blank=True)
    document_ref = models.CharField(max_length=160, blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.HELD)
    created_at = models.DateTimeField(auto_now_add=True)

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

    @property
    def balance_amount(self) -> Decimal:
        return max(Decimal("0.00"), self.deducted_amount - self.released_amount)


class ProjectAdvance(models.Model):
    class Direction(models.TextChoices):
        CLIENT_RECEIVED = "CLIENT_RECEIVED", "Client Mobilization Advance (Liability)"
        CONTRACTOR_PAID = "CONTRACTOR_PAID", "Contractor Mobilization Advance (Asset)"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="mobilization_advances")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, null=True, blank=True)
    advance_record = models.ForeignKey(
        "accounting.AdvanceRecord", on_delete=models.SET_NULL, null=True, blank=True
    )
    direction = models.CharField(max_length=20, choices=Direction.choices, default=Direction.CLIENT_RECEIVED)
    permitted_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    approved_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    disbursed_received_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    recovered_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    recovery_rate_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("10.00"))
    bank_guarantee_ref = models.CharField(max_length=80, blank=True)
    bank_guarantee_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    guarantee_expiry_date = models.DateField(null=True, blank=True)
    settlement_date = models.DateField(null=True, blank=True)
    recovery_schedule = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    created_at = models.DateTimeField(auto_now_add=True)

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

    @property
    def outstanding_balance(self) -> Decimal:
        return max(Decimal("0.00"), self.disbursed_received_amount - self.recovered_amount)


class ProjectGuarantee(models.Model):
    class GuaranteeType(models.TextChoices):
        BID_BOND = "BID_BOND", "Bid Bond"
        PERFORMANCE = "PERFORMANCE", "Performance Guarantee"
        ADVANCE_PAYMENT = "ADVANCE_PAYMENT", "Advance Payment Guarantee"
        RETENTION_MONEY = "RETENTION_MONEY", "Retention Money Guarantee"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="project_guarantees")
    bank_guarantee = models.ForeignKey(
        "loans.BankGuarantee", on_delete=models.SET_NULL, null=True, blank=True
    )
    guarantee_type = models.CharField(max_length=24, choices=GuaranteeType.choices)
    guarantee_number = models.CharField(max_length=64)
    issuing_bank = models.CharField(max_length=160)
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    issue_date = models.DateField()
    expiry_date = models.DateField()
    claim_expiry_date = models.DateField(null=True, blank=True)
    status = models.CharField(max_length=20, default="ACTIVE")

    class Meta:
        db_table = "project_guarantees"
        ordering = ["-issue_date"]


class ProjectBudget(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="project_budgets")
    budget = models.ForeignKey("budgeting.Budget", on_delete=models.SET_NULL, null=True, blank=True)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT)
    original_ceiling = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    approved_ceiling = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    estimated_cost_to_complete = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    current_version_no = models.PositiveSmallIntegerField(default=1)
    status = models.CharField(max_length=16, default="APPROVED")
    created_at = models.DateTimeField(auto_now_add=True)

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


class ProjectBudgetVersion(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    project_budget = models.ForeignKey(ProjectBudget, on_delete=models.CASCADE, related_name="versions")
    version_no = models.PositiveSmallIntegerField(default=1)
    ceiling_amount = models.DecimalField(max_digits=18, decimal_places=2)
    reason = models.CharField(max_length=255)
    breakdown = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_budget_versions"
        ordering = ["-version_no"]


class ProjectCostAllocation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="cost_allocations")
    site = models.ForeignKey("projects.Site", on_delete=models.SET_NULL, null=True, blank=True)
    cost_code = models.ForeignKey(CostCode, on_delete=models.SET_NULL, null=True, blank=True)
    boq_item = models.ForeignKey("accounting.BoqItem", on_delete=models.SET_NULL, null=True, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    source_type = models.CharField(max_length=32)  # SUPPLIER_BILL | INVENTORY_ISSUE | PAYROLL | SUBCONTRACTOR_BILL | SITE_EXPENSE | EQUIPMENT_HIRE | DEPRECIATION | VOUCHER
    source_ref = models.CharField(max_length=80)
    description = models.CharField(max_length=255, blank=True)
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    posting_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "project_cost_allocations"
        ordering = ["-posting_date", "-created_at"]

