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

from apps.audit.services import record_audit_event


class TreasurySettings(models.Model):
    class ChequeAccountingMode(models.TextChoices):
        CHEQUES_IN_HAND = "CHEQUES_IN_HAND", "Two-Step Cheques-in-Hand Asset Clearing"
        DIRECT_BANK = "DIRECT_BANK", "Direct Bank GL on Receipt"

    class ImprestPolicy(models.TextChoices):
        FIXED_REPLENISHMENT = "FIXED_REPLENISHMENT", "Fixed Imprest Limit (Replenish Verified Spend Only)"
        FLEXIBLE = "FLEXIBLE", "Flexible Advance Settlement"

    class DayCountBasis(models.TextChoices):
        ACT_365 = "ACT_365", "Actual / 365"
        ACT_360 = "ACT_360", "Actual / 360"
        ACT_ACT = "ACT_ACT", "Actual / Actual"
        THIRTY_360 = "30_360", "30 / 360"
        FIXED_30 = "FIXED_30", "Fixed 30-Day Month"
        CALENDAR_MONTH = "CALENDAR_MONTH", "Actual Calendar Month"
        CONTRACT_MONTHLY = "CONTRACT_MONTHLY", "Contractual Monthly Rate"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.OneToOneField("tenancy.Company", on_delete=models.CASCADE, related_name="treasury_settings")
    cheque_accounting_mode = models.CharField(
        max_length=24, choices=ChequeAccountingMode.choices, default=ChequeAccountingMode.CHEQUES_IN_HAND
    )
    imprest_policy = models.CharField(
        max_length=24, choices=ImprestPolicy.choices, default=ImprestPolicy.FIXED_REPLENISHMENT
    )
    default_day_count_basis = models.CharField(
        max_length=20, choices=DayCountBasis.choices, default=DayCountBasis.ACT_365
    )
    reconcile_date_tolerance_days = models.PositiveSmallIntegerField(default=3)
    reconcile_amount_tolerance = models.DecimalField(max_digits=12, decimal_places=2, default=Decimal("0.00"))
    dual_auth_threshold_npr = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("500000.00"))
    auto_sync_nrb_fx = models.BooleanField(default=True)
    lock_reconciled_periods = models.BooleanField(default=True)
    require_fx_override_approval = models.BooleanField(default=True)
    fx_override_tolerance_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("1.50"))
    stale_cheque_days = models.PositiveSmallIntegerField(default=180)
    clearing_delay_alert_days = models.PositiveSmallIntegerField(default=5)
    require_cheque_issue_approval = models.BooleanField(default=False)
    require_bounce_reversal_approval = models.BooleanField(default=False)
    strict_drawer_duplicate_block = models.BooleanField(default=True)
    cheques_in_hand_account = models.ForeignKey(
        "accounting.Account", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
    )
    cheques_in_clearing_account = models.ForeignKey(
        "accounting.Account", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
    )
    cheque_return_charge_account = models.ForeignKey(
        "accounting.Account", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
    )
    default_fx_rate_type = models.CharField(max_length=16, default="NRB_SELL")
    auto_reverse_unrealized_fx = models.BooleanField(default=False)
    # Enterprise Bank, Loan, OD/CC, BG & Collateral Studio Controls
    bg_expiry_alert_days = models.CharField(max_length=48, default="90,60,30,15,7")
    default_bg_commission_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("1.50"))
    default_bg_margin_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("10.00"))
    require_bg_release_proof = models.BooleanField(default=True)
    require_rate_override_approval = models.BooleanField(default=True)
    od_utilization_alert_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("85.00"))
    collateral_reval_interval_days = models.PositiveSmallIntegerField(default=365)
    interest_rounding_mode = models.CharField(max_length=16, default="HALF_UP")
    interest_decimal_places = models.PositiveSmallIntegerField(default=2)
    require_collateral_val_evidence = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "treasury_settings"


class TreasuryApprovalRequest(models.Model):
    class RequestKind(models.TextChoices):
        BANK_MASTER_CHANGE = "BANK_MASTER_CHANGE", "Bank Account Master Edit / Freeze / Close"
        IMPREST_ISSUE = "IMPREST_ISSUE", "Imprest Advance Authorization"
        IMPREST_SETTLEMENT = "IMPREST_SETTLEMENT", "Imprest Expense Settlement"
        CASH_HANDOVER = "CASH_HANDOVER", "Physical Cash Custody Handover"
        FX_OVERRIDE = "FX_OVERRIDE", "FX Manual Rate Override"
        RECON_REOPEN = "RECON_REOPEN", "Reopen Locked Reconciliation"
        OD_EXCESS = "OD_EXCESS", "OD/CC Limit Excess Exception"
        LOAN_REVISION = "LOAN_REVISION", "Loan Schedule / Rate Revision"
        CHEQUE_ISSUE = "CHEQUE_ISSUE", "High-Value Cheque Issuance Authorization"
        CHEQUE_BOUNCE_REVERSAL = "CHEQUE_BOUNCE_REVERSAL", "Bounced Cheque Reversal Approval"
        CHEQUE_STOP_PAYMENT = "CHEQUE_STOP_PAYMENT", "Cheque Stop-Payment Authorization"
        BG_ISSUE = "BG_ISSUE", "Bank Guarantee Issuance Authorization"
        BG_RELEASE = "BG_RELEASE", "Bank Guarantee Release & Margin Refund"
        COLLATERAL_RELEASE = "COLLATERAL_RELEASE", "Collateral Security Discharge"
        INTEREST_POSTING = "INTEREST_POSTING", "Loan / OD Interest Posting Approval"

    class Status(models.TextChoices):
        PENDING = "PENDING", "Pending 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, related_name="treasury_approvals")
    request_kind = models.CharField(max_length=28, choices=RequestKind.choices, db_index=True)
    entity_type = models.CharField(max_length=64)
    entity_id = models.CharField(max_length=64)
    title = models.CharField(max_length=200)
    payload = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    reason = models.TextField(blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.PENDING, db_index=True)
    requested_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="requested_treasury_approvals"
    )
    decided_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="decided_treasury_approvals"
    )
    decision_comment = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    decided_at = models.DateTimeField(null=True, blank=True)

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


class TreasuryAuditLog(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="treasury_audit_logs")
    module = models.CharField(max_length=32, db_index=True)
    action = models.CharField(max_length=64, db_index=True)
    entity_type = models.CharField(max_length=64)
    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 = "treasury_audit_logs"
        ordering = ["-created_at"]


def record_treasury_audit(
    *,
    company,
    module: str,
    action: str,
    entity_type: str,
    entity_id: str,
    actor=None,
    previous_state: dict | None = None,
    new_state: dict | None = None,
    notes: str = "",
):
    TreasuryAuditLog.objects.create(
        company=company,
        module=module,
        action=action,
        entity_type=entity_type,
        entity_id=str(entity_id),
        actor=actor,
        previous_state=previous_state,
        new_state=new_state,
        notes=notes[:255],
    )
    record_audit_event(
        company=company,
        actor=actor,
        action=action,
        entity_type=f"Treasury:{entity_type}",
        entity_id=str(entity_id),
        previous_state=previous_state,
        new_state=new_state,
    )


class TreasuryConfigHistory(models.Model):
    """Immutable version history for every Treasury Configuration Studio parameter change."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="treasury_config_history")
    version_no = models.PositiveIntegerField(default=1)
    section = models.CharField(max_length=32, default="PREFERENCES")  # BANK | LOAN | OD_CC | BG | COLLATERAL | PREFERENCES
    setting_key = models.CharField(max_length=64)
    previous_value = models.TextField(blank=True)
    new_value = models.TextField(blank=True)
    effective_date = models.DateField(null=True, blank=True)
    change_reason = models.CharField(max_length=255, blank=True)
    changed_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="+")
    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 = "treasury_config_history"
        ordering = ["-created_at", "-version_no"]


class TreasuryAlert(models.Model):
    """Persisted & acknowledged Treasury executive risk alerts."""

    class Severity(models.TextChoices):
        INFO = "INFO", "Info"
        WARNING = "WARNING", "Warning"
        CRITICAL = "CRITICAL", "Critical"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="treasury_alerts")
    alert_code = models.CharField(max_length=48, db_index=True)
    severity = models.CharField(max_length=12, choices=Severity.choices, default=Severity.WARNING)
    title = models.CharField(max_length=200)
    message = models.TextField()
    entity_type = models.CharField(max_length=48, blank=True)
    entity_id = models.CharField(max_length=64, blank=True)
    route_key = models.CharField(max_length=64, default="loans:dashboard")
    due_date = models.DateField(null=True, blank=True)
    is_resolved = models.BooleanField(default=False)
    resolved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True)
    resolved_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "treasury_alerts"
        ordering = ["is_resolved", "-created_at"]


from .cheques.models import (  # noqa: E402, F401
    ChequeAlert,
    ChequeApproval,
    ChequeAttachment,
    ChequeAuditLog,
    ChequeCancellation,
    ChequeClearingEvent,
    ChequeDepositBatch,
    ChequeDepositLine,
    ChequeReplacement,
    ChequeReturn,
    ChequeReversal,
    IssuedCheque,
    ReceivedCheque,
)


