from datetime import date
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils import timezone

from apps.banking.models import BankAccount, ChequeLeaf
from apps.treasury.cheques.audit import log_cheque_audit
from apps.treasury.cheques.issued_cheques.service import IssuedChequeService
from apps.treasury.cheques.models import (
    ChequeAlert,
    ChequeClearingEvent,
    ChequeReplacement,
    ChequeReturn,
    IssuedCheque,
)
from apps.treasury.cheques.received_cheques.service import ReceivedChequeService


class ChequeReplacementService:
    @staticmethod
    @transaction.atomic
    def replace_cheque(
        *,
        original_leaf: ChequeLeaf,
        user,
        reason: str,
        new_leaf: ChequeLeaf | None = None,
        new_cheque_number: str = "",
        bank_account: BankAccount | None = None,
        cheque_date: date | None = None,
        amount: Decimal | None = None,
        drawer_bank: str = "",
        drawer_account_ref: str = "",
    ) -> ChequeReplacement:
        orig = ChequeLeaf.objects.select_for_update().get(pk=original_leaf.pk)
        if orig.status not in (
            ChequeLeaf.Status.BOUNCED,
            ChequeLeaf.Status.CANCELLED,
            ChequeLeaf.Status.STOP_PAYMENT,
            ChequeLeaf.Status.STALE,
        ):
            raise ValidationError(
                f"Only BOUNCED, CANCELLED, STOP_PAYMENT, or STALE cheques can be replaced (current: {orig.status})."
            )

        target_ba = bank_account or orig.bank_account
        target_amt = Decimal(str(amount if amount is not None else orig.amount)).quantize(Decimal("0.01"))
        target_date = cheque_date or timezone.localdate()

        if orig.direction == ChequeLeaf.Direction.ISSUED:
            orig_prof = getattr(orig, "issued_profile", None)
            new_prof = IssuedChequeService.issue_cheque(
                company=orig.company,
                bank_account=target_ba,
                user=user,
                payee_name=(orig_prof.payee_name if orig_prof else orig.party_name),
                payee_type=(orig_prof.payee_type if orig_prof else IssuedCheque.PayeeType.SUPPLIER),
                party=orig.party,
                employee=(orig_prof.employee if orig_prof else None),
                amount=target_amt,
                cheque_date=target_date,
                issue_date=target_date,
                cheque_leaf=new_leaf,
                cheque_number=new_cheque_number,
                invoice_reference=(orig_prof.invoice_reference if orig_prof else ""),
                project=orig.project,
                purpose=f"Replacement for #{orig.cheque_number}: {reason}",
                currency=orig.currency,
            )
            repl_leaf = new_prof.leaf
        else:
            orig_prof = getattr(orig, "received_profile", None)
            num = (new_cheque_number or "").strip()
            if not num:
                raise ValidationError("Supply replacement customer cheque_number.")
            new_prof = ReceivedChequeService.receive_cheque(
                company=orig.company,
                deposit_bank_account=target_ba,
                user=user,
                cheque_number=num,
                drawer_name=(orig_prof.drawer_name if orig_prof else orig.drawer_name),
                drawer_bank=drawer_bank or (orig_prof.drawer_bank if orig_prof else orig.drawer_bank),
                drawer_branch=(orig_prof.drawer_branch if orig_prof else ""),
                drawer_account_ref=drawer_account_ref,
                customer=orig.party,
                project=orig.project,
                amount=target_amt,
                currency=orig.currency,
                cheque_date=target_date,
                received_date=target_date,
                purpose=f"Replacement for #{orig.cheque_number}: {reason}",
            )
            repl_leaf = new_prof.leaf

        link = ChequeReplacement.objects.create(
            company=orig.company,
            original_cheque=orig,
            replacement_cheque=repl_leaf,
            reason=reason.strip() or f"Replacement for {orig.cheque_number}",
            linked_by=user,
        )

        # Update bounce recovery status & resolve active bounce alerts
        ChequeReturn.objects.filter(
            cheque_leaf=orig,
            follow_up_status__in=[ChequeReturn.FollowUpStatus.OPEN, ChequeReturn.FollowUpStatus.IN_RECOVERY],
        ).update(follow_up_status=ChequeReturn.FollowUpStatus.REPLACED)
        ChequeAlert.objects.filter(
            cheque_leaf=orig, alert_type=ChequeAlert.AlertType.BOUNCE_RECOVERY, is_resolved=False
        ).update(is_resolved=True, acknowledged_by=user, acknowledged_at=timezone.now())

        ChequeClearingEvent.objects.create(
            company=orig.company,
            cheque_leaf=orig,
            event_type=ChequeClearingEvent.EventType.REPLACED,
            event_date=target_date,
            from_status=orig.status,
            to_status=orig.status,
            actor=user,
            notes=f"Replaced by cheque #{repl_leaf.cheque_number}: {reason}",
        )
        log_cheque_audit(
            company=orig.company,
            action="CHEQUE_REPLACED",
            actor=user,
            cheque_leaf=orig,
            new_state={
                "original_cheque": orig.cheque_number,
                "replacement_cheque": repl_leaf.cheque_number,
                "reason": reason,
            },
        )
        return link

