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.accounting.models import Voucher
from apps.banking.models import BankAccount, BankStatementLine, ChequeLeaf, ReconciliationMatch
from apps.treasury.cheques.audit import log_cheque_audit
from apps.treasury.cheques.deposits.service import ChequeDepositService
from apps.treasury.cheques.gl_helpers import (
    get_cheques_in_clearing_account,
    get_cheques_in_hand_account,
    get_treasury_settings,
    post_cheque_voucher,
)
from apps.treasury.cheques.models import (
    ChequeClearingEvent,
    ChequeDepositLine,
    IssuedCheque,
    ReceivedCheque,
)
from apps.treasury.models import TreasurySettings


class ChequeClearingService:
    @staticmethod
    @transaction.atomic
    def confirm_clearing(
        *,
        leaf: ChequeLeaf,
        user,
        cleared_date: date | None = None,
        bank_reference: str = "",
        statement_line: BankStatementLine | None = None,
        notes: str = "",
    ) -> ChequeLeaf:
        """
        Step 2 Bank Clearance Confirmation (for Received Cheques) or Presentation Reconciliation (for Issued Cheques):
        - Received Cheque (under CHEQUES_IN_HAND mode):
          Must already be deposited/under clearing (cannot jump straight from IN_HAND without deposit!).
          Posts Dr Bank Account GL / Cr Cheques-in-Clearing (1036).
        - Marks ONLY this cheque & deposit line CLEARED, preserving partial batch independence.
        - Idempotent guard prevents clearing an already-CLEARED cheque or re-matched statement line.
        """
        leaf = ChequeLeaf.objects.select_for_update().get(pk=leaf.pk)
        if leaf.status == ChequeLeaf.Status.CLEARED:
            raise ValidationError(f"Cheque #{leaf.cheque_number} is already CLEARED.")
        if leaf.status in (
            ChequeLeaf.Status.CANCELLED,
            ChequeLeaf.Status.BOUNCED,
            ChequeLeaf.Status.STOP_PAYMENT,
            ChequeLeaf.Status.LOST_DAMAGED,
            ChequeLeaf.Status.SKIPPED,
        ):
            raise ValidationError(f"Cheque #{leaf.cheque_number} in status {leaf.status} cannot be cleared.")

        clr_date = cleared_date or (statement_line.txn_date if statement_line else timezone.localdate())
        prev_status = leaf.status
        clearing_voucher = leaf.clearing_voucher

        if leaf.direction == ChequeLeaf.Direction.RECEIVED:
            if leaf.status not in (ChequeLeaf.Status.DEPOSITED, ChequeLeaf.Status.UNDER_CLEARING):
                raise ValidationError(
                    f"Cheque #{leaf.cheque_number} must be deposited into Cheques-in-Clearing first before final bank clearance confirmation."
                )

            settings_obj = get_treasury_settings(leaf.company)
            if leaf.amount > 0 and not clearing_voucher:
                dep_line = (
                    ChequeDepositLine.objects.select_for_update()
                    .filter(cheque_leaf=leaf)
                    .order_by("-created_at")
                    .first()
                )
                credit_acc = (
                    get_cheques_in_clearing_account(leaf.company)
                    if settings_obj.cheque_accounting_mode == TreasurySettings.ChequeAccountingMode.CHEQUES_IN_HAND
                    else get_cheques_in_hand_account(leaf.company)
                )
                clearing_voucher = post_cheque_voucher(
                    company=leaf.company,
                    user=user,
                    vtype=Voucher.VoucherType.CONTRA,
                    vdate=clr_date,
                    project=leaf.project,
                    reference_no=bank_reference or leaf.cheque_number,
                    currency=leaf.currency,
                    narration=(
                        f"Clearing Step 2: Cheque #{leaf.cheque_number} confirmed cleared into "
                        f"{leaf.bank_account.account_name}"
                    ),
                    lines_data=[
                        {
                            "account": leaf.bank_account.gl_account,
                            "debit": leaf.amount,
                            "credit": Decimal("0.00"),
                            "project": leaf.project,
                            "description": f"Bank credit for cleared cheque #{leaf.cheque_number}",
                        },
                        {
                            "account": credit_acc,
                            "debit": Decimal("0.00"),
                            "credit": leaf.amount,
                            "project": leaf.project,
                            "description": f"Release #{leaf.cheque_number} from {credit_acc.name}",
                        },
                    ],
                )
                if dep_line:
                    dep_line.clearing_step2_voucher = clearing_voucher
                    dep_line.status = ChequeDepositLine.LineStatus.CLEARED
                    dep_line.cleared_date = clr_date
                    dep_line.bank_reference = bank_reference or dep_line.bank_reference
                    dep_line.statement_line = statement_line or dep_line.statement_line
                    dep_line.save()
                    ChequeDepositService.recompute_batch_status(dep_line.batch)
            else:
                dep_line = ChequeDepositLine.objects.filter(cheque_leaf=leaf).order_by("-created_at").first()
                if dep_line:
                    dep_line.status = ChequeDepositLine.LineStatus.CLEARED
                    dep_line.cleared_date = clr_date
                    dep_line.bank_reference = bank_reference or dep_line.bank_reference
                    dep_line.statement_line = statement_line or dep_line.statement_line
                    dep_line.save()
                    ChequeDepositService.recompute_batch_status(dep_line.batch)

            if hasattr(leaf, "received_profile"):
                prof = leaf.received_profile
                prof.workflow_status = ReceivedCheque.WorkflowStatus.CLEARED
                prof.save(update_fields=["workflow_status", "updated_at"])
        else:
            # Issued cheque cleared when presented at bank
            if leaf.status not in (
                ChequeLeaf.Status.ISSUED,
                ChequeLeaf.Status.PRESENTED,
                ChequeLeaf.Status.APPROVED,
            ):
                raise ValidationError(f"Issued cheque #{leaf.cheque_number} is {leaf.status} and cannot be cleared.")
            if hasattr(leaf, "issued_profile"):
                prof = leaf.issued_profile
                prof.workflow_status = IssuedCheque.WorkflowStatus.CLEARED
                prof.save(update_fields=["workflow_status", "updated_at"])

        if statement_line:
            statement_line = BankStatementLine.objects.select_for_update().get(pk=statement_line.pk)
            if statement_line.match_status != BankStatementLine.MatchStatus.MATCHED:
                from apps.accounting.models import LedgerEntry

                target_voucher = clearing_voucher or leaf.voucher
                le = (
                    LedgerEntry.objects.filter(
                        voucher=target_voucher, account=leaf.bank_account.gl_account
                    ).first()
                    if target_voucher
                    else None
                )
                if le and not ReconciliationMatch.objects.filter(statement_line=statement_line, ledger_entry=le).exists():
                    ReconciliationMatch.objects.create(
                        statement_line=statement_line,
                        ledger_entry=le,
                        matched_amount=max(statement_line.debit, statement_line.credit),
                        match_type="CHEQUE_CLEAR",
                        matched_by=user,
                    )
                statement_line.match_status = BankStatementLine.MatchStatus.MATCHED
                statement_line.matched_amount = max(statement_line.debit, statement_line.credit)
                statement_line.match_confidence = Decimal("100.00")
                statement_line.match_reason = f"Confirmed cheque #{leaf.cheque_number}"
                statement_line.suggested_voucher = target_voucher
                statement_line.save(
                    update_fields=["match_status", "matched_amount", "match_confidence", "match_reason", "suggested_voucher"]
                )
            leaf.bank_reconciled = True

        leaf.status = ChequeLeaf.Status.CLEARED
        leaf.cleared_date = clr_date
        leaf.clearing_voucher = clearing_voucher
        leaf.save(update_fields=["status", "cleared_date", "clearing_voucher", "bank_reconciled", "updated_at"])

        ChequeClearingEvent.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.CLEARED,
            event_date=clr_date,
            from_status=prev_status,
            to_status=ChequeLeaf.Status.CLEARED,
            voucher=clearing_voucher or leaf.voucher,
            bank_reference=bank_reference,
            statement_line=statement_line,
            actor=user,
            notes=notes or f"Bank clearance confirmed ({bank_reference or 'manual'})",
        )
        log_cheque_audit(
            company=leaf.company,
            action="CHEQUE_CLEARING_CONFIRMED",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": prev_status},
            new_state={
                "status": ChequeLeaf.Status.CLEARED,
                "cleared_date": clr_date.isoformat(),
                "clearing_voucher_no": clearing_voucher.voucher_no if clearing_voucher else "",
                "bank_reference": bank_reference,
            },
        )
        return leaf

    @staticmethod
    def suggest_statement_matches(*, company, bank_account: BankAccount | None = None) -> list[dict]:
        """
        Score unmatched BankStatementLine entries against pending Received (UNDER_CLEARING/DEPOSITED)
        and Issued (ISSUED/PRESENTED) cheques using cheque number, amount, deposit date,
        bank reference, deposit batch, and drawer details.
        """
        stmt_qs = BankStatementLine.objects.select_related("bank_account").filter(
            company=company,
            match_status__in=[
                BankStatementLine.MatchStatus.UNMATCHED,
                BankStatementLine.MatchStatus.UNDER_REVIEW,
            ],
        )
        if bank_account:
            stmt_qs = stmt_qs.filter(bank_account=bank_account)

        pending_cheques = list(
            ChequeLeaf.objects.select_related("bank_account", "received_profile", "issued_profile")
            .filter(
                company=company,
                status__in=[
                    ChequeLeaf.Status.UNDER_CLEARING,
                    ChequeLeaf.Status.DEPOSITED,
                    ChequeLeaf.Status.ISSUED,
                    ChequeLeaf.Status.PRESENTED,
                ],
            )
        )

        suggestions = []
        for st in stmt_qs[:200]:
            is_credit = st.credit > 0 and st.debit == 0
            stmt_amt = st.credit if is_credit else st.debit
            target_dir = ChequeLeaf.Direction.RECEIVED if is_credit else ChequeLeaf.Direction.ISSUED

            candidates = []
            for chq in pending_cheques:
                if chq.bank_account_id != st.bank_account_id or chq.direction != target_dir:
                    continue
                if chq.amount != stmt_amt:
                    continue
                score = 50
                reasons = ["exact amount"]
                if st.cheque_no and (
                    st.cheque_no.strip().lower() == chq.cheque_number.strip().lower()
                    or st.cheque_no.strip().lstrip("0") == chq.cheque_number.strip().lstrip("0")
                ):
                    score += 35
                    reasons.append("cheque # match")
                elif chq.cheque_number in (st.description or ""):
                    score += 20
                    reasons.append("cheque # in narration")
                ref_date = chq.deposit_date or chq.cheque_date
                if ref_date and abs((st.txn_date - ref_date).days) <= 7:
                    score += 10
                    reasons.append("date within clearing window")
                if chq.drawer_name and chq.drawer_name.lower() in (st.description or "").lower():
                    score += 5
                    reasons.append("drawer match")
                candidates.append(
                    {
                        "cheque_id": str(chq.id),
                        "cheque_number": chq.cheque_number,
                        "direction": chq.direction,
                        "party_name": chq.party_name or chq.drawer_name,
                        "amount": str(chq.amount),
                        "deposit_date": chq.deposit_date.isoformat() if chq.deposit_date else None,
                        "confidence": min(score, 100),
                        "reasons": reasons,
                    }
                )
            if candidates:
                candidates.sort(key=lambda x: x["confidence"], reverse=True)
                suggestions.append(
                    {
                        "statement_line_id": str(st.id),
                        "bank_account_id": str(st.bank_account_id),
                        "bank_account_name": st.bank_account.account_name,
                        "txn_date": st.txn_date.isoformat(),
                        "cheque_no": st.cheque_no,
                        "reference_no": st.reference_no,
                        "description": st.description,
                        "amount": str(stmt_amt),
                        "direction": target_dir,
                        "ambiguous": len(candidates) > 1 and candidates[0]["confidence"] < 85,
                        "candidates": candidates[:5],
                    }
                )
        return suggestions

