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

from apps.accounting.models import Party, Voucher
from apps.banking.models import BankAccount, ChequeLeaf, normalize_cheque_number
from apps.banking.security import encrypt_account_number, hash_account_number, mask_account_number
from apps.party_hub.models import OpenItem
from apps.party_hub.services.allocation import InvoiceAllocationService
from apps.projects.models import Project
from apps.treasury.cheques.audit import log_cheque_audit
from apps.treasury.cheques.gl_helpers import (
    get_cheques_in_hand_account,
    get_debtors_control_account,
    get_treasury_settings,
    post_cheque_voucher,
)
from apps.treasury.cheques.models import ChequeClearingEvent, ReceivedCheque


class ReceivedChequeService:
    @staticmethod
    @transaction.atomic
    def receive_cheque(
        *,
        company,
        deposit_bank_account: BankAccount,
        user,
        cheque_number: str,
        drawer_name: str,
        drawer_bank: str,
        drawer_branch: str = "",
        drawer_account_ref: str = "",
        customer: Party | None = None,
        project: Project | None = None,
        amount: Decimal = Decimal("0.00"),
        currency: str = "",
        exchange_rate: Decimal = Decimal("1.000000"),
        cheque_date: date | None = None,
        received_date: date | None = None,
        receipt_voucher: Voucher | None = None,
        allocations: list[dict] | None = None,
        post_cheque_in_hand: bool = True,
        confirm_duplicate_warning: bool = False,
        purpose: str = "",
    ) -> ReceivedCheque:
        if deposit_bank_account.company_id != company.id:
            raise ValidationError("Deposit bank account does not belong to this company.")
        num = (cheque_number or "").strip()
        if not num:
            raise ValidationError("Cheque number is required.")
        norm_num = normalize_cheque_number(num)
        amt = Decimal(str(amount or "0.00")).quantize(Decimal("0.01"))
        ccy = (currency or deposit_bank_account.currency or "NPR").upper()
        rec_date = received_date or timezone.localdate()
        chq_date = cheque_date or rec_date

        clean_acct = (drawer_account_ref or "").strip()
        fingerprint = hash_account_number(clean_acct) if clean_acct else ""
        masked_acct = mask_account_number(clean_acct) if clean_acct else ""
        encrypted_acct = encrypt_account_number(clean_acct) if clean_acct else ""

        settings_obj = get_treasury_settings(company)
        dup_warning = False
        dup_reason = ""

        # Composite duplicate detection as specified:
        # 1. Exact drawer bank + drawer account fingerprint + cheque no + currency + amount
        if drawer_bank and fingerprint:
            exact_dup = ReceivedCheque.objects.filter(
                company=company,
                drawer_bank__iexact=drawer_bank.strip(),
                drawer_account_fingerprint=fingerprint,
                leaf__normalized_cheque_number=norm_num,
                currency=ccy,
                amount=amt,
            ).exists()
            if exact_dup:
                raise ValidationError(
                    f"Duplicate received cheque {num} ({amt} {ccy}) from {drawer_bank} ({masked_acct})."
                )
        elif drawer_bank:
            # Drawer account unavailable -> raise warning / require explicit confirmation
            ambiguous_matches = ReceivedCheque.objects.filter(
                company=company,
                drawer_bank__iexact=drawer_bank.strip(),
                leaf__normalized_cheque_number=norm_num,
                currency=ccy,
                amount=amt,
            ).exclude(workflow_status=ReceivedCheque.WorkflowStatus.CANCELLED)
            if ambiguous_matches.exists():
                dup_warning = True
                dup_reason = (
                    f"Possible duplicate cheque #{num} from {drawer_bank} ({amt} {ccy}); "
                    f"drawer account unavailable."
                )
                if settings_obj.strict_drawer_duplicate_block and not confirm_duplicate_warning:
                    raise ValidationError(
                        f"{dup_reason} Supply drawer account number or confirm manual duplicate override."
                    )

        if ChequeLeaf.objects.filter(
            bank_account=deposit_bank_account,
            cheque_number=num,
            direction=ChequeLeaf.Direction.RECEIVED,
        ).exists():
            raise ValidationError(f"Duplicate received cheque {num} on deposit account {deposit_bank_account.account_name}.")

        # Stage 0 GL Entry: Dr Cheques-in-Hand (1035), Cr Sundry Debtors
        voucher = receipt_voucher
        if voucher is None and post_cheque_in_hand and amt > 0:
            cih_acc = get_cheques_in_hand_account(company)
            debtors_acc = get_debtors_control_account(company, party=customer)
            voucher = post_cheque_voucher(
                company=company,
                user=user,
                vtype=Voucher.VoucherType.RECEIPT,
                vdate=rec_date,
                project=project,
                party=customer,
                reference_no=num,
                currency=ccy,
                exchange_rate=exchange_rate,
                narration=purpose or f"Cheque #{num} received from {drawer_name or (customer.name if customer else 'Customer')} -> Cheques-in-Hand",
                lines_data=[
                    {
                        "account": cih_acc,
                        "debit": amt,
                        "credit": Decimal("0.00"),
                        "project": project,
                        "description": f"Stage 0 Cheques-in-Hand #{num} ({drawer_bank})",
                    },
                    {
                        "account": debtors_acc,
                        "party": customer if debtors_acc.requires_subledger else None,
                        "debit": Decimal("0.00"),
                        "credit": amt,
                        "project": project,
                        "description": f"Provisional receipt against cheque #{num}",
                    },
                ],
            )
        elif voucher is not None and voucher.company_id != company.id:
            raise ValidationError("Receipt voucher belongs to another company.")

        allocated_refs = []
        if allocations and voucher and customer:
            alloc_result = InvoiceAllocationService.allocate_batch(
                company=company,
                user=user,
                party=customer,
                settlement_voucher=voucher,
                allocations=allocations,
                hub_side=OpenItem.HubSide.RECEIVABLE,
            )
            allocated_refs = alloc_result.get("allocations", [])

        leaf = ChequeLeaf.objects.create(
            company=company,
            bank_account=deposit_bank_account,
            cheque_number=num,
            normalized_cheque_number=norm_num,
            direction=ChequeLeaf.Direction.RECEIVED,
            status=ChequeLeaf.Status.IN_HAND,
            party=customer,
            party_name=(customer.name if customer else drawer_name),
            project=project,
            drawer_name=drawer_name,
            drawer_bank=drawer_bank,
            drawer_account_ref=masked_acct,
            purpose=purpose,
            cheque_date=chq_date,
            receiving_date=rec_date,
            amount=amt,
            currency=ccy,
            voucher=voucher,
        )

        profile = ReceivedCheque.objects.create(
            company=company,
            leaf=leaf,
            deposit_bank_account=deposit_bank_account,
            drawer_name=drawer_name,
            drawer_bank=drawer_bank,
            drawer_branch=drawer_branch,
            drawer_account_encrypted=encrypted_acct,
            drawer_account_masked=masked_acct,
            drawer_account_fingerprint=fingerprint,
            customer=customer,
            amount=amt,
            currency=ccy,
            exchange_rate=exchange_rate,
            cheque_date=chq_date,
            received_date=rec_date,
            receipt_voucher=voucher,
            invoice_references=allocated_refs,
            project=project,
            workflow_status=ReceivedCheque.WorkflowStatus.IN_HAND,
            duplicate_warning=dup_warning,
            duplicate_warning_reason=dup_reason,
        )

        ChequeClearingEvent.objects.create(
            company=company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.RECEIVED,
            event_date=rec_date,
            from_status="",
            to_status=ChequeLeaf.Status.IN_HAND,
            voucher=voucher,
            actor=user,
            notes=f"Cheque #{num} logged into Cheques-in-Hand from {drawer_name} ({drawer_bank})",
        )
        log_cheque_audit(
            company=company,
            action="RECEIVED_CHEQUE_LOGGED",
            actor=user,
            cheque_leaf=leaf,
            new_state={
                "cheque_number": num,
                "amount": str(amt),
                "drawer_bank": drawer_bank,
                "drawer_account_masked": masked_acct,
                "voucher_no": voucher.voucher_no if voucher else "",
                "status": ChequeLeaf.Status.IN_HAND,
            },
        )
        return profile

    @staticmethod
    @transaction.atomic
    def verify_cheque(*, leaf: ChequeLeaf, user, notes: str = "") -> ChequeLeaf:
        leaf = ChequeLeaf.objects.select_for_update().get(pk=leaf.pk)
        if leaf.direction != ChequeLeaf.Direction.RECEIVED:
            raise ValidationError("Verification applies to received cheques.")
        if leaf.status not in (ChequeLeaf.Status.IN_HAND, ChequeLeaf.Status.RECEIVED):
            raise ValidationError(f"Cheque #{leaf.cheque_number} in status {leaf.status} cannot be verified.")

        prev = leaf.status
        leaf.status = ChequeLeaf.Status.VERIFIED
        leaf.save(update_fields=["status", "updated_at"])

        if hasattr(leaf, "received_profile"):
            prof = leaf.received_profile
            prof.workflow_status = ReceivedCheque.WorkflowStatus.VERIFIED
            prof.verified_by = user
            prof.verified_at = timezone.now()
            prof.save(update_fields=["workflow_status", "verified_by", "verified_at", "updated_at"])

        ChequeClearingEvent.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.VERIFIED,
            event_date=timezone.localdate(),
            from_status=prev,
            to_status=ChequeLeaf.Status.VERIFIED,
            actor=user,
            notes=notes or "Physical cheque verified and ready for deposit",
        )
        log_cheque_audit(
            company=leaf.company,
            action="RECEIVED_CHEQUE_VERIFIED",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": prev},
            new_state={"status": ChequeLeaf.Status.VERIFIED},
            notes=notes,
        )
        return leaf

