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 apps.localization.bs_calendar import ad_to_bs
from apps.localization.tax import validate_nepal_pan


class PartyGroup(models.Model):
    """Customer and Supplier classification groups with default GL control mapping and terms."""

    class HubScope(models.TextChoices):
        DEBTOR = "DEBTOR", "Sundry Debtor / Customer Group"
        CREDITOR = "CREDITOR", "Sundry Creditor / Supplier Group"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="party_groups")
    hub_scope = models.CharField(max_length=16, choices=HubScope.choices, db_index=True)
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=160)
    default_control_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="party_group_controls"
    )
    default_payment_terms_days = models.PositiveSmallIntegerField(default=30)
    description = models.CharField(max_length=255, blank=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "party_groups"
        unique_together = [("company", "hub_scope", "code")]
        ordering = ["hub_scope", "code"]

    def __str__(self) -> str:
        return f"{self.hub_scope}:{self.code} — {self.name}"


class CustomerProfile(models.Model):
    """
    1:1 Customer / Contract Client extension over accounting.Party (parallel to procurement.VendorProfile).
    Preserves zero master duplication while storing AR contracts, tax class, credit holds & onboarding state.
    """

    class Category(models.TextChoices):
        GOVERNMENT = "GOVERNMENT", "Government / Public Authority"
        PRIVATE = "PRIVATE", "Private Developer / Client"
        CORPORATE = "CORPORATE", "Corporate & Industrial"
        INDIVIDUAL = "INDIVIDUAL", "Individual Client"

    class TaxClass(models.TextChoices):
        VAT_REGISTERED = "VAT_REGISTERED", "VAT Registered (13%)"
        PAN_ONLY = "PAN_ONLY", "PAN Only (Non-VAT)"
        TAX_EXEMPT = "TAX_EXEMPT", "Tax Exempt / Diplomatic"
        EXPORT = "EXPORT", "Zero-Rated / Export"

    class ApprovalStatus(models.TextChoices):
        PENDING = "PENDING", "Pending Approval"
        APPROVED = "APPROVED", "Approved"
        SUSPENDED = "SUSPENDED", "Suspended"
        BLACKLISTED = "BLACKLISTED", "Blacklisted"

    class RiskClass(models.TextChoices):
        LOW = "LOW", "Low Credit Risk"
        MODERATE = "MODERATE", "Moderate Credit Risk"
        HIGH = "HIGH", "High Credit Risk"
        CRITICAL = "CRITICAL", "Critical / Restricted"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="customer_profiles")
    party = models.OneToOneField("accounting.Party", on_delete=models.PROTECT, related_name="customer_profile")
    parent_customer = models.ForeignKey(
        "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="subsidiaries"
    )
    group = models.ForeignKey(PartyGroup, on_delete=models.SET_NULL, null=True, blank=True, related_name="customers")
    legal_name = models.CharField(max_length=200, blank=True)
    customer_category = models.CharField(max_length=20, choices=Category.choices, default=Category.PRIVATE)
    registration_no = models.CharField(max_length=64, blank=True)
    tax_classification = models.CharField(max_length=20, choices=TaxClass.choices, default=TaxClass.VAT_REGISTERED)
    pan_vat_no = models.CharField(max_length=20, blank=True, db_index=True)
    tds_applicable = models.BooleanField(default=True)
    default_tds_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("1.50"))
    default_retention_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("5.00"))
    default_currency = models.CharField(max_length=8, default="NPR")
    contract_number = models.CharField(max_length=64, blank=True)
    agreement_date = models.DateField(null=True, blank=True)
    contract_value = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    credit_days = models.PositiveSmallIntegerField(default=30)
    credit_hold = models.BooleanField(default=False)
    govt_contract_exempt_credit = models.BooleanField(default=False)
    is_blacklisted = models.BooleanField(default=False)
    blacklist_reason = models.CharField(max_length=255, blank=True)
    risk_classification = models.CharField(max_length=16, choices=RiskClass.choices, default=RiskClass.LOW)
    required_approval_level = models.CharField(max_length=40, default="FINANCE_MANAGER")
    contract_required = models.BooleanField(default=False)
    supporting_docs_required = models.BooleanField(default=False)
    collection_officer = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="assigned_debtors"
    )
    website = models.URLField(blank=True)
    notes = models.TextField(blank=True)
    duplicate_override_reason = models.CharField(max_length=255, blank=True)
    bank_name = models.CharField(max_length=120, blank=True)
    bank_account_no = models.CharField(max_length=48, blank=True)
    approval_status = models.CharField(
        max_length=16, choices=ApprovalStatus.choices, default=ApprovalStatus.APPROVED, db_index=True
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="approved_customers"
    )
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "customer_profiles"
        ordering = ["party__name"]

    def clean(self):
        if self.pan_vat_no:
            if not validate_nepal_pan(self.pan_vat_no):
                raise ValidationError({"pan_vat_no": "Nepal PAN/VAT must be a 9-digit number."})
            dup = CustomerProfile.objects.filter(company=self.company, pan_vat_no=self.pan_vat_no).exclude(pk=self.pk)
            if dup.exists() and not (self.duplicate_override_reason or "").strip():
                raise ValidationError({"pan_vat_no": f"Duplicate customer PAN/VAT {self.pan_vat_no} already registered."})

    def __str__(self) -> str:
        return f"{self.party.code} — {self.party.name}"


class CustomerContact(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    customer = models.ForeignKey(CustomerProfile, on_delete=models.CASCADE, related_name="contacts")
    name = models.CharField(max_length=120)
    designation = models.CharField(max_length=80, blank=True)
    phone = models.CharField(max_length=40, blank=True)
    email = models.EmailField(blank=True)
    is_primary = models.BooleanField(default=False)

    class Meta:
        db_table = "customer_contacts"


class CustomerAddress(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    customer = models.ForeignKey(CustomerProfile, on_delete=models.CASCADE, related_name="addresses")
    label = models.CharField(max_length=80, default="Head Office / Billing")
    address_line = models.CharField(max_length=255)
    province = models.CharField(max_length=80, blank=True)
    district = models.CharField(max_length=80, blank=True)
    local_level = models.CharField(max_length=120, blank=True)
    ward = models.CharField(max_length=16, blank=True)
    city = models.CharField(max_length=80, blank=True)
    country = models.CharField(max_length=80, default="Nepal")
    is_billing = models.BooleanField(default=True)
    is_site = models.BooleanField(default=False)

    class Meta:
        db_table = "customer_addresses"


class CustomerDocument(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    customer = models.ForeignKey(CustomerProfile, on_delete=models.CASCADE, related_name="documents")
    doc_type = models.CharField(max_length=64)
    doc_number = models.CharField(max_length=64, blank=True)
    file_ref = models.CharField(max_length=255, blank=True)
    issue_date = models.DateField(null=True, blank=True)
    expiry_date = models.DateField(null=True, blank=True)

    class Meta:
        db_table = "customer_documents"


class PartyControlMap(models.Model):
    """Explicit Debtors & Creditors control account mapping per Company and PartyType / PartyGroup."""

    class HubSide(models.TextChoices):
        RECEIVABLE = "RECEIVABLE", "Sundry Debtors (AR) Control"
        PAYABLE = "PAYABLE", "Sundry Creditors (AP) Control"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="party_control_maps")
    hub_side = models.CharField(max_length=16, choices=HubSide.choices, db_index=True)
    party_type = models.CharField(max_length=20)
    party_group = models.ForeignKey(PartyGroup, on_delete=models.SET_NULL, null=True, blank=True)
    control_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, related_name="hub_control_mappings"
    )
    retention_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="hub_retention_mappings"
    )
    advance_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="hub_advance_mappings"
    )
    writeoff_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="hub_writeoff_mappings"
    )
    is_default = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "party_control_maps"
        unique_together = [("company", "hub_side", "party_type", "party_group")]


class OpenItem(models.Model):
    """
    Materialized open receivable/payable or unallocated cash/note record tied strictly 1:1 to a POSTED Voucher
    touching a party control account. Prevents silent auto-clearing and powers real-time aging & allocations.
    """

    class HubSide(models.TextChoices):
        RECEIVABLE = "RECEIVABLE", "Receivable (Debtor)"
        PAYABLE = "PAYABLE", "Payable (Creditor)"

    class DocKind(models.TextChoices):
        SALES_INVOICE = "SALES_INVOICE", "Sales / Tax Invoice"
        PROFORMA_INVOICE = "PROFORMA_INVOICE", "Proforma Invoice"
        CLIENT_RA_BILL = "CLIENT_RA_BILL", "Client RA / Progress Bill"
        FINAL_BILL = "FINAL_BILL", "Final Contract Bill"
        VARIATION_CLAIM = "VARIATION_CLAIM", "Variation / Escalation Claim"
        PURCHASE_INVOICE = "PURCHASE_INVOICE", "Supplier Purchase Invoice"
        SUBCONTRACTOR_BILL = "SUBCONTRACTOR_BILL", "Subcontractor RA Bill"
        CREDIT_NOTE = "CREDIT_NOTE", "Credit Note"
        DEBIT_NOTE = "DEBIT_NOTE", "Debit Note"
        RECEIPT = "RECEIPT", "Customer Receipt (Unallocated Cash)"
        PAYMENT = "PAYMENT", "Supplier Payment (Unallocated Cash)"
        ADJUSTMENT = "ADJUSTMENT", "Authorized Control Adjustment"

    class Status(models.TextChoices):
        OPEN = "OPEN", "Open"
        PARTIAL = "PARTIAL", "Partially Settled"
        SETTLED = "SETTLED", "Fully Settled"
        DISPUTED = "DISPUTED", "Disputed / Held"
        WRITTEN_OFF = "WRITTEN_OFF", "Written Off"
        REVERSED = "REVERSED", "Reversed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="open_items")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="open_items")
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, related_name="open_items")
    control_account = models.ForeignKey("accounting.Account", on_delete=models.PROTECT, related_name="open_items")
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="open_items")
    purchase_order = models.ForeignKey(
        "procurement.PurchaseOrder", on_delete=models.SET_NULL, null=True, blank=True, related_name="open_items"
    )
    grn = models.ForeignKey(
        "inventory.GoodsReceiptNote", on_delete=models.SET_NULL, null=True, blank=True, related_name="open_items"
    )
    hub_side = models.CharField(max_length=16, choices=HubSide.choices, db_index=True)
    doc_kind = models.CharField(max_length=24, choices=DocKind.choices, db_index=True)
    is_unallocated_credit = models.BooleanField(
        default=False,
        help_text="True for Receipts, Payments, and Notes carrying unallocated credit awaiting explicit bill allocation.",
    )
    is_certified = models.BooleanField(default=True)
    document_no = models.CharField(max_length=64, db_index=True)
    contract_ref = models.CharField(max_length=64, blank=True)
    document_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    due_date = models.DateField(db_index=True)
    currency = models.CharField(max_length=3, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))

    gross_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    tax_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    tds_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    retention_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    advance_recovered = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    other_deductions = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))

    original_amount = models.DecimalField(max_digits=18, decimal_places=2)
    allocated_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    written_off_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))

    status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN, db_index=True)
    collection_owner = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="assigned_open_items"
    )
    expected_settlement_date = models.DateField(null=True, blank=True)
    notes = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "open_items"
        unique_together = [("voucher", "party", "control_account", "is_unallocated_credit", "document_no")]
        ordering = ["due_date", "document_date", "document_no"]

    @property
    def remaining_amount(self) -> Decimal:
        rem = self.original_amount - self.allocated_amount - self.written_off_amount
        return rem if rem > Decimal("0.00") else Decimal("0.00")

    def recompute_status(self, save: bool = True) -> None:
        if self.status in (self.Status.REVERSED,):
            return
        rem = self.remaining_amount
        if self.written_off_amount > Decimal("0.00") and rem <= Decimal("0.00"):
            new_status = self.Status.WRITTEN_OFF
        elif rem <= Decimal("0.00"):
            new_status = self.Status.SETTLED
        elif self.disputes.filter(status__in=["OPEN", "UNDER_REVIEW", "ESCALATED"]).exists():
            new_status = self.Status.DISPUTED
        elif self.allocated_amount > Decimal("0.00") or self.written_off_amount > Decimal("0.00"):
            new_status = self.Status.PARTIAL
        else:
            new_status = self.Status.OPEN
        self.status = new_status
        if save:
            self.save(update_fields=["status", "allocated_amount", "written_off_amount", "updated_at"])

    def save(self, *args, **kwargs):
        if self.document_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.document_date).isoformat()
        if not self.due_date:
            self.due_date = self.document_date
        super().save(*args, **kwargs)


class RetentionSchedule(models.Model):
    """Dedicated Contract Retention Receivable & Retention Payable schedule separate from normal invoices."""

    class Direction(models.TextChoices):
        RECEIVABLE = "RECEIVABLE", "Retention Receivable (From Client)"
        PAYABLE = "PAYABLE", "Retention Payable (To Subcontractor/Supplier)"

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

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="retention_schedules")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="retention_schedules")
    direction = models.CharField(max_length=16, choices=Direction.choices, db_index=True)
    source_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, related_name="retention_schedules")
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    contract_ref = models.CharField(max_length=64, blank=True)
    certificate_no = models.CharField(max_length=64, blank=True)
    retention_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("5.00"))
    retention_amount = models.DecimalField(max_digits=18, decimal_places=2)
    released_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    hold_date = models.DateField()
    bs_hold_date = models.CharField(max_length=16, blank=True)
    release_milestone = models.CharField(max_length=160, default="Completion & Defect Liability Expiry")
    defect_liability_end_date = models.DateField(null=True, blank=True)
    release_due_date = models.DateField(null=True, blank=True)
    is_disputed = models.BooleanField(default=False)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.HELD, db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "retention_schedules"
        unique_together = [("source_voucher", "party", "direction")]
        ordering = ["release_due_date", "hold_date"]

    @property
    def remaining_retention(self) -> Decimal:
        rem = self.retention_amount - self.released_amount
        return rem if rem > Decimal("0.00") else Decimal("0.00")

    def save(self, *args, **kwargs):
        if self.hold_date and not self.bs_hold_date:
            self.bs_hold_date = ad_to_bs(self.hold_date).isoformat()
        super().save(*args, **kwargs)


class RetentionReleaseLog(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    retention = models.ForeignKey(RetentionSchedule, on_delete=models.CASCADE, related_name="releases")
    release_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT)
    released_amount = models.DecimalField(max_digits=18, decimal_places=2)
    release_date = models.DateField()
    remarks = models.CharField(max_length=255, blank=True)
    released_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    released_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "retention_release_logs"


class CollectionActivity(models.Model):
    """Accounts Receivable collection follow-ups, promises-to-pay, overdue notices & escalations."""

    class ActivityType(models.TextChoices):
        CALL = "CALL", "Phone Follow-up"
        EMAIL = "EMAIL", "Email / Statement Sent"
        SITE_VISIT = "SITE_VISIT", "Client / Engineer Meeting"
        DEMAND_NOTICE = "DEMAND_NOTICE", "Formal Overdue Notice"
        ESCALATION = "ESCALATION", "Management Escalation"

    class Status(models.TextChoices):
        OPEN = "OPEN", "Follow-up Open"
        PROMISED = "PROMISED", "Payment Promised"
        COMPLETED = "COMPLETED", "Collected / Closed"
        ESCALATED = "ESCALATED", "Escalated"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="collection_activities")
    party = models.ForeignKey("accounting.Party", on_delete=models.CASCADE, related_name="collection_activities")
    open_item = models.ForeignKey(OpenItem, on_delete=models.SET_NULL, null=True, blank=True, related_name="collection_activities")
    assigned_to = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="assigned_collections"
    )
    activity_type = models.CharField(max_length=20, choices=ActivityType.choices, default=ActivityType.CALL)
    contacted_at = models.DateField()
    bs_contacted_at = models.CharField(max_length=16, blank=True)
    promised_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    promised_date = models.DateField(null=True, blank=True)
    next_followup_date = models.DateField(null=True, blank=True)
    outcome = models.CharField(max_length=255)
    notes = models.TextField(blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN, db_index=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="logged_collections")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "collection_activities"
        ordering = ["-contacted_at", "-created_at"]

    def save(self, *args, **kwargs):
        if self.contacted_at and not self.bs_contacted_at:
            self.bs_contacted_at = ad_to_bs(self.contacted_at).isoformat()
        super().save(*args, **kwargs)


class PaymentProposal(models.Model):
    """Accounts Payable payment planner verifying bank liquidity, priority, disputes & authority approval."""

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft Schedule"
        SUBMITTED = "SUBMITTED", "Submitted for Approval"
        APPROVED = "APPROVED", "Approved by Finance Authority"
        EXECUTED = "EXECUTED", "Payment Voucher(s) 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="payment_proposals")
    proposal_no = models.CharField(max_length=40)
    proposal_date = models.DateField()
    bs_date = models.CharField(max_length=16, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    bank_account = models.ForeignKey("banking.BankAccount", on_delete=models.PROTECT, related_name="payment_proposals")
    available_bank_balance = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_proposed = 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)
    notes = models.TextField(blank=True)
    prepared_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="prepared_payment_proposals"
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="approved_payment_proposals"
    )
    executed_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="executed_proposals"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "payment_proposals"
        unique_together = [("company", "proposal_no")]
        ordering = ["-proposal_date", "-created_at"]

    def save(self, *args, **kwargs):
        if self.proposal_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.proposal_date).isoformat()
        super().save(*args, **kwargs)


class PaymentProposalLine(models.Model):
    class Priority(models.TextChoices):
        URGENT = "URGENT", "Urgent / Critical Site"
        HIGH = "HIGH", "High Priority"
        NORMAL = "NORMAL", "Normal Due"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    proposal = models.ForeignKey(PaymentProposal, on_delete=models.CASCADE, related_name="lines")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT)
    open_item = models.ForeignKey(OpenItem, on_delete=models.PROTECT, related_name="proposal_lines")
    priority = models.CharField(max_length=12, choices=Priority.choices, default=Priority.NORMAL)
    proposed_amount = models.DecimalField(max_digits=18, decimal_places=2)
    discount_captured = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    tds_applicable = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    remarks = models.CharField(max_length=255, blank=True)

    class Meta:
        db_table = "payment_proposal_lines"


class PartyDispute(models.Model):
    """Invoice / RA / Retention dispute tracking preventing premature settlement or payment."""

    class HubSide(models.TextChoices):
        RECEIVABLE = "RECEIVABLE", "Debtor / Client Dispute"
        PAYABLE = "PAYABLE", "Creditor / Vendor Dispute"

    class DisputeType(models.TextChoices):
        QUALITY = "QUALITY", "Material / Work Quality"
        QUANTITY_VARIATION = "QUANTITY_VARIATION", "Measurement / BOQ Variance"
        RATE_MISMATCH = "RATE_MISMATCH", "Contract Rate Mismatch"
        TAX_DEDUCTION = "TAX_DEDUCTION", "VAT / TDS Discrepancy"
        DOCUMENTATION = "DOCUMENTATION", "Missing Certification / Challan"
        RETENTION = "RETENTION", "Defect Liability / Retention"

    class Status(models.TextChoices):
        OPEN = "OPEN", "Open Dispute"
        UNDER_REVIEW = "UNDER_REVIEW", "Under Review"
        RESOLVED = "RESOLVED", "Resolved"
        ESCALATED = "ESCALATED", "Escalated"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="party_disputes")
    hub_side = models.CharField(max_length=16, choices=HubSide.choices, db_index=True)
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="disputes")
    open_item = models.ForeignKey(OpenItem, on_delete=models.SET_NULL, null=True, blank=True, related_name="disputes")
    retention = models.ForeignKey(
        RetentionSchedule, on_delete=models.SET_NULL, null=True, blank=True, related_name="disputes"
    )
    dispute_no = models.CharField(max_length=40)
    dispute_type = models.CharField(max_length=24, choices=DisputeType.choices, default=DisputeType.DOCUMENTATION)
    disputed_amount = models.DecimalField(max_digits=18, decimal_places=2)
    claim_ref = models.CharField(max_length=64, blank=True)
    description = models.TextField()
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN, db_index=True)
    resolved_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    resolution_notes = models.TextField(blank=True)
    raised_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="raised_disputes")
    resolved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="resolved_disputes"
    )
    raised_at = models.DateTimeField(auto_now_add=True)
    resolved_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        db_table = "party_disputes"
        unique_together = [("company", "dispute_no")]
        ordering = ["-raised_at"]


class PartyStatement(models.Model):
    """Formal Customer / Supplier Balance Statements & External Confirmation Workflows."""

    class StatementType(models.TextChoices):
        CUSTOMER_STATEMENT = "CUSTOMER_STATEMENT", "Customer Account Statement"
        SUPPLIER_STATEMENT = "SUPPLIER_STATEMENT", "Supplier Account Statement"
        CONFIRMATION_REQUEST = "CONFIRMATION_REQUEST", "Balance Confirmation Statement"

    class ConfirmationStatus(models.TextChoices):
        GENERATED = "GENERATED", "Generated"
        SENT = "SENT", "Sent to Party"
        CONFIRMED = "CONFIRMED", "Confirmed Agreed"
        DISPUTED = "DISPUTED", "Exception / Disputed"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="party_statements")
    party = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="statements")
    statement_no = models.CharField(max_length=48)
    statement_type = models.CharField(max_length=28, choices=StatementType.choices, db_index=True)
    from_date = models.DateField()
    to_date = models.DateField()
    opening_balance = models.DecimalField(max_digits=18, decimal_places=2)
    closing_balance = models.DecimalField(max_digits=18, decimal_places=2)
    overdue_balance = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    retention_balance = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    advance_balance = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    confirmation_status = models.CharField(
        max_length=16, choices=ConfirmationStatus.choices, default=ConfirmationStatus.GENERATED, db_index=True
    )
    confirmed_by_name = models.CharField(max_length=120, blank=True)
    confirmation_notes = models.TextField(blank=True)
    confirmed_at = models.DateTimeField(null=True, blank=True)
    document_record = models.ForeignKey(
        "document_engine.DocumentRecord", on_delete=models.SET_NULL, null=True, blank=True
    )
    generated_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

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


class PartyReconciliationRun(models.Model):
    """Control-account GL vs. Subledger & Open-Item verification snapshot."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="party_reconciliations")
    run_no = models.CharField(max_length=40)
    as_of_date = models.DateField()
    is_reconciled = models.BooleanField(default=True)
    summary_payload = models.JSONField(default=dict, encoder=DjangoJSONEncoder)
    exception_count = models.PositiveIntegerField(default=0)
    run_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

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


class PartyReconciliationException(models.Model):
    class Severity(models.TextChoices):
        CRITICAL = "CRITICAL", "GL vs Subledger Variance"
        WARNING = "WARNING", "Open-Item / Allocation Warning"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    reconciliation_run = models.ForeignKey(
        PartyReconciliationRun, on_delete=models.CASCADE, related_name="exceptions"
    )
    control_role = models.CharField(max_length=32)
    account_code = models.CharField(max_length=32, blank=True)
    party = models.ForeignKey("accounting.Party", on_delete=models.SET_NULL, null=True, blank=True)
    gl_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    subledger_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    variance_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    severity = models.CharField(max_length=16, choices=Severity.choices, default=Severity.CRITICAL)
    description = models.CharField(max_length=255)
    is_resolved = models.BooleanField(default=False)

    class Meta:
        db_table = "party_reconciliation_exceptions"


from .models_ar import *  # noqa: F401, F403

