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

from apps.accounting.models import Account, AdvanceRecord, BillAllocation, Party, Voucher
from apps.accounting.services import PostingService, VoucherService
from apps.banking.models import BankAccount
from apps.party_hub.models import (
    CustomerAdvanceContractRule,
    CustomerReceipt,
    OpenItem,
    RABill,
    ReceiptAllocationReversal,
    RetentionReleaseLog,
    RetentionSchedule,
    SalesInvoice,
)
from apps.treasury.cheques.received_cheques.service import ReceivedChequeService
from .allocation import InvoiceAllocationService
from .ar_billing_service import _find_acc, _q2, log_ar_audit, resolve_ar_accounts


class ARReceiptAllocationService:
    """
    Enterprise Sundry Debtors Receipt, Two-Step Cheque Integration, TDS Withholding Certificate,
    Explicit Multi-Bill Allocation, Concurrency-Safe Reversal, and Retention Release engine.
    """

    @staticmethod
    @transaction.atomic
    def create_receipt(*, company, user, data: dict) -> CustomerReceipt:
        party: Party = data["party"]
        if party.company_id != company.id or party.party_type != Party.PartyType.CUSTOMER:
            raise ValidationError("Selected party must belong to this company and be a Customer.")

        mode = data.get("receipt_mode") or CustomerReceipt.ReceiptMode.BANK_TRANSFER
        rec_date: date = data.get("receipt_date") or timezone.localdate()
        amount = _q2(data.get("amount"))
        bank_charges = _q2(data.get("bank_charges_amount") or "0.00")
        if amount <= 0:
            raise ValidationError("Receipt amount must exceed zero.")

        idempotency_key = (data.get("idempotency_key") or "").strip()
        if idempotency_key:
            existing_v = Voucher.objects.filter(company=company, idempotency_key=idempotency_key).first()
            if existing_v and hasattr(existing_v, "ar_customer_receipt"):
                return existing_v.ar_customer_receipt

        rec_no = (data.get("receipt_no") or "").strip()
        if not rec_no:
            cnt = CustomerReceipt.objects.filter(company=company).count() + 1
            rec_no = f"RCP-{rec_date.strftime('%Y%m')}-{cnt:04d}"
        if CustomerReceipt.objects.filter(company=company, receipt_no=rec_no).exists():
            raise ValidationError(f"Duplicate receipt number '{rec_no}' blocked.")

        accs = resolve_ar_accounts(company, party)
        bank_account: BankAccount | None = data.get("bank_account")
        deposit_acc: Account | None = data.get("deposit_account")
        project = data.get("project")
        currency = (data.get("currency_code") or "NPR").upper()
        ex_rate = Decimal(str(data.get("exchange_rate") or "1.000000"))
        narration = data.get("narration") or f"Customer Receipt ({mode}) — {party.name}"
        ref_no = data.get("reference_no") or rec_no

        cheque_leaf = None
        adv_record = None
        allocations = data.get("allocations") or []

        if mode == CustomerReceipt.ReceiptMode.CHEQUE:
            if not bank_account:
                bank_account = BankAccount.objects.filter(company=company, is_active=True).order_by("-is_default", "account_name").first()
            if not bank_account:
                raise ValidationError("A deposit Bank Account is required to receive a Customer Cheque.")
            cheque_no = (data.get("cheque_number") or "").strip()
            drawer_bank = (data.get("drawer_bank") or "").strip() or "Customer Bank"
            drawer_name = (data.get("drawer_name") or party.name).strip()
            rc_profile = ReceivedChequeService.receive_cheque(
                company=company,
                deposit_bank_account=bank_account,
                user=user,
                cheque_number=cheque_no,
                drawer_name=drawer_name,
                drawer_bank=drawer_bank,
                drawer_branch=data.get("drawer_branch", ""),
                drawer_account_ref=data.get("drawer_account_ref", ""),
                customer=party,
                project=project,
                amount=amount,
                currency=currency,
                exchange_rate=ex_rate,
                cheque_date=data.get("cheque_date") or rec_date,
                received_date=rec_date,
                allocations=None,
                post_cheque_in_hand=True,
                confirm_duplicate_warning=bool(data.get("confirm_duplicate_warning", True)),
                purpose=narration,
            )
            cheque_leaf = rc_profile.leaf
            v = rc_profile.leaf.voucher
            deposit_acc = bank_account.gl_account
        else:
            if mode == CustomerReceipt.ReceiptMode.CASH:
                deposit_acc = deposit_acc or _find_acc(company, Account.ControlRole.CASH, "101")
            elif mode == CustomerReceipt.ReceiptMode.TDS_CERTIFICATE:
                tds_cert = (data.get("tds_certificate_no") or "").strip()
                if not tds_cert:
                    raise ValidationError("TDS Certificate Number is required for Withholding Tax Certificate receipt.")
                deposit_acc = deposit_acc or accs["tds"]
            else:
                if bank_account and bank_account.gl_account_id:
                    deposit_acc = bank_account.gl_account
                deposit_acc = deposit_acc or _find_acc(company, Account.ControlRole.BANK, "102")

            if not deposit_acc:
                raise ValidationError("Valid Cash/Bank/TDS GL deposit account could not be resolved.")

            if mode == CustomerReceipt.ReceiptMode.ADVANCE:
                credit_acc = accs["advance"]
                if not credit_acc:
                    raise ValidationError("Customer Advance Liability (207) GL account missing.")
                vtype = Voucher.VoucherType.RECEIPT
                net_bank = amount - bank_charges
                if net_bank <= 0:
                    raise ValidationError("Net cash received after bank charges must exceed zero.")
                lines_data = [{"account": deposit_acc, "debit": net_bank, "credit": Decimal("0.00"), "project": project, "description": narration}]
                if bank_charges > 0:
                    chg_acc = _find_acc(company, Account.ControlRole.OFFICE_EXPENSES, "51") or accs["deduction_expense"]
                    lines_data.append({"account": chg_acc, "debit": bank_charges, "credit": Decimal("0.00"), "project": project, "description": f"Bank charges on {rec_no}"})
                lines_data.append({
                    "account": credit_acc,
                    "party": party,
                    "debit": Decimal("0.00"),
                    "credit": amount,
                    "project": project,
                    "description": f"Customer Advance / Mobilization from {party.name}",
                })
            elif mode == CustomerReceipt.ReceiptMode.RETENTION_RELEASE:
                retention_id = data.get("retention_id")
                if not retention_id:
                    raise ValidationError("Target RetentionSchedule id is required for a Retention Release receipt.")
                ret_sched = RetentionSchedule.objects.select_for_update().get(
                    pk=retention_id, company=company, party=party, direction=RetentionSchedule.Direction.RECEIVABLE
                )
                if ret_sched.is_disputed or ret_sched.status == RetentionSchedule.Status.DISPUTED:
                    raise ValidationError("Retention schedule is DISPUTED; resolve dispute before release.")
                if amount > ret_sched.remaining_retention:
                    raise ValidationError(
                        f"Retention release ({amount}) exceeds eligible remaining retention ({ret_sched.remaining_retention})."
                    )
                if not accs["retention"]:
                    raise ValidationError("Retention Receivable GL account missing.")
                vtype = Voucher.VoucherType.RECEIPT
                lines_data = [
                    {"account": deposit_acc, "debit": amount, "credit": Decimal("0.00"), "project": project or ret_sched.project, "description": narration},
                    {"account": accs["retention"], "party": party, "debit": Decimal("0.00"), "credit": amount, "project": project or ret_sched.project, "description": f"Retention Release ({ret_sched.contract_ref or ret_sched.certificate_no})"},
                ]
            else:
                credit_acc = accs["debtors"]
                if not credit_acc:
                    raise ValidationError("Sundry Debtors control account missing.")
                vtype = Voucher.VoucherType.RECEIPT
                net_bank = amount - bank_charges
                if net_bank <= 0:
                    raise ValidationError("Net receipt amount after bank charges must exceed zero.")
                lines_data = [{"account": deposit_acc, "debit": net_bank, "credit": Decimal("0.00"), "project": project, "description": narration}]
                if bank_charges > 0:
                    chg_acc = _find_acc(company, Account.ControlRole.OFFICE_EXPENSES, "51") or accs["deduction_expense"]
                    lines_data.append({"account": chg_acc, "debit": bank_charges, "credit": Decimal("0.00"), "project": project, "description": f"Bank charges on {rec_no}"})
                lines_data.append({
                    "account": credit_acc,
                    "party": party,
                    "debit": Decimal("0.00"),
                    "credit": amount,
                    "project": project,
                    "description": narration,
                })

            v = VoucherService.create_draft(
                company=company,
                user=user,
                data={
                    "voucher_type": vtype,
                    "voucher_date": rec_date,
                    "project": project,
                    "party": party,
                    "branch": data.get("branch"),
                    "currency": currency,
                    "exchange_rate": ex_rate,
                    "reference_no": ref_no,
                    "narration": narration,
                    "net_amount": amount,
                    "idempotency_key": idempotency_key or None,
                },
                lines_data=lines_data,
            )
            v.status = Voucher.Status.APPROVED
            v.approved_by = user
            v.save(update_fields=["status", "approved_by"])
            v = PostingService.post_voucher(voucher=v, user=user)

            if mode == CustomerReceipt.ReceiptMode.ADVANCE:
                adv_record = AdvanceRecord.objects.filter(company=company, source_voucher=v, party=party).first()
                if adv_record and data.get("contract"):
                    CustomerAdvanceContractRule.objects.create(
                        company=company,
                        advance_record=adv_record,
                        contract=data["contract"],
                        recovery_method=data.get("recovery_method", CustomerAdvanceContractRule.RecoveryMethod.PCT_CERTIFIED),
                        recovery_rate_pct=_q2(data.get("recovery_rate_pct") or data["contract"].advance_recovery_rate or "10.00"),
                        agreement_ref=data.get("agreement_ref", ""),
                        bank_guarantee_ref=data.get("bank_guarantee_ref", ""),
                    )

            if mode == CustomerReceipt.ReceiptMode.RETENTION_RELEASE:
                ret_sched = RetentionSchedule.objects.select_for_update().get(pk=data["retention_id"])
                ret_sched.released_amount += amount
                ret_sched.status = RetentionSchedule.Status.RELEASED if ret_sched.remaining_retention == 0 else RetentionSchedule.Status.PARTIAL
                ret_sched.save(update_fields=["released_amount", "status"])
                RetentionReleaseLog.objects.create(
                    retention=ret_sched,
                    release_voucher=v,
                    released_amount=amount,
                    release_date=rec_date,
                    remarks=narration,
                    released_by=user,
                )

        oi = OpenItem.objects.filter(voucher=v, party=party, hub_side=OpenItem.HubSide.RECEIVABLE).first()
        cr = CustomerReceipt.objects.create(
            company=company,
            branch=data.get("branch"),
            party=party,
            project=project,
            receipt_no=rec_no,
            receipt_date=rec_date,
            receipt_mode=mode,
            deposit_account=deposit_acc,
            bank_account=bank_account,
            cheque_leaf=cheque_leaf,
            cheque_number=data.get("cheque_number", ""),
            cheque_date=data.get("cheque_date"),
            drawee_bank=data.get("drawer_bank", ""),
            tds_certificate_no=data.get("tds_certificate_no", ""),
            tds_tax_period=data.get("tds_tax_period", ""),
            currency_code=currency,
            exchange_rate=ex_rate,
            amount=amount,
            bank_charges_amount=bank_charges,
            reference_no=ref_no,
            narration=narration[:255],
            voucher=v,
            open_item=oi,
            advance_record=adv_record,
            status=(
                CustomerReceipt.Status.FULLY_ALLOCATED
                if mode in (CustomerReceipt.ReceiptMode.ADVANCE, CustomerReceipt.ReceiptMode.RETENTION_RELEASE)
                else CustomerReceipt.Status.POSTED
            ),
            created_by=user,
        )

        if allocations:
            if mode in (CustomerReceipt.ReceiptMode.ADVANCE, CustomerReceipt.ReceiptMode.RETENTION_RELEASE):
                raise ValidationError(f"{mode} receipts cannot be allocated directly as normal invoice cash receipts.")
            ARReceiptAllocationService.allocate_receipt(
                company=company,
                user=user,
                receipt=cr,
                allocations=allocations,
            )
            cr.refresh_from_db()

        log_ar_audit(company, "CustomerReceipt", cr.id, "CUSTOMER_RECEIPT_POSTED", user, {"receipt_no": cr.receipt_no, "mode": mode, "amount": str(amount)})
        return cr

    @staticmethod
    def get_allocatable_documents(*, company, party: Party) -> dict:
        open_bills = list(
            OpenItem.objects.select_related("voucher", "project")
            .filter(company=company, party=party, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False)
            .exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.WRITTEN_OFF, OpenItem.Status.REVERSED])
            .order_by("due_date", "document_date")
        )
        unallocated_credits = list(
            OpenItem.objects.select_related("voucher", "project")
            .filter(company=company, party=party, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=True)
            .exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.REVERSED])
            .order_by("document_date")
        )
        advances = list(
            AdvanceRecord.objects.filter(company=company, party=party, advance_type=AdvanceRecord.AdvanceType.CUSTOMER_ADVANCE)
            .exclude(status__in=[AdvanceRecord.Status.SETTLED, AdvanceRecord.Status.CANCELLED])
            .order_by("issue_date")
        )

        def _fmt_oi(o: OpenItem):
            return {
                "open_item_id": str(o.id),
                "voucher_id": str(o.voucher_id),
                "voucher_no": o.voucher.voucher_no,
                "doc_kind": o.doc_kind,
                "document_no": o.document_no,
                "document_date": o.document_date.isoformat(),
                "bs_date": o.bs_date,
                "due_date": o.due_date.isoformat(),
                "project_name": o.project.name if o.project else None,
                "original_amount": str(o.original_amount),
                "allocated_amount": str(o.allocated_amount),
                "remaining_amount": str(o.remaining_amount),
                "status": o.status,
            }

        return {
            "open_bills": [_fmt_oi(x) for x in open_bills],
            "unallocated_receipts": [_fmt_oi(x) for x in unallocated_credits],
            "customer_advances": [
                {
                    "id": str(a.id),
                    "advance_no": a.advance_no,
                    "issue_date": a.issue_date.isoformat(),
                    "original_amount": str(a.original_amount),
                    "adjusted_amount": str(a.adjusted_amount),
                    "remaining_amount": str(a.remaining_amount),
                    "status": a.status,
                }
                for a in advances
            ],
        }

    @staticmethod
    @transaction.atomic
    def allocate_receipt(*, company, user, receipt: CustomerReceipt | None = None, settlement_voucher: Voucher | None = None, party: Party | None = None, allocations: list[dict]) -> dict:
        if receipt:
            if receipt.receipt_mode in (CustomerReceipt.ReceiptMode.ADVANCE, CustomerReceipt.ReceiptMode.RETENTION_RELEASE):
                raise ValidationError(f"{receipt.receipt_mode} receipts cannot be allocated against standard receivables.")
            if receipt.status == CustomerReceipt.Status.BOUNCED:
                raise ValidationError("Cannot allocate a bounced cheque receipt.")
            settlement_voucher = receipt.voucher
            party = receipt.party
        if not settlement_voucher or not party:
            raise ValidationError("Settlement receipt voucher and customer party are required.")

        result = InvoiceAllocationService.allocate_batch(
            company=company,
            user=user,
            party=party,
            settlement_voucher=settlement_voucher,
            allocations=allocations,
            hub_side=OpenItem.HubSide.RECEIVABLE,
        )

        # Sync wrapper statuses on CustomerReceipt, SalesInvoice, and RABill
        sett_oi = OpenItem.objects.filter(voucher=settlement_voucher, party=party, is_unallocated_credit=True).first()
        if receipt and sett_oi:
            receipt.status = (
                CustomerReceipt.Status.FULLY_ALLOCATED
                if sett_oi.remaining_amount == 0
                else (CustomerReceipt.Status.PARTIALLY_ALLOCATED if sett_oi.allocated_amount > 0 else CustomerReceipt.Status.POSTED)
            )
            receipt.save(update_fields=["status"])

        for row in allocations:
            oi = OpenItem.objects.filter(pk=row["open_item_id"]).first()
            if oi:
                if hasattr(oi, "ar_sales_invoice") and oi.ar_sales_invoice:
                    si = oi.ar_sales_invoice
                    si.status = SalesInvoice.Status.SETTLED if oi.remaining_amount == 0 else SalesInvoice.Status.PARTIAL
                    si.save(update_fields=["status", "updated_at"])
                if hasattr(oi, "ra_bill") and oi.ra_bill:
                    rb = oi.ra_bill
                    rb.status = RABill.WorkflowStatus.SETTLED if oi.remaining_amount == 0 else RABill.WorkflowStatus.PARTIALLY_RECEIVED
                    rb.save(update_fields=["status", "updated_at"])

        return result

    @staticmethod
    @transaction.atomic
    def reverse_allocation(*, company, user, allocation_id, reason: str) -> dict:
        if not (reason or "").strip():
            raise ValidationError("Reversal reason is mandatory for audit integrity.")
        ba = BillAllocation.objects.select_for_update().select_related("party", "settlement_voucher", "against_voucher").filter(
            pk=allocation_id, company=company
        ).first()
        if not ba:
            raise ValidationError("Allocation record not found.")

        inv_oi = OpenItem.objects.select_for_update().filter(
            voucher=ba.against_voucher, party=ba.party, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False
        ).first()
        rec_oi = OpenItem.objects.select_for_update().filter(
            voucher=ba.settlement_voucher, party=ba.party, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=True
        ).first()

        rev_amt = ba.allocated_amount
        rev_log = ReceiptAllocationReversal.objects.create(
            company=company,
            party=ba.party,
            allocation_id_ref=ba.id,
            invoice_voucher=ba.against_voucher,
            receipt_voucher=ba.settlement_voucher,
            reversed_amount=rev_amt,
            reason=reason.strip(),
            reversed_by=user,
        )

        ba.delete()

        if inv_oi:
            inv_oi.allocated_amount = max(inv_oi.allocated_amount - rev_amt, Decimal("0.00"))
            inv_oi.recompute_status(save=True)
            if hasattr(inv_oi, "ar_sales_invoice") and inv_oi.ar_sales_invoice:
                si = inv_oi.ar_sales_invoice
                si.status = SalesInvoice.Status.POSTED if inv_oi.allocated_amount == 0 else SalesInvoice.Status.PARTIAL
                si.save(update_fields=["status", "updated_at"])
            if hasattr(inv_oi, "ra_bill") and inv_oi.ra_bill:
                rb = inv_oi.ra_bill
                rb.status = RABill.WorkflowStatus.POSTED if inv_oi.allocated_amount == 0 else RABill.WorkflowStatus.PARTIALLY_RECEIVED
                rb.save(update_fields=["status", "updated_at"])

        if rec_oi:
            rec_oi.allocated_amount = max(rec_oi.allocated_amount - rev_amt, Decimal("0.00"))
            rec_oi.recompute_status(save=True)
            if hasattr(rec_oi.voucher, "ar_customer_receipt") and rec_oi.voucher.ar_customer_receipt:
                cr = rec_oi.voucher.ar_customer_receipt
                cr.status = CustomerReceipt.Status.POSTED if rec_oi.allocated_amount == 0 else CustomerReceipt.Status.PARTIALLY_ALLOCATED
                cr.save(update_fields=["status"])

        log_ar_audit(
            company,
            "BillAllocation",
            rev_log.allocation_id_ref,
            "ALLOCATION_REVERSED",
            user,
            {"reversed_amount": str(rev_amt), "reason": rev_log.reason, "reversal_id": str(rev_log.id)},
        )
        return {
            "reversal_id": str(rev_log.id),
            "reversed_amount": str(rev_amt),
            "invoice_remaining": str(inv_oi.remaining_amount) if inv_oi else None,
            "receipt_unallocated_remaining": str(rec_oi.remaining_amount) if rec_oi else None,
        }
