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

from .coa import Account
from .parties import Party


class OpeningCategory(models.TextChoices):
    BANK = "BANK", "Bank Accounts"
    CASH = "CASH", "Cash Vaults & Cash-in-Hand"
    DEBTORS = "DEBTORS", "Sundry Debtors (Customer Receivables)"
    CREDITORS = "CREDITORS", "Sundry Creditors (Supplier Payables)"
    LOANS = "LOANS", "Term & Project Loans"
    OD_CC = "OD_CC", "Overdraft & Cash Credit Facilities"
    FIXED_ASSETS = "FIXED_ASSETS", "Fixed Assets & Machinery"
    ACCUM_DEPRECIATION = "ACCUM_DEPRECIATION", "Accumulated Depreciation"
    INVENTORY = "INVENTORY", "Inventory / Stock"
    EMPLOYEE_ADVANCES = "EMPLOYEE_ADVANCES", "Employee / Staff Advances"
    SUPPLIER_ADVANCES = "SUPPLIER_ADVANCES", "Supplier Advances (Asset)"
    CUSTOMER_ADVANCES = "CUSTOMER_ADVANCES", "Customer Advances (Liability)"
    RETENTION_RECEIVABLE = "RETENTION_RECEIVABLE", "Retention Receivable"
    RETENTION_PAYABLE = "RETENTION_PAYABLE", "Retention Payable"
    TAX_RECEIVABLE = "TAX_RECEIVABLE", "Tax / VAT / TDS Receivable"
    TAX_PAYABLE = "TAX_PAYABLE", "Tax / VAT / TDS Payable"
    EQUITY = "EQUITY", "Equity, Capital & Retained Earnings"
    OTHER = "OTHER", "Other Subsidiary & General Ledgers"


class DirectionChoice(models.TextChoices):
    DR = "DR", "Debit (Dr)"
    CR = "CR", "Credit (Cr)"


class OpeningBalanceProfile(models.Model):
    """Per-company & financial-year conversion cut-off, approval and migration lock controls."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ob_profiles")
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.CASCADE, related_name="ob_profiles")
    conversion_cutoff_date = models.DateField(help_text="Cut-off date for historical opening balances.")
    bs_cutoff_date = models.CharField(max_length=16, blank=True)
    require_approval = models.BooleanField(default=True)
    auto_post_on_create = models.BooleanField(default=True)
    allow_live_midyear_migration = models.BooleanField(default=False)
    default_clearing_account = models.ForeignKey(
        Account, on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
    )
    default_equity_account = models.ForeignKey(
        Account, on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
    )
    is_migration_locked = models.BooleanField(default=False)
    locked_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="+")
    locked_at = models.DateTimeField(null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "ob_profiles"
        unique_together = [("company", "fiscal_year")]


class OpeningBalanceAdjustmentMapping(models.Model):
    """Category-specific Opening Balance Adjustment GL configuration."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ob_mappings")
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.SET_NULL, null=True, blank=True)
    category = models.CharField(max_length=28, choices=OpeningCategory.choices)
    adjustment_account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="ob_adjustment_mappings")
    normal_balance = models.CharField(max_length=4, choices=DirectionChoice.choices, default=DirectionChoice.CR)
    allowed_account_groups = models.JSONField(default=list, blank=True)
    require_approval = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    description = models.CharField(max_length=255, blank=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "ob_adjustment_mappings"
        unique_together = [("company", "category")]
        ordering = ["category"]


class OpeningBalanceVoucher(models.Model):
    class EntryMode(models.TextChoices):
        INDIVIDUAL = "INDIVIDUAL", "Individual Account Opening"
        PARTY = "PARTY", "Party / Bill-Wise Opening"
        BULK_IMPORT = "BULK_IMPORT", "Bulk Excel/CSV Import"
        COMPANY_MIGRATION = "COMPANY_MIGRATION", "Full Company Migration"
        CARRY_FORWARD = "CARRY_FORWARD", "Year-End Carry-Forward"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        SUBMITTED = "SUBMITTED", "Submitted for Review"
        REJECTED = "REJECTED", "Rejected"
        APPROVED = "APPROVED", "Approved"
        POSTED = "POSTED", "Posted to GL"
        REVERSED = "REVERSED", "Reversed"
        RECONCILIATION_PENDING = "RECONCILIATION_PENDING", "Reconciliation Pending"
        FINALIZED = "FINALIZED", "Finalized"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="ob_vouchers")
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT, related_name="ob_vouchers")
    ob_number = models.CharField(max_length=48)
    entry_mode = models.CharField(max_length=24, choices=EntryMode.choices, default=EntryMode.INDIVIDUAL)
    opening_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    currency = models.CharField(max_length=3, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))
    source_entity_type = models.CharField(max_length=48, blank=True)  # BankAccount | CashAccount | Party | Account | EquipmentAsset
    source_entity_id = models.CharField(max_length=64, blank=True)
    is_historical_migration = models.BooleanField(default=True)
    migration_override_reason = models.CharField(max_length=255, blank=True)
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.DRAFT, db_index=True)
    voucher = models.OneToOneField(
        "accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True, related_name="opening_balance_record"
    )
    total_debit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    total_credit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    supporting_doc_ref = models.CharField(max_length=120, blank=True)
    narration = models.TextField(blank=True)
    idempotency_key = models.CharField(max_length=120, blank=True, db_index=True)
    version = models.PositiveIntegerField(default=1)
    prepared_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="prepared_obs")
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="approved_obs")
    posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="posted_obs")
    approved_at = models.DateTimeField(null=True, blank=True)
    posted_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "ob_vouchers"
        unique_together = [("company", "ob_number")]
        ordering = ["-opening_date", "-created_at"]


class OpeningBalanceLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    ob_voucher = models.ForeignKey(OpeningBalanceVoucher, on_delete=models.CASCADE, related_name="lines")
    line_no = models.PositiveSmallIntegerField(default=1)
    account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="ob_lines")
    party = models.ForeignKey(Party, on_delete=models.PROTECT, null=True, blank=True, related_name="ob_lines")
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    opening_category = models.CharField(max_length=28, choices=OpeningCategory.choices, default=OpeningCategory.OTHER)
    direction = models.CharField(max_length=4, choices=DirectionChoice.choices)
    default_direction = models.CharField(max_length=4, choices=DirectionChoice.choices)
    is_direction_overridden = models.BooleanField(default=False)
    override_reason = models.CharField(max_length=255, blank=True)
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    debit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    credit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    currency = models.CharField(max_length=3, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))
    base_debit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    base_credit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    adjustment_account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="ob_counterpart_lines")
    reference_no = models.CharField(max_length=64, blank=True)
    invoice_date = models.DateField(null=True, blank=True)
    due_date = models.DateField(null=True, blank=True)
    narration = models.CharField(max_length=255, blank=True)

    class Meta:
        db_table = "ob_lines"
        ordering = ["line_no"]


class OpeningBalanceSubledgerItem(models.Model):
    """Bill-wise AR/AP opening invoice / advance breakdown materialized into OpenItem on post."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    ob_line = models.ForeignKey(OpeningBalanceLine, on_delete=models.CASCADE, related_name="subledger_items")
    party = models.ForeignKey(Party, on_delete=models.PROTECT)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    doc_kind = models.CharField(max_length=24, default="SALES_INVOICE")
    invoice_ref = models.CharField(max_length=64)
    invoice_date = models.DateField()
    due_date = models.DateField()
    original_amount = models.DecimalField(max_digits=18, decimal_places=2)
    settled_before_cutoff = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    outstanding_amount = models.DecimalField(max_digits=18, decimal_places=2)
    currency = models.CharField(max_length=3, default="NPR")
    exchange_rate = models.DecimalField(max_digits=14, decimal_places=6, default=Decimal("1.000000"))
    contract_ref = models.CharField(max_length=64, blank=True)
    open_item = models.ForeignKey("party_hub.OpenItem", on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        db_table = "ob_subledger_items"
        ordering = ["invoice_date", "invoice_ref"]


class OpeningBalancePartyReference(models.Model):
    """Tracks distinct bill/contract reference uniqueness & summary per party migration."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.CASCADE)
    party = models.ForeignKey(Party, on_delete=models.CASCADE, related_name="ob_references")
    reference_no = models.CharField(max_length=64)
    classification = models.CharField(max_length=28)  # DEBTOR | CREDITOR | CUSTOMER_ADVANCE | SUPPLIER_ADVANCE
    opening_amount = models.DecimalField(max_digits=18, decimal_places=2)
    ob_voucher = models.ForeignKey(OpeningBalanceVoucher, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "ob_party_references"
        unique_together = [("company", "fiscal_year", "party", "reference_no")]


class OpeningBalanceImport(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT)
    batch_name = models.CharField(max_length=150)
    total_rows = models.PositiveIntegerField(default=0)
    valid_rows = models.PositiveIntegerField(default=0)
    error_rows = models.PositiveIntegerField(default=0)
    status = models.CharField(max_length=24, default="VALIDATED")  # VALIDATED | HAS_ERRORS | CONVERTED
    ob_voucher = models.ForeignKey(OpeningBalanceVoucher, on_delete=models.SET_NULL, null=True, blank=True)
    uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

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


class OpeningBalanceImportLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    batch = models.ForeignKey(OpeningBalanceImport, on_delete=models.CASCADE, related_name="rows")
    row_no = models.PositiveIntegerField()
    account_code = models.CharField(max_length=32)
    party_code = models.CharField(max_length=32, blank=True)
    opening_date = models.DateField(null=True, blank=True)
    debit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    credit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    currency = models.CharField(max_length=3, default="NPR")
    reference_no = models.CharField(max_length=64, blank=True)
    due_date = models.DateField(null=True, blank=True)
    is_valid = models.BooleanField(default=True)
    error_message = models.CharField(max_length=255, blank=True)

    class Meta:
        db_table = "ob_import_lines"
        ordering = ["row_no"]


class OpeningBalanceApproval(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    ob_voucher = models.ForeignKey(OpeningBalanceVoucher, on_delete=models.CASCADE, related_name="approvals")
    decision = models.CharField(max_length=16)  # SUBMITTED | APPROVED | REJECTED
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    comment = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

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


class OpeningBalanceReconciliation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    fiscal_year = models.ForeignKey("tenancy.FiscalYear", on_delete=models.PROTECT)
    reconciliation_date = models.DateField()
    recon_kind = models.CharField(max_length=24, default="CLEARING")  # BANK_OPENING | CASH_PHYSICAL | AR_CONTROL | AP_CONTROL | CLEARING
    reference_label = models.CharField(max_length=150)
    book_balance = models.DecimalField(max_digits=18, decimal_places=2)
    external_balance = models.DecimalField(max_digits=18, decimal_places=2)  # Bank stmt balance or Physical cash count or Subledger sum
    deposits_in_transit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    unpresented_cheques = 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"))
    status = models.CharField(max_length=20, default="RECONCILED")  # RECONCILED | VARIANCE_OPEN | APPROVED
    explanation = models.TextField(blank=True)
    evidence_ref = models.CharField(max_length=120, blank=True)
    reconciled_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "ob_reconciliations"
        ordering = ["-reconciliation_date", "-created_at"]


class OpeningBalanceCorrection(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    original_ob_voucher = models.ForeignKey(OpeningBalanceVoucher, on_delete=models.PROTECT, related_name="corrections")
    reversal_ob_voucher = models.ForeignKey(
        OpeningBalanceVoucher, on_delete=models.PROTECT, null=True, blank=True, related_name="reversal_for_correction"
    )
    replacement_ob_voucher = models.ForeignKey(
        OpeningBalanceVoucher, on_delete=models.PROTECT, null=True, blank=True, related_name="replacement_for_correction"
    )
    correction_type = models.CharField(max_length=32, default="AMOUNT_OR_DIRECTION")  # RECLASSIFICATION | AMOUNT_OR_DIRECTION | PARTY_CORRECTION | FX_ADJUSTMENT
    original_amount = models.DecimalField(max_digits=18, decimal_places=2)
    original_direction = models.CharField(max_length=4, choices=DirectionChoice.choices)
    corrected_amount = models.DecimalField(max_digits=18, decimal_places=2)
    corrected_direction = models.CharField(max_length=4, choices=DirectionChoice.choices)
    reason = models.TextField()
    supporting_doc_ref = models.CharField(max_length=120, blank=True)
    approved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

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


class OpeningBalanceAuditEvent(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    action = models.CharField(max_length=48, db_index=True)
    entity_type = models.CharField(max_length=48)
    entity_id = models.CharField(max_length=64)
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True)
    previous_state = models.JSONField(null=True, blank=True, encoder=DjangoJSONEncoder)
    new_state = models.JSONField(null=True, blank=True, encoder=DjangoJSONEncoder)
    notes = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

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


class FinancialYearOpeningCarryForward(models.Model):
    """Prevents duplicate year-end opening carry-forward across consecutive financial years."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="fy_carry_forwards")
    source_fiscal_year = models.ForeignKey(
        "tenancy.FiscalYear", on_delete=models.PROTECT, related_name="carry_forwards_out"
    )
    target_fiscal_year = models.ForeignKey(
        "tenancy.FiscalYear", on_delete=models.PROTECT, related_name="carry_forwards_in"
    )
    carry_forward_date = models.DateField()
    ob_voucher = models.OneToOneField(OpeningBalanceVoucher, on_delete=models.PROTECT)
    total_debit = models.DecimalField(max_digits=18, decimal_places=2)
    total_credit = models.DecimalField(max_digits=18, decimal_places=2)
    accounts_carried = models.PositiveIntegerField(default=0)
    open_items_carried = models.PositiveIntegerField(default=0)
    status = models.CharField(max_length=16, default="POSTED")
    executed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "ob_fy_carry_forwards"
        unique_together = [("company", "source_fiscal_year", "target_fiscal_year")]

