from datetime import date, timedelta
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Sum
from django.utils import timezone

from apps.accounting.models import Account, LedgerEntry, Party, Voucher
from apps.accounting.services import LedgerService, PostingService, VoucherService
from apps.audit.services import record_audit_event
from apps.dashboard.cache import bump_dashboard_cache
from apps.treasury.models import TreasurySettings, record_treasury_audit
from .importers import parse_statement_bytes
from .models import (
    BankAccount,
    BankAccountDocument,
    BankAccountSignatory,
    BankReconciliationSession,
    BankStatementImport,
    BankStatementLine,
    BankStatementTemplate,
    CashAccount,
    CashCountReconciliation,
    CashCustodyHandover,
    CashTransfer,
    ChequeBook,
    ChequeLeaf,
    ImprestAdvance,
    ImprestSettlement,
    ReconciliationMatch,
)
from .security import encrypt_account_number, hash_account_number, mask_account_number


def _next_gl_code(company, prefix: str) -> str:
    existing = set(
        Account.objects.filter(company=company, code__startswith=prefix).values_list("code", flat=True)
    )
    for n in range(1, 999):
        candidate = f"{prefix}{n:02d}"
        if candidate not in existing:
            return candidate
    raise ValidationError(f"Exhausted GL code sequence for prefix {prefix}.")


def _get_or_create_group(company, code: str, name: str, atype: str) -> Account:
    acc, _ = Account.objects.get_or_create(
        company=company,
        code=code,
        defaults={"name": name, "account_type": atype, "is_group": True},
    )
    return acc


def _post_system_voucher(*, company, user, vtype: str, vdate: date, narration: str, lines_data: list[dict], project=None, idemp: str | None = None) -> Voucher:
    v = VoucherService.create_draft(
        company=company,
        user=user,
        data={
            "voucher_type": vtype,
            "voucher_date": vdate,
            "project": project,
            "narration": narration,
            "idempotency_key": idemp,
        },
        lines_data=lines_data,
    )
    if v.status == Voucher.Status.DRAFT:
        v.status = Voucher.Status.APPROVED
        v.approved_by = user
        v.save(update_fields=["status", "approved_by"])
        v = PostingService.post_voucher(voucher=v, user=user)
    bump_dashboard_cache(company.id)
    return v


class BankingService:
    @staticmethod
    @transaction.atomic
    def create_bank_account(
        *,
        company,
        user,
        bank_branch,
        account_name: str,
        account_number: str,
        account_type: str,
        purpose: str,
        currency: str,
        opening_balance: Decimal,
        branch=None,
        project=None,
        gl_account=None,
        account_code: str = "",
        account_open_date=None,
        cheque_facility_enabled: bool = True,
        online_banking_ref: str = "",
        interest_income_ledger=None,
        bank_charge_ledger=None,
        opening_date=None,
        opening_direction: str = "",
        adjustment_account=None,
        opening_narration: str = "",
        migration_override_reason: str = "",
        exchange_rate: Decimal = Decimal("1.000000"),
        auto_post_opening: bool = True,
    ) -> BankAccount:
        acct_hash = hash_account_number(account_number)
        if BankAccount.objects.filter(company=company, account_number_hash=acct_hash).exists():
            raise ValidationError("A bank account with this account number already exists for this company.")

        gl_was_created = False
        if gl_account is None:
            gl_was_created = True
            assets_grp = _get_or_create_group(company, "1000", "Assets", Account.AccountType.ASSET)
            gl_account = Account.objects.create(
                company=company,
                parent=assets_grp,
                code=_next_gl_code(company, "102"),
                name=f"{bank_branch.bank.short_code} — {account_name}",
                account_type=Account.AccountType.ASSET,
                control_role=Account.ControlRole.BANK,
                allow_direct_posting=True,
                nfrs_mapping="NAS 07",
                opening_debit=Decimal("0.00"),
                opening_credit=Decimal("0.00"),
            )

        if not account_code:
            account_code = f"BA-{gl_account.code}"

        ba = BankAccount.objects.create(
            company=company,
            bank_branch=bank_branch,
            branch=branch,
            project=project,
            account_code=account_code,
            account_name=account_name,
            account_number_masked=mask_account_number(account_number),
            account_number_encrypted=encrypt_account_number(account_number),
            account_number_hash=acct_hash,
            account_type=account_type,
            purpose=purpose,
            currency=currency,
            account_open_date=account_open_date,
            cheque_facility_enabled=cheque_facility_enabled,
            online_banking_ref=online_banking_ref,
            gl_account=gl_account,
            interest_income_ledger=interest_income_ledger,
            bank_charge_ledger=bank_charge_ledger,
            opening_balance=opening_balance,
        )
        # Single-GL invariant: post opening balance through balanced OpeningBalanceVoucher (never static Account.opening_debit)
        ob_amt = abs(Decimal(str(opening_balance or "0.00")))
        if ob_amt > Decimal("0.00") and (gl_was_created or (gl_account.opening_debit == 0 and gl_account.opening_credit == 0)):
            from apps.accounting.services.opening_balance_service import OpeningBalanceCreationService
            eff_dir = opening_direction or ("CR" if Decimal(str(opening_balance)) < 0 else "DR")
            ovr = "Bank facility opening credit / overdraft" if eff_dir == "CR" and not opening_direction else ""
            OpeningBalanceCreationService.create_single_account_opening(
                company=company,
                user=user,
                account=gl_account,
                amount=ob_amt,
                opening_date=opening_date,
                direction=eff_dir,
                adjustment_account=adjustment_account,
                project=project,
                category="OD_CC" if eff_dir == "CR" and account_type == BankAccount.AccountType.OVERDRAFT else "BANK",
                currency=currency,
                exchange_rate=exchange_rate,
                source_entity_type="BankAccount",
                source_entity_id=str(ba.id),
                reference_no=account_code,
                narration=opening_narration or f"Opening balance for Bank Account {ba.account_name}",
                override_reason=ovr,
                migration_override_reason=migration_override_reason,
                auto_post=auto_post_opening,
            )
        record_treasury_audit(
            company=company,
            module="BANK_ACCOUNTS",
            action="BANK_ACCOUNT_CREATED",
            entity_type="BankAccount",
            entity_id=str(ba.id),
            actor=user,
            new_state={"name": ba.account_name, "code": ba.account_code, "masked": ba.account_number_masked, "gl_code": gl_account.code},
        )
        return ba

    @staticmethod
    @transaction.atomic
    def create_cash_account(
        *,
        company,
        user,
        code: str,
        name: str,
        cash_type: str,
        currency: str,
        imprest_limit: Decimal,
        branch=None,
        project=None,
        site=None,
        custodian=None,
        gl_account=None,
        opening_balance: Decimal = Decimal("0.00"),
        opening_date=None,
        opening_direction: str = "",
        adjustment_account=None,
        opening_narration: str = "",
        migration_override_reason: str = "",
        exchange_rate: Decimal = Decimal("1.000000"),
        auto_post_opening: bool = True,
    ) -> CashAccount:
        if gl_account is None:
            assets_grp = _get_or_create_group(company, "1000", "Assets", Account.AccountType.ASSET)
            gl_account = Account.objects.create(
                company=company,
                parent=assets_grp,
                code=_next_gl_code(company, "101"),
                name=name,
                account_type=Account.AccountType.ASSET,
                control_role=Account.ControlRole.CASH,
                allow_direct_posting=True,
                nfrs_mapping="NAS 07",
            )
        ca = CashAccount.objects.create(
            company=company,
            branch=branch,
            project=project,
            site=site,
            custodian=custodian,
            code=code,
            name=name,
            cash_type=cash_type,
            currency=currency,
            imprest_limit=imprest_limit,
            gl_account=gl_account,
        )
        ob_amt = abs(Decimal(str(opening_balance or "0.00")))
        if ob_amt > Decimal("0.00"):
            from apps.accounting.services.opening_balance_service import OpeningBalanceCreationService
            OpeningBalanceCreationService.create_single_account_opening(
                company=company,
                user=user,
                account=gl_account,
                amount=ob_amt,
                opening_date=opening_date,
                direction=opening_direction or "DR",
                adjustment_account=adjustment_account,
                project=project,
                category="CASH",
                currency=currency,
                exchange_rate=exchange_rate,
                source_entity_type="CashAccount",
                source_entity_id=str(ca.id),
                reference_no=code,
                narration=opening_narration or f"Opening balance for Cash Vault {ca.name}",
                migration_override_reason=migration_override_reason,
                auto_post=auto_post_opening,
            )
        record_audit_event(
            company=company,
            actor=user,
            action="CASH_ACCOUNT_CREATED",
            entity_type="CashAccount",
            entity_id=str(ca.id),
            new_state={"code": ca.code, "cash_type": ca.cash_type, "gl_code": gl_account.code},
        )
        return ca

    @staticmethod
    @transaction.atomic
    def execute_transfer(
        *,
        company,
        user,
        transfer_type: str,
        transfer_date: date,
        from_gl: Account,
        to_gl: Account,
        amount: Decimal,
        currency: str = "NPR",
        exchange_rate: Decimal = Decimal("1.000000"),
        project=None,
        narration: str = "",
        transfer_ref: str = "",
        fee_amount: Decimal = Decimal("0.00"),
    ) -> CashTransfer:
        if from_gl.id == to_gl.id:
            raise ValidationError("Source and destination accounts must be different.")
        if amount <= 0:
            raise ValidationError("Transfer amount must be positive.")
        if transfer_ref:
            existing = CashTransfer.objects.filter(company=company, transfer_ref=transfer_ref).first()
            if existing:
                return existing

        base_amt = (amount * exchange_rate).quantize(Decimal("0.01"))
        lines = [
            {
                "account": to_gl,
                "debit": amount,
                "credit": Decimal("0.00"),
                "currency": currency,
                "exchange_rate": exchange_rate,
                "project": project,
            },
            {
                "account": from_gl,
                "debit": Decimal("0.00"),
                "credit": amount + fee_amount,
                "currency": currency,
                "exchange_rate": exchange_rate,
                "project": project,
            },
        ]
        if fee_amount > 0:
            chg_acc, _ = Account.objects.get_or_create(
                company=company,
                code="5230",
                defaults={"name": "Bank Charges & Commissions", "account_type": Account.AccountType.EXPENSE, "allow_direct_posting": True},
            )
            lines.append(
                {
                    "account": chg_acc,
                    "debit": fee_amount,
                    "credit": Decimal("0.00"),
                    "currency": currency,
                    "exchange_rate": exchange_rate,
                    "project": project,
                    "description": "Transfer fee",
                }
            )

        v = _post_system_voucher(
            company=company,
            user=user,
            vtype=Voucher.VoucherType.CONTRA,
            vdate=transfer_date,
            project=project,
            narration=narration or f"{transfer_type}: {from_gl.code} -> {to_gl.code}",
            lines_data=lines,
            idemp=f"trf:{company.id}:{transfer_ref}" if transfer_ref else None,
        )
        ct = CashTransfer.objects.create(
            company=company,
            transfer_type=transfer_type,
            transfer_date=transfer_date,
            from_gl_account=from_gl,
            to_gl_account=to_gl,
            amount=amount,
            fee_amount=fee_amount,
            transfer_ref=transfer_ref,
            currency=currency,
            exchange_rate=exchange_rate,
            project=project,
            narration=narration,
            voucher=v,
            created_by=user,
        )
        record_treasury_audit(
            company=company,
            module="TRANSFERS",
            action="TRANSFER_POSTED",
            entity_type="CashTransfer",
            entity_id=str(ct.id),
            actor=user,
            new_state={"type": transfer_type, "amount": str(base_amt), "voucher_no": v.voucher_no, "ref": transfer_ref},
        )
        return ct

    @staticmethod
    @transaction.atomic
    def record_bank_charge_or_interest(
        *,
        bank_account: BankAccount,
        user,
        kind: str,
        txn_date: date,
        amount: Decimal,
        reference_no: str = "",
        narration: str = "",
        project=None,
    ) -> Voucher:
        if amount <= 0:
            raise ValidationError("Amount must be positive.")
        if bank_account.status == BankAccount.Status.CLOSED:
            raise ValidationError("Cannot post entries to a closed bank account.")
        company = bank_account.company
        if kind.upper() == "INTEREST":
            inc_acc = bank_account.interest_income_ledger
            if not inc_acc:
                inc_acc, _ = Account.objects.get_or_create(
                    company=company,
                    code="4230",
                    defaults={"name": "Bank Interest Income", "account_type": Account.AccountType.INCOME, "allow_direct_posting": True},
                )
            vtype = Voucher.VoucherType.RECEIPT
            lines = [
                {"account": bank_account.gl_account, "debit": amount, "credit": Decimal("0.00"), "project": project},
                {"account": inc_acc, "debit": Decimal("0.00"), "credit": amount, "project": project},
            ]
        else:
            chg_acc = bank_account.bank_charge_ledger
            if not chg_acc:
                chg_acc, _ = Account.objects.get_or_create(
                    company=company,
                    code="5230",
                    defaults={"name": "Bank Charges & Commissions", "account_type": Account.AccountType.EXPENSE, "allow_direct_posting": True},
                )
            vtype = Voucher.VoucherType.PAYMENT
            lines = [
                {"account": chg_acc, "debit": amount, "credit": Decimal("0.00"), "project": project},
                {"account": bank_account.gl_account, "debit": Decimal("0.00"), "credit": amount, "project": project},
            ]
        return _post_system_voucher(
            company=company,
            user=user,
            vtype=vtype,
            vdate=txn_date,
            project=project,
            narration=narration or f"Bank {kind.title()} ({bank_account.account_name}) {reference_no}".strip(),
            lines_data=lines,
        )

    @staticmethod
    @transaction.atomic
    def approve_cash_count(*, count_obj: CashCountReconciliation, user) -> CashCountReconciliation:
        if count_obj.status == CashCountReconciliation.Status.APPROVED:
            return count_obj
        if count_obj.counted_by_id == user.id and not user.is_superuser:
            raise ValidationError("Maker-checker control: custodian cannot approve own cash count.")

        voucher = None
        if count_obj.variance != Decimal("0.00"):
            if count_obj.variance < 0:
                short_acc, _ = Account.objects.get_or_create(
                    company=count_obj.company,
                    code="5220",
                    defaults={"name": "Cash Shortage & Write-Off", "account_type": Account.AccountType.EXPENSE},
                )
                lines = [
                    {"account": short_acc, "debit": abs(count_obj.variance), "credit": Decimal("0.00")},
                    {"account": count_obj.cash_account.gl_account, "debit": Decimal("0.00"), "credit": abs(count_obj.variance)},
                ]
            else:
                excess_acc, _ = Account.objects.get_or_create(
                    company=count_obj.company,
                    code="4220",
                    defaults={"name": "Cash Excess / Overage", "account_type": Account.AccountType.INCOME},
                )
                lines = [
                    {"account": count_obj.cash_account.gl_account, "debit": count_obj.variance, "credit": Decimal("0.00")},
                    {"account": excess_acc, "debit": Decimal("0.00"), "credit": count_obj.variance},
                ]
            voucher = _post_system_voucher(
                company=count_obj.company,
                user=user,
                vtype=Voucher.VoucherType.JOURNAL,
                vdate=count_obj.count_date,
                narration=f"Cash count reconciliation ({count_obj.cash_account.code}): variance {count_obj.variance}",
                lines_data=lines,
            )

        count_obj.status = CashCountReconciliation.Status.APPROVED
        count_obj.approved_by = user
        count_obj.voucher = voucher
        count_obj.save(update_fields=["status", "approved_by", "voucher"])
        return count_obj

    @staticmethod
    @transaction.atomic
    def create_cheque_book(*, company, bank_account: BankAccount, book_code: str, prefix: str, start_number: int, end_number: int, issued_date: date) -> ChequeBook:
        from apps.treasury.cheques.cheque_books.service import ChequeBookService

        return ChequeBookService.register_book(
            company=company,
            bank_account=bank_account,
            book_code=book_code,
            prefix=prefix,
            start_number=start_number,
            end_number=end_number,
            issued_date=issued_date,
        )

    @staticmethod
    @transaction.atomic
    def receive_cheque(
        *,
        company,
        bank_account: BankAccount,
        user,
        cheque_number: str,
        drawer_name: str,
        drawer_bank: str,
        drawer_account_ref: str = "",
        party: Party | None = None,
        project=None,
        amount: Decimal = Decimal("0.00"),
        cheque_date: date | None = None,
        receiving_date: date | None = None,
        post_cheque_in_hand: bool = True,
    ) -> ChequeLeaf:
        from apps.treasury.cheques.received_cheques.service import ReceivedChequeService

        profile = ReceivedChequeService.receive_cheque(
            company=company,
            deposit_bank_account=bank_account,
            user=user,
            cheque_number=cheque_number,
            drawer_name=drawer_name,
            drawer_bank=drawer_bank,
            drawer_account_ref=drawer_account_ref,
            customer=party,
            project=project,
            amount=amount,
            cheque_date=cheque_date,
            received_date=receiving_date,
            post_cheque_in_hand=post_cheque_in_hand,
        )
        return profile.leaf

    @staticmethod
    @transaction.atomic
    def transition_cheque(*, leaf: ChequeLeaf, action: str, user, action_date: date | None = None, reason: str = "") -> ChequeLeaf:
        from apps.treasury.cheques.bounce_management.service import BounceManagementService
        from apps.treasury.cheques.cancellations.service import ChequeCancellationService
        from apps.treasury.cheques.cheque_leaves.service import ChequeLeafService
        from apps.treasury.cheques.clearing.service import ChequeClearingService
        from apps.treasury.cheques.deposits.service import ChequeDepositService
        from apps.treasury.cheques.issued_cheques.service import IssuedChequeService
        from apps.treasury.cheques.received_cheques.service import ReceivedChequeService

        d = action_date or timezone.localdate()
        act = (action or "").lower().strip()
        if act == "reserve":
            return ChequeLeafService.reserve_leaf(leaf=leaf, user=user, reason=reason)
        if act == "verify" and leaf.direction == ChequeLeaf.Direction.RECEIVED:
            return ReceivedChequeService.verify_cheque(leaf=leaf, user=user, notes=reason)
        if act == "approve" and leaf.direction == ChequeLeaf.Direction.ISSUED and hasattr(leaf, "issued_profile"):
            return IssuedChequeService.approve_and_issue(leaf=leaf, approver=user, approve=True, comment=reason).leaf
        if act in ("deposit", "under_clearing") and leaf.direction == ChequeLeaf.Direction.RECEIVED:
            ChequeDepositService.create_deposit_batch(
                company=leaf.company,
                deposit_bank_account=leaf.bank_account,
                cheque_ids=[leaf.id],
                user=user,
                deposit_slip_no=reason or f"SLIP-{leaf.cheque_number}",
                deposit_date=d,
            )
            leaf.refresh_from_db()
            return leaf
        if act == "clear":
            return ChequeClearingService.confirm_clearing(leaf=leaf, user=user, cleared_date=d, notes=reason)
        if act == "cancel":
            return ChequeCancellationService.cancel_cheque(leaf=leaf, user=user, reason=reason or "Cancelled", cancel_date=d)
        if act == "stop_payment":
            return IssuedChequeService.stop_payment(leaf=leaf, user=user, reason=reason or "Stop payment", stop_date=d)
        if act == "lost_damaged":
            return ChequeLeafService.mark_leaf_unusable(leaf=leaf, kind="LOST_DAMAGED", user=user, reason=reason or "Lost or damaged leaf")
        if act == "bounce":
            BounceManagementService.record_bounce(
                leaf=leaf,
                user=user,
                bounce_date=d,
                return_reason=reason or "Cheque dishonored",
                require_approval_override=False,
            )
            leaf.refresh_from_db()
            return leaf

        prev_status = leaf.status
        if act in ("prepare", "approve", "issue", "present", "verify", "deposit", "under_clearing"):
            status_map = {
                "prepare": ChequeLeaf.Status.PREPARED,
                "approve": ChequeLeaf.Status.APPROVED,
                "issue": ChequeLeaf.Status.ISSUED,
                "present": ChequeLeaf.Status.PRESENTED,
                "verify": ChequeLeaf.Status.VERIFIED,
                "deposit": ChequeLeaf.Status.DEPOSITED,
                "under_clearing": ChequeLeaf.Status.UNDER_CLEARING,
            }
            leaf.status = status_map[act]
            if act == "approve":
                leaf.signing_authority = user
            if act == "deposit":
                leaf.deposit_date = d
        elif act == "stale":
            if leaf.status in (ChequeLeaf.Status.ISSUED, ChequeLeaf.Status.IN_HAND, ChequeLeaf.Status.DEPOSITED, ChequeLeaf.Status.VERIFIED):
                leaf.status = ChequeLeaf.Status.STALE
        leaf.save()
        record_treasury_audit(
            company=leaf.company,
            module="CHEQUES",
            action=f"CHEQUE_{act.upper()}",
            entity_type="ChequeLeaf",
            entity_id=str(leaf.id),
            actor=user,
            previous_state={"status": prev_status},
            new_state={"cheque_number": leaf.cheque_number, "status": leaf.status},
        )
        return leaf

    @staticmethod
    @transaction.atomic
    def import_statement(
        *,
        company,
        user,
        bank_account: BankAccount,
        file_name: str,
        file_format: str,
        content_bytes: bytes,
        template: BankStatementTemplate | None = None,
        preview_only: bool = False,
    ):
        fmt = file_format.upper()
        mapping = template.column_mapping if template else None
        parsed = parse_statement_bytes(fmt, content_bytes, mapping=mapping)

        if preview_only:
            out = []
            for row in parsed[:200]:
                exists = BankStatementLine.objects.filter(
                    bank_account=bank_account, line_fingerprint=row["fingerprint"]
                ).exists()
                out.append(
                    {
                        "txn_date": row["txn_date"].isoformat(),
                        "reference_no": row["reference_no"],
                        "cheque_no": row["cheque_no"],
                        "description": row["description"],
                        "debit": str(row["debit"]),
                        "credit": str(row["credit"]),
                        "is_duplicate": exists,
                    }
                )
            return {"preview": True, "row_count": len(parsed), "rows": out}

        imp = BankStatementImport.objects.create(
            company=company,
            bank_account=bank_account,
            file_name=file_name,
            file_format=fmt,
            imported_by=user,
        )

        imported = 0
        skipped = 0
        created_lines = []
        dates = []
        for row in parsed:
            if BankStatementLine.objects.filter(
                bank_account=bank_account, line_fingerprint=row["fingerprint"]
            ).exists():
                skipped += 1
                continue
            dates.append(row["txn_date"])
            line = BankStatementLine.objects.create(
                company=company,
                bank_account=bank_account,
                statement_import=imp,
                txn_date=row["txn_date"],
                reference_no=row["reference_no"],
                cheque_no=row["cheque_no"],
                description=row["description"][:255],
                debit=row["debit"],
                credit=row["credit"],
                balance=row["balance"],
                line_fingerprint=row["fingerprint"],
            )
            created_lines.append(line)
            imported += 1

        imp.imported_count = imported
        imp.skipped_duplicates = skipped
        if dates:
            imp.statement_period_start = min(dates)
            imp.statement_period_end = max(dates)
        imp.save(update_fields=["imported_count", "skipped_duplicates", "statement_period_start", "statement_period_end"])

        BankingService.auto_match_lines(bank_account=bank_account, user=user, lines=created_lines)
        return imp

    @staticmethod
    def auto_match_lines(*, bank_account: BankAccount, user, lines: list[BankStatementLine] | None = None) -> int:
        if lines is None:
            lines = list(
                BankStatementLine.objects.filter(
                    bank_account=bank_account,
                    match_status__in=[BankStatementLine.MatchStatus.UNMATCHED, BankStatementLine.MatchStatus.UNDER_REVIEW],
                )
            )
        settings_obj = TreasurySettings.objects.filter(company=bank_account.company).first()
        tol_days = settings_obj.reconcile_date_tolerance_days if settings_obj else 5

        matched_count = 0
        already_matched_entry_ids = set(
            ReconciliationMatch.objects.filter(
                statement_line__bank_account=bank_account
            ).values_list("ledger_entry_id", flat=True)
        )

        for st in lines:
            if st.match_status not in (BankStatementLine.MatchStatus.UNMATCHED, BankStatementLine.MatchStatus.UNDER_REVIEW):
                continue
            target_debit = st.credit
            target_credit = st.debit
            win_start = st.txn_date - timedelta(days=tol_days)
            win_end = st.txn_date + timedelta(days=tol_days)

            candidates = list(
                LedgerEntry.objects.select_related("voucher")
                .filter(
                    company=bank_account.company,
                    account=bank_account.gl_account,
                    posting_date__range=(win_start, win_end),
                    base_debit=target_debit,
                    base_credit=target_credit,
                )
                .exclude(id__in=already_matched_entry_ids)
            )

            scored = []
            for cand in candidates:
                score = Decimal("60.00")
                reasons = ["exact amount"]
                if st.cheque_no:
                    chq = ChequeLeaf.objects.filter(bank_account=bank_account, cheque_number=st.cheque_no).first()
                    if chq and chq.voucher_id == cand.voucher_id:
                        score += Decimal("35.00")
                        reasons.append("cheque match")
                if st.reference_no and cand.voucher and cand.voucher.reference_no == st.reference_no:
                    score += Decimal("30.00")
                    reasons.append("reference match")
                if cand.posting_date == st.txn_date:
                    score += Decimal("10.00")
                    reasons.append("same date")
                scored.append((min(Decimal("100.00"), score), ", ".join(reasons), cand))

            scored.sort(key=lambda x: x[0], reverse=True)
            if not scored:
                continue

            top_score, top_reason, match_entry = scored[0]
            ambiguous = len(scored) > 1 and scored[1][0] == top_score and top_score < Decimal("90.00")

            if ambiguous:
                st.match_status = BankStatementLine.MatchStatus.UNDER_REVIEW
                st.match_confidence = top_score
                st.match_reason = f"Ambiguous ({len(scored)} candidates): {top_reason}"
                st.suggested_voucher = match_entry.voucher
                st.save(update_fields=["match_status", "match_confidence", "match_reason", "suggested_voucher"])
                continue

            amt = max(target_debit, target_credit)
            ReconciliationMatch.objects.create(
                statement_line=st,
                ledger_entry=match_entry,
                matched_amount=amt,
                match_type="AUTO",
                matched_by=user,
            )
            already_matched_entry_ids.add(match_entry.id)
            st.match_status = BankStatementLine.MatchStatus.MATCHED
            st.matched_amount = amt
            st.match_confidence = top_score
            st.match_reason = top_reason
            st.suggested_voucher = match_entry.voucher
            st.save(update_fields=["match_status", "matched_amount", "match_confidence", "match_reason", "suggested_voucher"])
            if st.cheque_no:
                ChequeLeaf.objects.filter(bank_account=bank_account, cheque_number=st.cheque_no).update(bank_reconciled=True)
            matched_count += 1

        return matched_count

    @staticmethod
    @transaction.atomic
    def manual_match_line(*, statement_line: BankStatementLine, ledger_entry: LedgerEntry, amount: Decimal, user) -> ReconciliationMatch:
        if ledger_entry.account_id != statement_line.bank_account.gl_account_id:
            raise ValidationError("Ledger entry does not belong to this bank account's GL ledger.")
        line_total = max(statement_line.debit, statement_line.credit)
        if statement_line.matched_amount + amount > line_total:
            raise ValidationError("Matched amount exceeds statement line total.")

        match_type = "MANUAL" if statement_line.matched_amount + amount == line_total else "PARTIAL"
        rec = ReconciliationMatch.objects.create(
            statement_line=statement_line,
            ledger_entry=ledger_entry,
            matched_amount=amount,
            match_type=match_type,
            matched_by=user,
        )
        statement_line.matched_amount += amount
        statement_line.match_status = (
            BankStatementLine.MatchStatus.MATCHED
            if statement_line.matched_amount == line_total
            else BankStatementLine.MatchStatus.PARTIAL
        )
        statement_line.match_confidence = Decimal("100.00")
        statement_line.match_reason = "Manual accountant verification"
        statement_line.save(update_fields=["matched_amount", "match_status", "match_confidence", "match_reason"])
        return rec

    @staticmethod
    @transaction.atomic
    def post_charge_or_interest(*, statement_line: BankStatementLine, user, kind: str) -> Voucher:
        ba = statement_line.bank_account
        company = ba.company
        if kind == "INTEREST":
            amt = statement_line.credit
            if amt <= 0:
                raise ValidationError("Interest income line must have a statement credit > 0.")
            inc_acc = ba.interest_income_ledger
            if not inc_acc:
                inc_acc, _ = Account.objects.get_or_create(
                    company=company,
                    code="4230",
                    defaults={"name": "Bank Interest Income", "account_type": Account.AccountType.INCOME},
                )
            lines = [
                {"account": ba.gl_account, "debit": amt, "credit": Decimal("0.00")},
                {"account": inc_acc, "debit": Decimal("0.00"), "credit": amt},
            ]
            vtype = Voucher.VoucherType.RECEIPT
        else:
            amt = statement_line.debit
            if amt <= 0:
                raise ValidationError("Bank charge line must have a statement debit > 0.")
            chg_acc = ba.bank_charge_ledger
            if not chg_acc:
                chg_acc, _ = Account.objects.get_or_create(
                    company=company,
                    code="5230",
                    defaults={"name": "Bank Charges & Commissions", "account_type": Account.AccountType.EXPENSE},
                )
            lines = [
                {"account": chg_acc, "debit": amt, "credit": Decimal("0.00")},
                {"account": ba.gl_account, "debit": Decimal("0.00"), "credit": amt},
            ]
            vtype = Voucher.VoucherType.PAYMENT

        v = _post_system_voucher(
            company=company,
            user=user,
            vtype=vtype,
            vdate=statement_line.txn_date,
            narration=statement_line.description or f"Bank {kind.lower()} ({ba.account_name})",
            lines_data=lines,
        )
        le = LedgerEntry.objects.filter(voucher=v, account=ba.gl_account).first()
        if le:
            BankingService.manual_match_line(statement_line=statement_line, ledger_entry=le, amount=amt, user=user)
        statement_line.suggested_voucher = v
        statement_line.save(update_fields=["suggested_voucher"])
        return v

    @staticmethod
    def get_gl_balance(gl_account: Account, as_of: date | None = None) -> Decimal:
        qs = LedgerEntry.objects.filter(account=gl_account)
        if as_of:
            qs = qs.filter(posting_date__lte=as_of)
        agg = qs.aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        return (gl_account.opening_debit - gl_account.opening_credit) + (
            (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
        )

    @staticmethod
    def get_bank_workspace(ba: BankAccount) -> dict:
        today = timezone.localdate()
        month_start = today.replace(day=1)
        book_bal = BankingService.get_gl_balance(ba.gl_account)
        last_line = BankStatementLine.objects.filter(bank_account=ba).order_by("-txn_date", "-id").first()
        stmt_bal = last_line.balance if last_line and last_line.balance is not None else book_bal
        uncleared_issued = ChequeLeaf.objects.filter(
            bank_account=ba,
            direction=ChequeLeaf.Direction.ISSUED,
            status__in=[ChequeLeaf.Status.ISSUED, ChequeLeaf.Status.PRESENTED, ChequeLeaf.Status.APPROVED],
        ).aggregate(s=Sum("amount"))["s"] or Decimal("0.00")
        deposits_transit = ChequeLeaf.objects.filter(
            bank_account=ba,
            direction=ChequeLeaf.Direction.RECEIVED,
            status__in=[ChequeLeaf.Status.IN_HAND, ChequeLeaf.Status.DEPOSITED, ChequeLeaf.Status.UNDER_CLEARING],
        ).aggregate(s=Sum("amount"))["s"] or Decimal("0.00")
        unreconciled_count = BankStatementLine.objects.filter(
            bank_account=ba,
            match_status__in=[BankStatementLine.MatchStatus.UNMATCHED, BankStatementLine.MatchStatus.UNDER_REVIEW],
        ).count()
        month_agg = LedgerEntry.objects.filter(
            account=ba.gl_account, posting_date__gte=month_start
        ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        return {
            "opening_balance": str(ba.opening_balance),
            "book_balance": str(book_bal),
            "statement_balance": str(stmt_bal),
            "last_statement_date": last_line.txn_date.isoformat() if last_line else None,
            "uncleared_cheques_amount": str(uncleared_issued),
            "deposits_in_transit_amount": str(deposits_transit),
            "unreconciled_count": unreconciled_count,
            "current_month_receipts": str(month_agg["d"] or Decimal("0.00")),
            "current_month_payments": str(month_agg["c"] or Decimal("0.00")),
            "issued_cheques_count": ChequeLeaf.objects.filter(bank_account=ba, direction=ChequeLeaf.Direction.ISSUED).exclude(status=ChequeLeaf.Status.AVAILABLE).count(),
            "received_cheques_count": ChequeLeaf.objects.filter(bank_account=ba, direction=ChequeLeaf.Direction.RECEIVED).count(),
        }

    @staticmethod
    def compute_brs_statement(*, bank_account: BankAccount, period_start: date, period_end: date, statement_closing_balance: Decimal) -> dict:
        book_bal = BankingService.get_gl_balance(bank_account.gl_account, as_of=period_end)
        matched_entry_ids = set(
            ReconciliationMatch.objects.filter(statement_line__bank_account=bank_account).values_list("ledger_entry_id", flat=True)
        )
        unmatched_book_qs = LedgerEntry.objects.select_related("voucher").filter(
            company=bank_account.company,
            account=bank_account.gl_account,
            posting_date__lte=period_end,
        ).exclude(id__in=matched_entry_ids)

        deposits_in_transit = Decimal("0.00")
        outstanding_cheques = Decimal("0.00")
        unmatched_book_rows = []
        for le in unmatched_book_qs:
            if le.base_debit > 0:
                deposits_in_transit += le.base_debit
            if le.base_credit > 0:
                outstanding_cheques += le.base_credit
            unmatched_book_rows.append(
                {
                    "id": str(le.id),
                    "posting_date": le.posting_date.isoformat(),
                    "voucher_no": le.voucher.voucher_no if le.voucher else "",
                    "narration": le.voucher.narration if le.voucher else "",
                    "debit": str(le.base_debit),
                    "credit": str(le.base_credit),
                }
            )
        adjusted_bank_balance = statement_closing_balance + deposits_in_transit - outstanding_cheques
        variance = (adjusted_bank_balance - book_bal).quantize(Decimal("0.01"))
        return {
            "bank_account_id": str(bank_account.id),
            "account_name": bank_account.account_name,
            "period_start": period_start.isoformat(),
            "period_end": period_end.isoformat(),
            "statement_closing_balance": str(statement_closing_balance),
            "deposits_in_transit": str(deposits_in_transit),
            "outstanding_cheques": str(outstanding_cheques),
            "adjusted_bank_balance": str(adjusted_bank_balance),
            "book_closing_balance": str(book_bal),
            "unreconciled_difference": str(variance),
            "unmatched_book_entries": unmatched_book_rows,
        }


class ImprestService:
    @staticmethod
    @transaction.atomic
    def issue_imprest(
        *,
        company,
        user,
        cash_account: CashAccount,
        custodian,
        funding_gl_account: Account,
        imprest_no: str,
        request_date: date,
        amount: Decimal,
        project=None,
        site=None,
        purpose: str = "",
        due_date: date | None = None,
    ) -> ImprestAdvance:
        if amount <= 0:
            raise ValidationError("Imprest issue amount must be positive.")
        if cash_account.imprest_limit > 0 and amount > cash_account.imprest_limit:
            raise ValidationError(
                f"Imprest amount ({amount}) exceeds cash account imprest limit ({cash_account.imprest_limit})."
            )
        imprest_gl, _ = Account.objects.get_or_create(
            company=company,
            code="1061",
            defaults={
                "name": "Employee Imprest Receivable",
                "account_type": Account.AccountType.ASSET,
                "control_role": Account.ControlRole.EMPLOYEE_ADVANCE,
                "allow_direct_posting": True,
            },
        )
        v = _post_system_voucher(
            company=company,
            user=user,
            vtype=Voucher.VoucherType.PAYMENT,
            vdate=request_date,
            project=project,
            narration=f"Imprest advance {imprest_no} issued to {custodian.username}: {purpose}".strip(),
            lines_data=[
                {"account": imprest_gl, "debit": amount, "credit": Decimal("0.00"), "project": project},
                {"account": funding_gl_account, "debit": Decimal("0.00"), "credit": amount, "project": project},
            ],
        )
        imp = ImprestAdvance.objects.create(
            company=company,
            imprest_no=imprest_no,
            cash_account=cash_account,
            funding_gl_account=funding_gl_account,
            imprest_gl_account=imprest_gl,
            custodian=custodian,
            project=project,
            site=site,
            purpose=purpose,
            request_date=request_date,
            due_date=due_date,
            approved_limit=cash_account.imprest_limit or amount,
            issued_amount=amount,
            status=ImprestAdvance.Status.ISSUED,
            issue_voucher=v,
            manager_approved_by=user,
            finance_approved_by=user,
        )
        record_treasury_audit(
            company=company,
            module="IMPREST",
            action="IMPREST_ISSUED",
            entity_type="ImprestAdvance",
            entity_id=str(imp.id),
            actor=user,
            new_state={"imprest_no": imprest_no, "amount": str(amount), "custodian": custodian.username},
        )
        return imp

    @staticmethod
    @transaction.atomic
    def settle_imprest(
        *,
        imprest: ImprestAdvance,
        user,
        settlement_date: date,
        expense_lines: list[dict],
        unused_cash_returned: Decimal = Decimal("0.00"),
        return_to_gl_account: Account | None = None,
        replenish_requested: bool = False,
        notes: str = "",
    ) -> ImprestSettlement:
        exp_total = sum((Decimal(str(ln.get("amount", 0))) for ln in expense_lines), Decimal("0.00"))
        if exp_total + unused_cash_returned > imprest.outstanding_balance:
            raise ValidationError(
                f"Settlement total ({exp_total + unused_cash_returned}) exceeds outstanding imprest balance ({imprest.outstanding_balance})."
            )
        if exp_total <= 0 and unused_cash_returned <= 0:
            raise ValidationError("Must provide verified expense lines or unused cash returned.")

        exp_voucher = None
        if exp_total > 0:
            v_lines = []
            for ln in expense_lines:
                amt = Decimal(str(ln["amount"]))
                if amt <= 0:
                    continue
                acc = Account.objects.get(id=ln["account"], company=imprest.company)
                v_lines.append(
                    {
                        "account": acc,
                        "debit": amt,
                        "credit": Decimal("0.00"),
                        "project": imprest.project,
                        "site": imprest.site,
                        "description": ln.get("description", ""),
                    }
                )
            v_lines.append(
                {
                    "account": imprest.imprest_gl_account,
                    "debit": Decimal("0.00"),
                    "credit": exp_total,
                    "project": imprest.project,
                }
            )
            exp_voucher = _post_system_voucher(
                company=imprest.company,
                user=user,
                vtype=Voucher.VoucherType.JOURNAL,
                vdate=settlement_date,
                project=imprest.project,
                narration=f"Imprest {imprest.imprest_no} verified expense settlement",
                lines_data=v_lines,
            )

        ret_voucher = None
        if unused_cash_returned > 0:
            ret_acc = return_to_gl_account or imprest.cash_account.gl_account
            ret_voucher = _post_system_voucher(
                company=imprest.company,
                user=user,
                vtype=Voucher.VoucherType.RECEIPT,
                vdate=settlement_date,
                project=imprest.project,
                narration=f"Imprest {imprest.imprest_no} unused cash return",
                lines_data=[
                    {"account": ret_acc, "debit": unused_cash_returned, "credit": Decimal("0.00"), "project": imprest.project},
                    {"account": imprest.imprest_gl_account, "debit": Decimal("0.00"), "credit": unused_cash_returned, "project": imprest.project},
                ],
            )

        repl_voucher = None
        repl_amt = Decimal("0.00")
        if replenish_requested and exp_total > 0 and imprest.funding_gl_account:
            # Fixed imprest rule: replenish strictly the verified spend without enlarging cap
            repl_amt = min(exp_total, imprest.approved_limit)
            repl_voucher = _post_system_voucher(
                company=imprest.company,
                user=user,
                vtype=Voucher.VoucherType.PAYMENT,
                vdate=settlement_date,
                project=imprest.project,
                narration=f"Imprest {imprest.imprest_no} replenishment ({repl_amt})",
                lines_data=[
                    {"account": imprest.imprest_gl_account, "debit": repl_amt, "credit": Decimal("0.00"), "project": imprest.project},
                    {"account": imprest.funding_gl_account, "debit": Decimal("0.00"), "credit": repl_amt, "project": imprest.project},
                ],
            )
            imprest.issued_amount += repl_amt

        imprest.settled_expense_amount += exp_total
        imprest.returned_cash_amount += unused_cash_returned
        imprest.status = (
            ImprestAdvance.Status.SETTLED
            if imprest.outstanding_balance == Decimal("0.00")
            else ImprestAdvance.Status.PARTIALLY_SETTLED
        )
        imprest.save()

        sett = ImprestSettlement.objects.create(
            company=imprest.company,
            imprest=imprest,
            settlement_date=settlement_date,
            expense_lines=expense_lines,
            verified_expense_total=exp_total,
            unused_cash_returned=unused_cash_returned,
            return_to_gl_account=return_to_gl_account,
            replenish_requested=replenish_requested,
            replenished_amount=repl_amt,
            settlement_voucher=exp_voucher,
            return_voucher=ret_voucher,
            replenishment_voucher=repl_voucher,
            status=ImprestSettlement.Status.APPROVED,
            submitted_by=user,
            approved_by=user,
            notes=notes,
        )
        record_treasury_audit(
            company=imprest.company,
            module="IMPREST",
            action="IMPREST_SETTLED",
            entity_type="ImprestSettlement",
            entity_id=str(sett.id),
            actor=user,
            new_state={"imprest_no": imprest.imprest_no, "expenses": str(exp_total), "returned": str(unused_cash_returned)},
        )
        return sett

    @staticmethod
    @transaction.atomic
    def confirm_handover(*, handover: CashCustodyHandover, user) -> CashCustodyHandover:
        if handover.status == CashCustodyHandover.Status.COMPLETED:
            return handover
        if handover.to_custodian_id != user.id and not user.is_superuser:
            raise ValidationError("Only the receiving custodian or an administrator can confirm cash handover.")
        handover.status = CashCustodyHandover.Status.COMPLETED
        handover.confirmed_by = user
        handover.confirmed_at = timezone.now()
        handover.save(update_fields=["status", "confirmed_by", "confirmed_at"])
        ca = handover.cash_account
        ca.custodian = handover.to_custodian
        ca.save(update_fields=["custodian"])
        record_treasury_audit(
            company=handover.company,
            module="CASH",
            action="CASH_HANDOVER_CONFIRMED",
            entity_type="CashCustodyHandover",
            entity_id=str(handover.id),
            actor=user,
            new_state={"cash_account": ca.code, "new_custodian": handover.to_custodian.username, "amount": str(handover.physical_amount)},
        )
        return handover

