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 Q, Sum
from django.utils import timezone

from apps.accounts_rbac.policies import scope_queryset
from apps.accounting.models import Account, LedgerEntry, Party, Voucher
from apps.accounting.services import PostingService, VoucherService
from apps.audit.services import record_audit_event
from apps.banking.models import BankAccount, BankTransaction, CashAccount, ChequeBook, ChequeLeaf
from apps.treasury.cheques.audit import log_cheque_audit
from apps.treasury.cheques.cheque_books.service import ChequeBookService
from apps.treasury.cheques.gl_helpers import (
    get_bank_transfer_in_transit_account,
    get_creditors_control_account,
)
from apps.treasury.cheques.models import (
    ChequeCancellation,
    ChequeClearingEvent,
    IssuedCheque,
)


BLOCKED_CHEQUE_STATUSES = {
    ChequeLeaf.Status.ISSUED,
    ChequeLeaf.Status.PRESENTED,
    ChequeLeaf.Status.CLEARED,
    ChequeLeaf.Status.BOUNCED,
    ChequeLeaf.Status.CANCELLED,
    ChequeLeaf.Status.STOP_PAYMENT,
    ChequeLeaf.Status.STOPPED,
    ChequeLeaf.Status.LOST,
    ChequeLeaf.Status.DAMAGED,
    ChequeLeaf.Status.LOST_DAMAGED,
    ChequeLeaf.Status.SKIPPED,
    ChequeLeaf.Status.STALE,
}


def _check_branch_scope(company, user, obj, field_label: str = "bank account"):
    if not user or getattr(user, "is_superuser", False):
        return
    from apps.accounts_rbac.models import CompanyMembership

    mem = CompanyMembership.objects.select_related("role").filter(
        user=user, company=company, is_active=True
    ).first()
    if not mem:
        return
    if mem.data_scope == CompanyMembership.DataScope.BRANCH:
        branch_ids = set(mem.branches.values_list("id", flat=True))
        if getattr(obj, "branch_id", None) and obj.branch_id not in branch_ids:
            raise ValidationError(f"You do not have branch access scope for this {field_label}.")


class BankAccountQueryService:
    @staticmethod
    def list_eligible_accounts(*, company, user=None, membership=None, currency: str = "", include_inactive: bool = False):
        qs = BankAccount.objects.select_related(
            "bank_branch__bank", "branch", "gl_account", "project"
        ).filter(company=company)
        if not include_inactive:
            qs = qs.filter(status=BankAccount.Status.ACTIVE)
        if currency:
            qs = qs.filter(currency__iexact=currency.strip())
        if membership and user:
            qs = scope_queryset(qs, membership, user, owner_field=None)
        elif user and not getattr(user, "is_superuser", False):
            from apps.accounts_rbac.models import CompanyMembership

            mem = CompanyMembership.objects.filter(user=user, company=company, is_active=True).first()
            if mem:
                qs = scope_queryset(qs, mem, user, owner_field=None)
        return qs

    @staticmethod
    def serialize_selector_row(ba: BankAccount) -> dict:
        agg = LedgerEntry.objects.filter(company=ba.company, account=ba.gl_account).aggregate(
            d=Sum("base_debit"), c=Sum("base_credit")
        )
        book_bal = (ba.gl_account.opening_debit - ba.gl_account.opening_credit) + (
            (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
        )
        active_books = ba.cheque_books.filter(status=ChequeBook.BookStatus.ACTIVE, is_active=True).count()
        avail_cheques = ba.cheques.filter(
            company=ba.company,
            direction=ChequeLeaf.Direction.ISSUED,
            status=ChequeLeaf.Status.AVAILABLE,
            reserved_voucher__isnull=True,
            voucher__isnull=True,
            cheque_book__status=ChequeBook.BookStatus.ACTIVE,
            cheque_book__is_active=True,
        ).count()
        return {
            "id": str(ba.id),
            "account_name": ba.account_name,
            "account_code": ba.account_code,
            "bank_name": ba.bank_branch.bank.name if ba.bank_branch else "",
            "branch_name": ba.bank_branch.name if ba.bank_branch else "",
            "company_branch": str(ba.branch_id) if ba.branch_id else None,
            "account_number_masked": ba.account_number_masked,
            "account_type": ba.account_type,
            "currency": ba.currency,
            "gl_account": str(ba.gl_account_id),
            "gl_code": ba.gl_account.code,
            "gl_name": ba.gl_account.name,
            "current_balance": str(book_bal),
            "cheque_facility_enabled": ba.cheque_facility_enabled,
            "available_cheque_books_count": active_books,
            "available_cheques_count": avail_cheques,
            "status": ba.status,
        }


class ChequeAvailabilityService:
    @staticmethod
    def get_available_cheques(
        *,
        company,
        bank_account: BankAccount,
        user=None,
        membership=None,
        voucher_id=None,
    ) -> list[ChequeLeaf]:
        if bank_account.company_id != company.id:
            raise ValidationError("Selected bank account does not belong to this company.")
        if bank_account.status != BankAccount.Status.ACTIVE:
            raise ValidationError(
                f"Bank account '{bank_account.account_name}' is {bank_account.status} and cannot issue cheques."
            )
        if not bank_account.cheque_facility_enabled:
            raise ValidationError(
                f"Cheque facility is disabled on bank account '{bank_account.account_name}'."
            )
        _check_branch_scope(company, user, bank_account, "bank account")

        base_q = Q(status=ChequeLeaf.Status.AVAILABLE, reserved_voucher__isnull=True, voucher__isnull=True)
        if voucher_id:
            base_q = base_q | Q(status=ChequeLeaf.Status.RESERVED, reserved_voucher_id=voucher_id)

        qs = (
            ChequeLeaf.objects.select_related("cheque_book", "bank_account__bank_branch__bank")
            .filter(
                base_q,
                company=company,
                bank_account=bank_account,
                direction=ChequeLeaf.Direction.ISSUED,
                cheque_book__status=ChequeBook.BookStatus.ACTIVE,
                cheque_book__is_active=True,
            )
            .exclude(status__in=BLOCKED_CHEQUE_STATUSES)
            .order_by("cheque_number")
        )
        return list(qs)


class ChequeReservationService:
    @staticmethod
    @transaction.atomic
    def reserve_leaf(
        *,
        company,
        bank_account: BankAccount,
        leaf_id,
        user,
        voucher: Voucher | None = None,
        cheque_date: date | None = None,
        amount: Decimal | None = None,
        party: Party | None = None,
        reason: str = "",
        expiry_hours: int = 24,
    ) -> ChequeLeaf:
        if bank_account.company_id != company.id or bank_account.status != BankAccount.Status.ACTIVE:
            raise ValidationError("Cannot reserve a cheque on a frozen, closed, or cross-company bank account.")
        if not bank_account.cheque_facility_enabled:
            raise ValidationError("Cheque facility is disabled on the selected bank account.")
        _check_branch_scope(company, user, bank_account, "bank account")

        try:
            leaf = ChequeLeaf.objects.select_for_update().get(id=leaf_id, company=company)
        except ChequeLeaf.DoesNotExist:
            raise ValidationError("Selected cheque leaf does not exist for this company.")

        if leaf.bank_account_id != bank_account.id:
            raise ValidationError(
                f"Cheque leaf #{leaf.cheque_number} belongs to '{leaf.bank_account.account_name}', "
                f"not '{bank_account.account_name}'."
            )
        if leaf.direction != ChequeLeaf.Direction.ISSUED:
            raise ValidationError("Only issued-series cheque leaves can be reserved for payment/contra.")
        if leaf.cheque_book and (
            leaf.cheque_book.status != ChequeBook.BookStatus.ACTIVE or not leaf.cheque_book.is_active
        ):
            raise ValidationError(f"Cheque book '{leaf.cheque_book.book_code}' is {leaf.cheque_book.status}.")

        same_voucher_reserved = bool(
            voucher and leaf.status == ChequeLeaf.Status.RESERVED and leaf.reserved_voucher_id == voucher.id
        )
        if not same_voucher_reserved:
            if leaf.status in BLOCKED_CHEQUE_STATUSES or leaf.status == ChequeLeaf.Status.RESERVED or leaf.reserved_voucher_id:
                owner_info = (
                    f" by voucher {leaf.reserved_voucher.voucher_no or leaf.reserved_voucher_id}"
                    if leaf.reserved_voucher_id
                    else ""
                )
                raise ValidationError(
                    f"Cheque leaf #{leaf.cheque_number} is {leaf.status}{owner_info} and cannot be selected."
                )

        # Release any previously held reserved leaf for this same voucher when switching leaves
        if voucher:
            prev_leaves = ChequeLeaf.objects.select_for_update().filter(
                company=company,
                reserved_voucher=voucher,
                status=ChequeLeaf.Status.RESERVED,
            ).exclude(id=leaf.id)
            for prev_lf in prev_leaves:
                ChequeReservationService.release_reservation(
                    leaf=prev_lf,
                    user=user,
                    reason=f"Released on voucher {voucher.voucher_no or voucher.id} cheque switch",
                )

        prev_status = leaf.status
        now = timezone.now()
        leaf.status = ChequeLeaf.Status.RESERVED
        leaf.reserved_voucher = voucher
        leaf.reserved_by = user
        leaf.reserved_at = now
        leaf.reservation_expires_at = now + timedelta(hours=expiry_hours)
        if cheque_date:
            leaf.cheque_date = cheque_date
        if amount is not None:
            leaf.amount = Decimal(str(amount)).quantize(Decimal("0.01"))
        if party:
            leaf.party = party
            leaf.party_name = party.name
        if reason:
            leaf.purpose = reason[:200]
        leaf.save()

        ChequeClearingEvent.objects.create(
            company=company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.RESERVED,
            event_date=timezone.localdate(),
            from_status=prev_status,
            to_status=ChequeLeaf.Status.RESERVED,
            voucher=voucher,
            actor=user,
            notes=reason or f"Reserved for voucher {(voucher.voucher_no or str(voucher.id)[:8]) if voucher else 'manual'}",
        )
        log_cheque_audit(
            company=company,
            action="CHEQUE_RESERVED",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": prev_status},
            new_state={
                "status": ChequeLeaf.Status.RESERVED,
                "voucher_id": str(voucher.id) if voucher else "",
                "bank_account": bank_account.account_name,
            },
            notes=reason,
        )
        return leaf

    @staticmethod
    @transaction.atomic
    def release_reservation(*, leaf: ChequeLeaf, user=None, voucher: Voucher | None = None, reason: str = "") -> ChequeLeaf:
        leaf = ChequeLeaf.objects.select_for_update().get(pk=leaf.pk)
        if leaf.status in BLOCKED_CHEQUE_STATUSES:
            raise ValidationError(
                f"Cheque #{leaf.cheque_number} is already {leaf.status} and cannot return to AVAILABLE."
            )
        if leaf.status != ChequeLeaf.Status.RESERVED:
            raise ValidationError(f"Cheque #{leaf.cheque_number} is not RESERVED (status: {leaf.status}).")
        if voucher and leaf.reserved_voucher_id and leaf.reserved_voucher_id != voucher.id:
            raise ValidationError("Cannot release reservation belonging to another voucher.")

        leaf.status = ChequeLeaf.Status.AVAILABLE
        leaf.reserved_voucher = None
        leaf.reserved_by = None
        leaf.reserved_at = None
        leaf.reservation_expires_at = None
        leaf.amount = Decimal("0.00")
        leaf.cheque_date = None
        leaf.purpose = ""
        leaf.save()

        ChequeClearingEvent.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.CREATED,
            event_date=timezone.localdate(),
            from_status=ChequeLeaf.Status.RESERVED,
            to_status=ChequeLeaf.Status.AVAILABLE,
            actor=user,
            notes=reason or "Reservation released back to AVAILABLE inventory",
        )
        log_cheque_audit(
            company=leaf.company,
            action="CHEQUE_RESERVATION_RELEASED",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": ChequeLeaf.Status.RESERVED},
            new_state={"status": ChequeLeaf.Status.AVAILABLE},
            notes=reason,
        )
        return leaf

    @staticmethod
    @transaction.atomic
    def validate_and_issue_on_post(*, voucher: Voucher, user) -> ChequeLeaf | None:
        payload = voucher.operational_payload or {}
        pay_mode = str(payload.get("payment_mode") or payload.get("instrument_type") or "").upper()
        leaf_id = payload.get("cheque_leaf_id") or payload.get("cheque_leaf")

        reserved_leaf = ChequeLeaf.objects.select_for_update().filter(
            company=voucher.company, reserved_voucher=voucher
        ).first()
        if not leaf_id and reserved_leaf:
            leaf_id = str(reserved_leaf.id)

        if pay_mode == "CHEQUE" and voucher.voucher_type in ("PAYMENT", "CONTRA", "SUBCONTRACTOR_PAYMENT", "LABOR_PAYMENT", "SUPPLIER_ADVANCE"):
            if not leaf_id:
                raise ValidationError(
                    "Cheque payment requires selecting an available cheque leaf linked to the selected bank account."
                )

        if not leaf_id:
            return None

        try:
            leaf = ChequeLeaf.objects.select_for_update().get(id=leaf_id, company=voucher.company)
        except ChequeLeaf.DoesNotExist:
            raise ValidationError("Linked cheque leaf does not exist.")

        # Validate issuing/sending bank account ownership at posting time
        expected_ba_id = payload.get("source_bank_account_id") or payload.get("bank_account_id")
        if expected_ba_id and str(leaf.bank_account_id) != str(expected_ba_id):
            raise ValidationError(
                f"Cheque #{leaf.cheque_number} belongs to '{leaf.bank_account.account_name}', not the selected bank account."
            )
        if not voucher.lines.filter(account=leaf.bank_account.gl_account, credit__gt=0).exists():
            raise ValidationError(
                f"Posting blocked: Cheque #{leaf.cheque_number} bank account '{leaf.bank_account.account_name}' must be credited on the voucher."
            )

        if leaf.status in BLOCKED_CHEQUE_STATUSES:
            raise ValidationError(f"Cheque #{leaf.cheque_number} is {leaf.status} and cannot be posted.")
        if leaf.reserved_voucher_id and leaf.reserved_voucher_id != voucher.id:
            raise ValidationError(
                f"Cheque #{leaf.cheque_number} is reserved by another active voucher."
            )

        chq_date_raw = payload.get("cheque_date") or payload.get("instrument_date")
        chq_date = date.fromisoformat(str(chq_date_raw)[:10]) if chq_date_raw else voucher.voucher_date
        bank_credit_line = voucher.lines.filter(account=leaf.bank_account.gl_account, credit__gt=0).first()
        chq_amt = bank_credit_line.credit if bank_credit_line else voucher.net_amount

        prev_status = leaf.status
        leaf.status = ChequeLeaf.Status.ISSUED
        leaf.voucher = voucher
        leaf.reserved_voucher = None
        leaf.cheque_date = chq_date
        leaf.amount = chq_amt
        leaf.currency = leaf.bank_account.currency
        leaf.party = voucher.party
        leaf.party_name = voucher.party_name or payload.get("payee_name") or (voucher.party.name if voucher.party else "Internal Transfer")
        leaf.project = voucher.project
        leaf.purpose = voucher.narration[:200]
        leaf.signing_authority = user
        leaf.save()

        IssuedCheque.objects.update_or_create(
            leaf=leaf,
            defaults={
                "company": voucher.company,
                "cheque_book": leaf.cheque_book,
                "bank_account": leaf.bank_account,
                "payee_type": (
                    IssuedCheque.PayeeType.CONTRACTOR
                    if voucher.party and voucher.party.party_type == Party.PartyType.SUBCONTRACTOR
                    else IssuedCheque.PayeeType.EMPLOYEE
                    if voucher.party and voucher.party.party_type == Party.PartyType.EMPLOYEE
                    else IssuedCheque.PayeeType.OTHER
                    if voucher.voucher_type == Voucher.VoucherType.CONTRA
                    else IssuedCheque.PayeeType.SUPPLIER
                ),
                "party": voucher.party,
                "payee_name": leaf.party_name,
                "amount": chq_amt,
                "currency": leaf.bank_account.currency,
                "exchange_rate": voucher.exchange_rate,
                "cheque_date": chq_date,
                "issue_date": voucher.voucher_date,
                "payment_voucher": voucher,
                "invoice_reference": voucher.reference_no or leaf.cheque_number,
                "project": voucher.project,
                "purpose": voucher.narration[:255],
                "prepared_by": voucher.created_by,
                "authorized_by": user,
                "workflow_status": IssuedCheque.WorkflowStatus.ISSUED,
            },
        )
        ChequeClearingEvent.objects.create(
            company=voucher.company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.ISSUED,
            event_date=voucher.voucher_date,
            from_status=prev_status,
            to_status=ChequeLeaf.Status.ISSUED,
            voucher=voucher,
            actor=user,
            notes=f"Issued on voucher post ({voucher.voucher_no})",
        )
        ChequeBookService.sync_book_stock_status(leaf.cheque_book, actor=user)
        log_cheque_audit(
            company=voucher.company,
            action="CHEQUE_ISSUED_ON_VOUCHER_POST",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": prev_status},
            new_state={"status": ChequeLeaf.Status.ISSUED, "voucher_no": voucher.voucher_no, "amount": str(chq_amt)},
        )
        return leaf

    @staticmethod
    @transaction.atomic
    def handle_voucher_cancel_or_reverse(*, voucher: Voucher, user, reversal_voucher: Voucher | None = None, reason: str = ""):
        # 1. Draft/submitted cancellation: release ONLY RESERVED leaves
        for lf in ChequeLeaf.objects.select_for_update().filter(company=voucher.company, reserved_voucher=voucher, status=ChequeLeaf.Status.RESERVED):
            ChequeReservationService.release_reservation(
                leaf=lf, user=user, voucher=voucher, reason=reason or f"Voucher {voucher.voucher_no or voucher.id} cancelled"
            )

        # 2. Posted voucher reversal: NEVER return an ISSUED cheque back to AVAILABLE! Keep audit history & cancel leaf cleanly.
        if reversal_voucher is not None:
            for lf in ChequeLeaf.objects.select_for_update().filter(company=voucher.company, voucher=voucher, direction=ChequeLeaf.Direction.ISSUED):
                prev = lf.status
                if lf.status != ChequeLeaf.Status.CANCELLED:
                    lf.status = ChequeLeaf.Status.CANCELLED
                lf.reversal_voucher = reversal_voucher
                lf.bounce_reason = (reason or f"Voucher {voucher.voucher_no} reversed")[:255]
                lf.save(update_fields=["status", "reversal_voucher", "bounce_reason", "updated_at"])
                if hasattr(lf, "issued_profile"):
                    prof = lf.issued_profile
                    prof.workflow_status = IssuedCheque.WorkflowStatus.CANCELLED
                    prof.save(update_fields=["workflow_status", "updated_at"])
                ChequeCancellation.objects.create(
                    company=voucher.company,
                    cheque_leaf=lf,
                    cancellation_kind=ChequeCancellation.CancellationKind.ISSUED_CANCEL,
                    reason=lf.bounce_reason,
                    requested_by=user,
                    approved_by=user,
                    reversal_voucher=reversal_voucher,
                )
                ChequeClearingEvent.objects.create(
                    company=voucher.company,
                    cheque_leaf=lf,
                    event_type=ChequeClearingEvent.EventType.REVERSED,
                    event_date=reversal_voucher.voucher_date,
                    from_status=prev,
                    to_status=lf.status,
                    voucher=reversal_voucher,
                    actor=user,
                    notes=f"Preserved cheque #{lf.cheque_number} on reversal {reversal_voucher.voucher_no}",
                )
                log_cheque_audit(
                    company=voucher.company,
                    action="CHEQUE_VOUCHER_REVERSED",
                    actor=user,
                    cheque_leaf=lf,
                    previous_state={"status": prev},
                    new_state={"status": lf.status, "reversal_voucher_no": reversal_voucher.voucher_no},
                    notes=lf.bounce_reason,
                )


class BankTransactionService:
    @staticmethod
    @transaction.atomic
    def sync_for_voucher(*, voucher: Voucher) -> BankTransaction | None:
        lines = list(voucher.lines.select_related("account").all())
        if not lines:
            return None

        payload = voucher.operational_payload or {}
        bank_acc_by_gl = {
            ba.gl_account_id: ba
            for ba in BankAccount.objects.filter(company=voucher.company, gl_account_id__in=[l.account_id for l in lines])
        }
        cash_acc_by_gl = {
            ca.gl_account_id: ca
            for ca in CashAccount.objects.filter(company=voucher.company, gl_account_id__in=[l.account_id for l in lines])
        }
        if not bank_acc_by_gl and voucher.voucher_type != Voucher.VoucherType.CONTRA:
            return None

        # Determine Primary Bank, Counter Bank & Cash Account cleanly
        primary_ba = None
        counter_ba = None
        cash_acc = next(iter(cash_acc_by_gl.values()), None)

        src_ba_id = payload.get("source_bank_account_id") or payload.get("bank_account_id")
        dst_ba_id = payload.get("destination_bank_account_id")
        if src_ba_id:
            primary_ba = BankAccount.objects.filter(id=src_ba_id, company=voucher.company).first()
        if dst_ba_id:
            counter_ba = BankAccount.objects.filter(id=dst_ba_id, company=voucher.company).first()

        if not primary_ba:
            # Prefer bank line on credit side first for payments/withdrawals, or any bank line
            for l in lines:
                if l.account_id in bank_acc_by_gl:
                    primary_ba = bank_acc_by_gl[l.account_id]
                    break
        if not counter_ba and primary_ba:
            for l in lines:
                ba = bank_acc_by_gl.get(l.account_id)
                if ba and ba.id != primary_ba.id:
                    counter_ba = ba
                    break

        if not primary_ba and not counter_ba:
            return None

        txn_kind = BankTransaction.TransactionKind.OTHER
        if voucher.voucher_type == Voucher.VoucherType.CONTRA:
            tk = str(payload.get("contra_type") or payload.get("transfer_kind") or "").upper()
            if tk in ("CASH_TO_BANK", "CASH_DEPOSIT"):
                txn_kind = BankTransaction.TransactionKind.CASH_TO_BANK
            elif tk in ("BANK_TO_CASH", "CASH_WITHDRAWAL"):
                txn_kind = BankTransaction.TransactionKind.BANK_TO_CASH
            elif tk == "BANK_TRANSFER_IN_TRANSIT":
                txn_kind = BankTransaction.TransactionKind.BANK_TRANSFER_IN_TRANSIT
            elif tk == "INCOMING_TRANSFER_CONFIRMATION":
                txn_kind = BankTransaction.TransactionKind.INCOMING_TRANSFER_CONFIRMATION
            else:
                txn_kind = BankTransaction.TransactionKind.BANK_TO_BANK
        elif voucher.voucher_type in ("PAYMENT", "SUBCONTRACTOR_PAYMENT", "LABOR_PAYMENT", "SUPPLIER_ADVANCE"):
            txn_kind = BankTransaction.TransactionKind.PAYMENT
        elif voucher.voucher_type in ("RECEIPT", "CUSTOMER_ADVANCE"):
            txn_kind = BankTransaction.TransactionKind.RECEIPT

        pay_mode = str(payload.get("payment_mode") or payload.get("instrument_type") or "").upper()
        if pay_mode == "CHEQUE":
            method = BankTransaction.Method.CHEQUE
        elif pay_mode == "CASH" or txn_kind == BankTransaction.TransactionKind.CASH_TO_BANK:
            method = BankTransaction.Method.CASH
        elif pay_mode in ("QR_WALLET", "IPS", "RTGS", "ELECTRONIC"):
            method = BankTransaction.Method.ELECTRONIC
        else:
            method = BankTransaction.Method.TRANSFER

        leaf = (
            ChequeLeaf.objects.filter(voucher=voucher).first()
            or ChequeLeaf.objects.filter(reserved_voucher=voucher).first()
        )
        amt = max((max(l.debit, l.credit) for l in lines), default=voucher.net_amount)

        if txn_kind == BankTransaction.TransactionKind.BANK_TO_BANK:
            dr_recon = BankTransaction.ReconStatus.UNRECONCILED
            cr_recon = BankTransaction.ReconStatus.UNRECONCILED
        elif txn_kind in (BankTransaction.TransactionKind.CASH_TO_BANK, BankTransaction.TransactionKind.INCOMING_TRANSFER_CONFIRMATION, BankTransaction.TransactionKind.RECEIPT):
            dr_recon = BankTransaction.ReconStatus.UNRECONCILED
            cr_recon = BankTransaction.ReconStatus.NOT_APPLICABLE
        else:
            dr_recon = BankTransaction.ReconStatus.NOT_APPLICABLE
            cr_recon = BankTransaction.ReconStatus.UNRECONCILED

        payee_lbl = voucher.party_name or (counter_ba.account_name if counter_ba else (cash_acc.name if cash_acc else ""))
        obj, _ = BankTransaction.objects.update_or_create(
            voucher=voucher,
            defaults={
                "company": voucher.company,
                "branch": voucher.branch,
                "fiscal_year": voucher.fiscal_year,
                "transaction_kind": txn_kind,
                "method": method,
                "bank_account": primary_ba,
                "counter_bank_account": counter_ba,
                "cash_account": cash_acc,
                "cheque_leaf": leaf,
                "txn_date": voucher.voucher_date,
                "amount": amt,
                "currency": voucher.currency,
                "reference_no": voucher.reference_no or (leaf.cheque_number if leaf else ""),
                "payee_or_account": payee_lbl[:200],
                "narration": voucher.narration,
                "debit_reconciliation_status": dr_recon,
                "credit_reconciliation_status": cr_recon,
            },
        )
        return obj


class ContraVoucherService:
    CONTRA_TYPES = {
        "CASH_TO_BANK",
        "BANK_TO_CASH",
        "BANK_TO_BANK",
        "BANK_TRANSFER_IN_TRANSIT",
        "INCOMING_TRANSFER_CONFIRMATION",
    }

    @staticmethod
    @transaction.atomic
    def create_contra_voucher(*, company, user, data: dict, submit: bool = False, approve: bool = False, post_now: bool = False) -> Voucher:
        contra_type = str(data.get("contra_type") or data.get("transfer_kind") or "CASH_TO_BANK").upper()
        if contra_type not in ContraVoucherService.CONTRA_TYPES:
            raise ValidationError(f"Unsupported Contra transaction type: {contra_type}")

        vdate = data["voucher_date"] if isinstance(data["voucher_date"], date) else date.fromisoformat(str(data["voucher_date"])[:10])
        amount = Decimal(str(data.get("amount") or "0.00")).quantize(Decimal("0.01"))
        if amount <= 0:
            raise ValidationError("Contra transfer amount must be greater than zero.")

        if data.get("party") or data.get("bill_wise_allocations"):
            raise ValidationError(
                "Contra vouchers cannot reference external suppliers/customers or invoice allocations. Use Payment/Receipt vouchers."
            )

        instrument = str(data.get("payment_mode") or data.get("instrument_type") or "TRANSFER").upper()
        cheque_leaf_id = data.get("cheque_leaf_id") or data.get("cheque_leaf")
        project = data.get("project")
        narration = (data.get("narration") or "").strip()
        ref_no = (data.get("reference_no") or "").strip()

        src_ba: BankAccount | None = None
        dst_ba: BankAccount | None = None
        cash_acc: CashAccount | None = None
        src_gl: Account | None = None
        dst_gl: Account | None = None

        def _get_active_bank(ba_id, label: str) -> BankAccount:
            if not ba_id:
                raise ValidationError(f"{label} bank account is required.")
            ba = BankAccount.objects.select_related("gl_account").filter(id=ba_id, company=company).first()
            if not ba:
                raise ValidationError(f"{label} bank account not found for this company.")
            if ba.status != BankAccount.Status.ACTIVE:
                raise ValidationError(f"{label} bank account '{ba.account_name}' is {ba.status} and cannot be used.")
            _check_branch_scope(company, user, ba, f"{label} bank account")
            return ba

        def _get_active_cash(ca_id) -> tuple[CashAccount | None, Account]:
            if ca_id:
                ca = CashAccount.objects.select_related("gl_account").filter(id=ca_id, company=company).first()
                if ca:
                    if not ca.is_active or ca.is_frozen:
                        raise ValidationError(f"Cash account '{ca.name}' is inactive/frozen.")
                    return ca, ca.gl_account
                gl = Account.objects.filter(id=ca_id, company=company, control_role=Account.ControlRole.CASH, is_group=False, is_active=True).first()
                if gl:
                    return None, gl
            raise ValidationError("A valid active Cash Account belonging to this company is required.")

        if contra_type == "CASH_TO_BANK":
            cash_acc, src_gl = _get_active_cash(data.get("cash_account_id") or data.get("source_cash_account"))
            dst_ba = _get_active_bank(data.get("destination_bank_account_id") or data.get("bank_account_id"), "Destination")
            dst_gl = dst_ba.gl_account
            default_narr = f"Cash deposited to {dst_ba.account_name}"

        elif contra_type == "BANK_TO_CASH":
            src_ba = _get_active_bank(data.get("source_bank_account_id") or data.get("bank_account_id"), "Source")
            cash_acc, dst_gl = _get_active_cash(data.get("cash_account_id") or data.get("destination_cash_account"))
            src_gl = src_ba.gl_account
            default_narr = f"Cash withdrawn from {src_ba.account_name}"

        elif contra_type == "BANK_TO_BANK":
            src_ba = _get_active_bank(data.get("source_bank_account_id"), "Sending")
            dst_ba = _get_active_bank(data.get("destination_bank_account_id"), "Receiving")
            if src_ba.id == dst_ba.id:
                raise ValidationError("Sending and receiving bank accounts must be different.")
            src_gl = src_ba.gl_account
            dst_gl = dst_ba.gl_account
            default_narr = f"Bank transfer {src_ba.account_name} -> {dst_ba.account_name}"

        elif contra_type == "BANK_TRANSFER_IN_TRANSIT":
            src_ba = _get_active_bank(data.get("source_bank_account_id"), "Sending")
            src_gl = src_ba.gl_account
            dst_gl = get_bank_transfer_in_transit_account(company)
            default_narr = f"Bank transfer in-transit initiated from {src_ba.account_name}"

        else:  # INCOMING_TRANSFER_CONFIRMATION
            dst_ba = _get_active_bank(data.get("destination_bank_account_id"), "Receiving")
            src_gl = get_bank_transfer_in_transit_account(company)
            dst_gl = dst_ba.gl_account
            default_narr = f"Incoming bank transfer confirmed into {dst_ba.account_name}"

        if src_gl.id == dst_gl.id:
            raise ValidationError("Debit and Credit GL accounts must be different in Contra voucher.")

        # Cheque validation when Contra uses cheque instrument (ONLY from Source/Sending bank)
        if instrument == "CHEQUE":
            if contra_type not in ("BANK_TO_CASH", "BANK_TO_BANK", "BANK_TRANSFER_IN_TRANSIT") or not src_ba:
                raise ValidationError("Cheque withdrawal/transfer requires a Source/Sending Bank Account.")
            if not cheque_leaf_id:
                raise ValidationError("Select an available cheque leaf belonging to the Source Bank Account.")
            avail_ids = {str(lf.id) for lf in ChequeAvailabilityService.get_available_cheques(company=company, bank_account=src_ba, user=user)}
            if str(cheque_leaf_id) not in avail_ids:
                lf = ChequeLeaf.objects.filter(id=cheque_leaf_id, company=company).first()
                if not lf:
                    raise ValidationError("Selected cheque leaf does not exist.")
                if lf.bank_account_id != src_ba.id:
                    raise ValidationError(
                        f"Cheque #{lf.cheque_number} belongs to '{lf.bank_account.account_name}', not sending bank '{src_ba.account_name}'."
                    )
                raise ValidationError(f"Cheque #{lf.cheque_number} is {lf.status} and not AVAILABLE for issuance.")

        ccy = (src_ba.currency if src_ba else (dst_ba.currency if dst_ba else company.base_currency))
        if src_ba and dst_ba and src_ba.currency != dst_ba.currency:
            raise ValidationError(
                f"Currency mismatch between sending bank ({src_ba.currency}) and receiving bank ({dst_ba.currency})."
            )

        voucher = VoucherService.create_draft(
            company=company,
            user=user,
            data={
                "voucher_type": Voucher.VoucherType.CONTRA,
                "voucher_date": vdate,
                "branch": data.get("branch") or (src_ba.branch if src_ba else (dst_ba.branch if dst_ba else None)),
                "project": project,
                "currency": ccy,
                "reference_no": ref_no,
                "narration": narration or default_narr,
                "gross_amount": amount,
                "net_amount": amount,
                "operational_payload": {
                    "contra_type": contra_type,
                    "payment_mode": instrument,
                    "source_bank_account_id": str(src_ba.id) if src_ba else "",
                    "destination_bank_account_id": str(dst_ba.id) if dst_ba else "",
                    "cash_account_id": str(cash_acc.id) if cash_acc else "",
                    "cheque_leaf_id": str(cheque_leaf_id) if cheque_leaf_id else "",
                    "cheque_date": str(data.get("cheque_date") or vdate.isoformat()),
                },
            },
            lines_data=[
                {"account": dst_gl, "debit": amount, "credit": Decimal("0.00"), "project": project, "description": default_narr},
                {"account": src_gl, "debit": Decimal("0.00"), "credit": amount, "project": project, "description": default_narr},
            ],
        )

        if instrument == "CHEQUE" and cheque_leaf_id and src_ba:
            chq_dt = date.fromisoformat(str(data.get("cheque_date") or vdate.isoformat())[:10])
            lf = ChequeReservationService.reserve_leaf(
                company=company,
                bank_account=src_ba,
                leaf_id=cheque_leaf_id,
                user=user,
                voucher=voucher,
                cheque_date=chq_dt,
                amount=amount,
                reason=f"Reserved for Contra {contra_type}",
            )
            voucher.reference_no = lf.cheque_number
            voucher.save(update_fields=["reference_no"])

        BankTransactionService.sync_for_voucher(voucher=voucher)

        if submit or approve or post_now:
            voucher = VoucherService.submit_voucher(voucher=voucher, user=user)
        if approve or post_now:
            from apps.accounting.services import ApprovalService

            voucher = ApprovalService.approve_voucher(voucher=voucher, user=user, comment="Contra approved")
        if post_now:
            voucher = PostingService.post_voucher(voucher=voucher, user=user)
        return voucher


class PaymentVoucherService:
    @staticmethod
    @transaction.atomic
    def create_payment_voucher(*, company, user, data: dict, submit: bool = False, approve: bool = False, post_now: bool = False) -> Voucher:
        vdate = data["voucher_date"] if isinstance(data["voucher_date"], date) else date.fromisoformat(str(data["voucher_date"])[:10])
        amount = Decimal(str(data.get("amount") or data.get("gross_amount") or "0.00")).quantize(Decimal("0.01"))
        if amount <= 0:
            raise ValidationError("Payment amount must be greater than zero.")

        pay_mode = str(data.get("payment_mode") or "BANK_TRANSFER").upper()
        cheque_leaf_id = data.get("cheque_leaf_id") or data.get("cheque_leaf")
        bank_account_id = data.get("bank_account_id") or data.get("bank_account")
        cash_account_id = data.get("cash_account_id") or data.get("cash_account")

        party = data.get("party")
        if isinstance(party, str) and party:
            party = Party.objects.filter(id=party, company=company).first()
        project = data.get("project")

        credit_acc: Account | None = None
        selected_ba: BankAccount | None = None
        selected_ca: CashAccount | None = None

        if pay_mode == "CASH":
            if cash_account_id:
                selected_ca = CashAccount.objects.select_related("gl_account").filter(id=cash_account_id, company=company).first()
                if selected_ca:
                    if not selected_ca.is_active or selected_ca.is_frozen:
                        raise ValidationError(f"Cash account '{selected_ca.name}' is frozen or inactive.")
                    credit_acc = selected_ca.gl_account
                else:
                    credit_acc = Account.objects.filter(id=cash_account_id, company=company, control_role=Account.ControlRole.CASH, is_group=False).first()
            if not credit_acc:
                credit_acc = Account.objects.filter(company=company, control_role=Account.ControlRole.CASH, is_group=False, is_active=True).first()
            if not credit_acc:
                raise ValidationError("Active Cash Account is required for Cash Payment.")
        else:
            if not bank_account_id:
                raise ValidationError("Bank Account is mandatory for Bank Transfer / Cheque payment.")
            selected_ba = BankAccount.objects.select_related("gl_account").filter(id=bank_account_id, company=company).first()
            if not selected_ba:
                raise ValidationError("Selected Bank Account not found.")
            if selected_ba.status != BankAccount.Status.ACTIVE:
                raise ValidationError(f"Bank account '{selected_ba.account_name}' is {selected_ba.status} and cannot be used.")
            _check_branch_scope(company, user, selected_ba, "bank account")
            credit_acc = selected_ba.gl_account

        if pay_mode == "CHEQUE":
            if not cheque_leaf_id:
                raise ValidationError("Payment Mode Cheque requires selecting an available cheque leaf from the selected bank account.")
            avail_ids = {str(lf.id) for lf in ChequeAvailabilityService.get_available_cheques(company=company, bank_account=selected_ba, user=user)}
            if str(cheque_leaf_id) not in avail_ids:
                lf = ChequeLeaf.objects.filter(id=cheque_leaf_id, company=company).first()
                if not lf:
                    raise ValidationError("Selected cheque leaf does not exist.")
                if lf.bank_account_id != selected_ba.id:
                    raise ValidationError(
                        f"Cheque #{lf.cheque_number} belongs to '{lf.bank_account.account_name}', not '{selected_ba.account_name}'."
                    )
                raise ValidationError(f"Cheque #{lf.cheque_number} is {lf.status} and cannot be selected.")

        debit_acc = data.get("debit_account")
        if isinstance(debit_acc, str) and debit_acc:
            debit_acc = Account.objects.filter(id=debit_acc, company=company, is_group=False, is_active=True).first()
        if not debit_acc:
            debit_acc = get_creditors_control_account(company, party=party)

        if debit_acc.id == credit_acc.id:
            raise ValidationError("Debit and Credit accounts cannot be identical.")

        tds_amt = Decimal(str(data.get("tds_amount") or "0.00")).quantize(Decimal("0.01"))
        net_pay = amount - tds_amt
        lines_data = [
            {
                "account": debit_acc,
                "party": party if debit_acc.requires_subledger else None,
                "debit": amount,
                "credit": Decimal("0.00"),
                "project": project,
                "description": data.get("narration") or f"Payment to {party.name if party else debit_acc.name}",
            }
        ]
        if tds_amt > 0:
            tds_acc = Account.objects.filter(company=company, control_role=Account.ControlRole.TDS_PAYABLE, is_group=False).first()
            if tds_acc:
                lines_data.append({"account": tds_acc, "debit": Decimal("0.00"), "credit": tds_amt, "description": "TDS Withholding"})
            else:
                net_pay = amount
        lines_data.append(
            {
                "account": credit_acc,
                "debit": Decimal("0.00"),
                "credit": net_pay,
                "project": project,
                "description": f"{pay_mode} Payment",
            }
        )

        voucher = VoucherService.create_draft(
            company=company,
            user=user,
            data={
                "voucher_type": Voucher.VoucherType.PAYMENT,
                "voucher_date": vdate,
                "branch": data.get("branch") or (selected_ba.branch if selected_ba else None),
                "project": project,
                "party": party,
                "party_name": data.get("party_name") or (party.name if party else ""),
                "reference_no": data.get("reference_no", ""),
                "narration": data.get("narration") or f"Payment ({pay_mode}) to {party.name if party else debit_acc.name}",
                "gross_amount": amount,
                "tds_amount": tds_amt,
                "net_amount": net_pay,
                "bill_wise_allocations": data.get("bill_wise_allocations") or [],
                "operational_payload": {
                    "payment_mode": pay_mode,
                    "bank_account_id": str(selected_ba.id) if selected_ba else "",
                    "cash_account_id": str(selected_ca.id) if selected_ca else "",
                    "cheque_leaf_id": str(cheque_leaf_id) if cheque_leaf_id else "",
                    "cheque_date": str(data.get("cheque_date") or vdate.isoformat()),
                },
            },
            lines_data=lines_data,
        )

        if pay_mode == "CHEQUE" and cheque_leaf_id and selected_ba:
            chq_dt = date.fromisoformat(str(data.get("cheque_date") or vdate.isoformat())[:10])
            lf = ChequeReservationService.reserve_leaf(
                company=company,
                bank_account=selected_ba,
                leaf_id=cheque_leaf_id,
                user=user,
                voucher=voucher,
                cheque_date=chq_dt,
                amount=net_pay,
                party=party,
                reason=f"Reserved for Payment Voucher {voucher.id}",
            )
            voucher.reference_no = lf.cheque_number
            voucher.save(update_fields=["reference_no"])

        BankTransactionService.sync_for_voucher(voucher=voucher)

        if submit or approve or post_now:
            voucher = VoucherService.submit_voucher(voucher=voucher, user=user)
        if approve or post_now:
            from apps.accounting.services import ApprovalService

            voucher = ApprovalService.approve_voucher(voucher=voucher, user=user, comment="Payment approved")
        if post_now:
            voucher = PostingService.post_voucher(voucher=voucher, user=user)
        return voucher

