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

from apps.accounting.models import Account, LedgerEntry, Voucher
from apps.accounting.services import PostingService
from apps.banking.models import ChequeLeaf
from apps.party_hub.services.sync import OpenItemSyncService
from apps.treasury.cheques.gl_helpers import (
    get_cheque_return_charge_account,
    get_creditors_control_account,
    get_debtors_control_account,
    post_cheque_voucher,
)
from apps.treasury.cheques.models import (
    ChequeDepositLine,
    ChequeReturn,
    ChequeReversal,
)


class ChequeReversalEngine:
    @staticmethod
    @transaction.atomic
    def execute_return_reversals(
        *,
        leaf: ChequeLeaf,
        cheque_return: ChequeReturn,
        dep_line: ChequeDepositLine | None,
        actor,
        reversal_date: date,
        reason: str,
        bank_charge_amount: Decimal = Decimal("0.00"),
    ) -> list[ChequeReversal]:
        """
        Executes linked double-entry reversals according to lifecycle stage without ever editing
        or deleting original posted vouchers:
        - BEFORE_DEPOSIT (Scenario A): Reverse receipt (Dr Debtors / Cr 1035) & reopen invoice.
        - AFTER_DEPOSIT (Scenario B):
            1) Reverse deposit transfer Step 1 (Dr 1035 / Cr 1036).
            2) Reverse original receipt (Dr Debtors / Cr 1035) & reopen invoice.
        - AFTER_CLEARANCE (Scenario C):
            Reopen allocated invoices & post Dr Debtors / Cr Bank Account GL.
        - ISSUED_BOUNCE:
            Release payable allocations & reverse issued payment voucher (Dr Bank / Cr Creditors/Expense).
        - Plus separate Bank Charge voucher whenever bank_charge_amount > 0.
        """
        created_reversals: list[ChequeReversal] = []
        scenario = cheque_return.bounce_scenario

        if scenario == ChequeReturn.BounceScenario.BEFORE_DEPOSIT:
            if leaf.voucher and leaf.voucher.status == Voucher.Status.POSTED:
                reopened = OpenItemSyncService.release_allocations_for_reversal(
                    voucher=leaf.voucher,
                    reason=f"Bounced cheque #{leaf.cheque_number}: {reason}",
                )
                rev_v = PostingService.reverse_voucher(
                    voucher=leaf.voucher,
                    user=actor,
                    reversal_date=reversal_date,
                    reason=f"Scenario A bounce #{leaf.cheque_number}: {reason}",
                )
                leaf.reversal_voucher = rev_v
                created_reversals.append(
                    ChequeReversal.objects.create(
                        company=leaf.company,
                        cheque_leaf=leaf,
                        cheque_return=cheque_return,
                        step_kind=ChequeReversal.StepKind.RECEIPT_REVERSAL,
                        original_voucher=leaf.voucher,
                        reversal_voucher=rev_v,
                        reopened_allocations=reopened,
                        amount=leaf.amount,
                    )
                )

        elif scenario == ChequeReturn.BounceScenario.AFTER_DEPOSIT:
            # Step 1: Reverse deposit transfer (Dr 1035 Cheques-in-Hand / Cr 1036 Cheques-in-Clearing)
            step1_v = dep_line.clearing_step1_voucher if dep_line else None
            if step1_v and step1_v.status == Voucher.Status.POSTED:
                rev_dep = PostingService.reverse_voucher(
                    voucher=step1_v,
                    user=actor,
                    reversal_date=reversal_date,
                    reason=f"Scenario B reverse deposit transfer #{leaf.cheque_number}: {reason}",
                )
                created_reversals.append(
                    ChequeReversal.objects.create(
                        company=leaf.company,
                        cheque_leaf=leaf,
                        cheque_return=cheque_return,
                        step_kind=ChequeReversal.StepKind.DEPOSIT_TRANSFER_REVERSAL,
                        original_voucher=step1_v,
                        reversal_voucher=rev_dep,
                        amount=leaf.amount,
                    )
                )

            # Step 2: Reverse original Stage 0 receipt (Dr Debtors / Cr 1035) & reopen invoices
            if leaf.voucher and leaf.voucher.status == Voucher.Status.POSTED:
                reopened = OpenItemSyncService.release_allocations_for_reversal(
                    voucher=leaf.voucher,
                    reason=f"Scenario B bounced cheque #{leaf.cheque_number}: {reason}",
                )
                rev_rcpt = PostingService.reverse_voucher(
                    voucher=leaf.voucher,
                    user=actor,
                    reversal_date=reversal_date,
                    reason=f"Scenario B reverse receipt #{leaf.cheque_number}: {reason}",
                )
                leaf.reversal_voucher = rev_rcpt
                created_reversals.append(
                    ChequeReversal.objects.create(
                        company=leaf.company,
                        cheque_leaf=leaf,
                        cheque_return=cheque_return,
                        step_kind=ChequeReversal.StepKind.RECEIPT_REVERSAL,
                        original_voucher=leaf.voucher,
                        reversal_voucher=rev_rcpt,
                        reopened_allocations=reopened,
                        amount=leaf.amount,
                    )
                )

        elif scenario == ChequeReturn.BounceScenario.AFTER_CLEARANCE:
            reopened = []
            if leaf.voucher:
                reopened = OpenItemSyncService.release_allocations_for_reversal(
                    voucher=leaf.voucher,
                    reason=f"Scenario C post-clearance bounce #{leaf.cheque_number}: {reason}",
                )
            debtors_acc = get_debtors_control_account(leaf.company, party=leaf.party)
            rev_bank = post_cheque_voucher(
                company=leaf.company,
                user=actor,
                vtype=Voucher.VoucherType.JOURNAL,
                vdate=reversal_date,
                project=leaf.project,
                party=leaf.party,
                reference_no=cheque_return.bank_return_reference or leaf.cheque_number,
                currency=leaf.currency,
                narration=(
                    f"Scenario C post-clearance cheque return #{leaf.cheque_number}: "
                    f"restore receivable & debit bank return ({reason})"
                ),
                lines_data=[
                    {
                        "account": debtors_acc,
                        "party": leaf.party if debtors_acc.requires_subledger else None,
                        "debit": leaf.amount,
                        "credit": Decimal("0.00"),
                        "project": leaf.project,
                        "description": f"Reopen receivable for returned cheque #{leaf.cheque_number}",
                    },
                    {
                        "account": leaf.bank_account.gl_account,
                        "debit": Decimal("0.00"),
                        "credit": leaf.amount,
                        "project": leaf.project,
                        "description": f"Bank reversal of previously cleared cheque #{leaf.cheque_number}",
                    },
                ],
            )
            leaf.reversal_voucher = rev_bank
            created_reversals.append(
                ChequeReversal.objects.create(
                    company=leaf.company,
                    cheque_leaf=leaf,
                    cheque_return=cheque_return,
                    step_kind=ChequeReversal.StepKind.BANK_CREDIT_REVERSAL,
                    original_voucher=leaf.clearing_voucher or leaf.voucher,
                    reversal_voucher=rev_bank,
                    reopened_allocations=reopened,
                    amount=leaf.amount,
                )
            )

        elif scenario == ChequeReturn.BounceScenario.ISSUED_BOUNCE:
            if leaf.voucher and leaf.voucher.status == Voucher.Status.POSTED:
                reopened = OpenItemSyncService.release_allocations_for_reversal(
                    voucher=leaf.voucher,
                    reason=f"Issued cheque #{leaf.cheque_number} bounced: {reason}",
                )
                rev_pay = PostingService.reverse_voucher(
                    voucher=leaf.voucher,
                    user=actor,
                    reversal_date=reversal_date,
                    reason=f"Issued cheque bounce #{leaf.cheque_number}: {reason}",
                )
                leaf.reversal_voucher = rev_pay
                created_reversals.append(
                    ChequeReversal.objects.create(
                        company=leaf.company,
                        cheque_leaf=leaf,
                        cheque_return=cheque_return,
                        step_kind=ChequeReversal.StepKind.PAYMENT_REVERSAL,
                        original_voucher=leaf.voucher,
                        reversal_voucher=rev_pay,
                        reopened_allocations=reopened,
                        amount=leaf.amount,
                    )
                )
            elif leaf.amount > 0:
                creditors_acc = get_creditors_control_account(leaf.company, party=leaf.party)
                rev_pay = post_cheque_voucher(
                    company=leaf.company,
                    user=actor,
                    vtype=Voucher.VoucherType.JOURNAL,
                    vdate=reversal_date,
                    project=leaf.project,
                    party=leaf.party,
                    reference_no=leaf.cheque_number,
                    currency=leaf.currency,
                    narration=f"Issued cheque bounce #{leaf.cheque_number} payable restoration: {reason}",
                    lines_data=[
                        {
                            "account": leaf.bank_account.gl_account,
                            "debit": leaf.amount,
                            "credit": Decimal("0.00"),
                            "project": leaf.project,
                            "description": f"Reverse issued cheque #{leaf.cheque_number}",
                        },
                        {
                            "account": creditors_acc,
                            "party": leaf.party if creditors_acc.requires_subledger else None,
                            "debit": Decimal("0.00"),
                            "credit": leaf.amount,
                            "project": leaf.project,
                            "description": f"Restore payable for bounced cheque #{leaf.cheque_number}",
                        },
                    ],
                )
                leaf.reversal_voucher = rev_pay
                created_reversals.append(
                    ChequeReversal.objects.create(
                        company=leaf.company,
                        cheque_leaf=leaf,
                        cheque_return=cheque_return,
                        step_kind=ChequeReversal.StepKind.PAYMENT_REVERSAL,
                        original_voucher=None,
                        reversal_voucher=rev_pay,
                        amount=leaf.amount,
                    )
                )

        # Separate Bank Return Fee entry (Dr Bank Charges / Cheque Return Expense, Cr Bank Account GL)
        fee = Decimal(str(bank_charge_amount or "0.00")).quantize(Decimal("0.01"))
        if fee > 0:
            charge_acc = get_cheque_return_charge_account(leaf.company, bank_account=leaf.bank_account)
            fee_voucher = post_cheque_voucher(
                company=leaf.company,
                user=actor,
                vtype=Voucher.VoucherType.PAYMENT,
                vdate=reversal_date,
                project=leaf.project,
                reference_no=cheque_return.bank_return_reference or leaf.cheque_number,
                currency=leaf.currency,
                narration=f"Bank cheque return charge for #{leaf.cheque_number} ({reason})",
                lines_data=[
                    {
                        "account": charge_acc,
                        "debit": fee,
                        "credit": Decimal("0.00"),
                        "project": leaf.project,
                        "description": f"Cheque return fee #{leaf.cheque_number}",
                    },
                    {
                        "account": leaf.bank_account.gl_account,
                        "debit": Decimal("0.00"),
                        "credit": fee,
                        "project": leaf.project,
                        "description": f"Bank debit return fee #{leaf.cheque_number}",
                    },
                ],
            )
            cheque_return.charge_voucher = fee_voucher
            cheque_return.save(update_fields=["charge_voucher"])
            created_reversals.append(
                ChequeReversal.objects.create(
                    company=leaf.company,
                    cheque_leaf=leaf,
                    cheque_return=cheque_return,
                    step_kind=ChequeReversal.StepKind.BANK_CHARGE,
                    original_voucher=None,
                    reversal_voucher=fee_voucher,
                    amount=fee,
                )
            )

        return created_reversals

    @staticmethod
    def reconcile_subledger_with_gl(*, company) -> dict:
        """
        Compute live GL vs Subledger reconciliation for Cheques-in-Hand (1035) and Cheques-in-Clearing (1036).
        """
        from django.db.models import Sum
        from apps.treasury.cheques.gl_helpers import (
            get_cheques_in_clearing_account,
            get_cheques_in_hand_account,
        )

        def gl_bal(acc: Account) -> Decimal:
            agg = LedgerEntry.objects.filter(company=company, account=acc).aggregate(
                d=Sum("base_debit"), c=Sum("base_credit")
            )
            return (acc.opening_debit - acc.opening_credit) + (
                (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
            )

        cih_acc = get_cheques_in_hand_account(company)
        cic_acc = get_cheques_in_clearing_account(company)

        cih_sub_qs = ChequeLeaf.objects.filter(
            company=company,
            direction=ChequeLeaf.Direction.RECEIVED,
            status__in=[ChequeLeaf.Status.IN_HAND, ChequeLeaf.Status.RECEIVED, ChequeLeaf.Status.VERIFIED],
        )
        cic_sub_qs = ChequeLeaf.objects.filter(
            company=company,
            direction=ChequeLeaf.Direction.RECEIVED,
            status__in=[ChequeLeaf.Status.DEPOSITED, ChequeLeaf.Status.UNDER_CLEARING],
        )

        cih_sub = cih_sub_qs.aggregate(total=Sum("amount"))["total"] or Decimal("0.00")
        cic_sub = cic_sub_qs.aggregate(total=Sum("amount"))["total"] or Decimal("0.00")
        cih_gl = gl_bal(cih_acc)
        cic_gl = gl_bal(cic_acc)

        return {
            "cheques_in_hand": {
                "account_code": cih_acc.code,
                "account_name": cih_acc.name,
                "gl_balance": str(cih_gl),
                "subledger_balance": str(cih_sub),
                "variance": str(cih_gl - cih_sub),
                "count": cih_sub_qs.count(),
                "reconciled": cih_gl == cih_sub,
            },
            "cheques_in_clearing": {
                "account_code": cic_acc.code,
                "account_name": cic_acc.name,
                "gl_balance": str(cic_gl),
                "subledger_balance": str(cic_sub),
                "variance": str(cic_gl - cic_sub),
                "count": cic_sub_qs.count(),
                "reconciled": cic_gl == cic_sub,
            },
        }

