from datetime import date
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Sum

from apps.accounting.models import (
    Account,
    AdvanceAdjustment,
    AdvanceRecord,
    BillAllocation,
    Party,
    Voucher,
)
from apps.accounting.services import PostingService, VoucherService
from apps.audit.services import record_audit_event
from apps.party_hub.models import OpenItem


def _find_acc(company, role: str, prefix: str) -> Account | None:
    return (
        Account.objects.filter(company=company, control_role=role, is_group=False, is_active=True).first()
        or Account.objects.filter(company=company, code__startswith=prefix, is_group=False, is_active=True).first()
    )


class InvoiceAllocationService:
    """
    Concurrency-safe invoice settlement & allocation engine.
    Supports 1-to-Many, Many-to-1, Credit/Debit Notes, Explicit Advance Adjustments, and Bad Debt Write-Offs.
    Never silently auto-clears bills; validates exact remaining open balances on both sides.
    """

    @staticmethod
    @transaction.atomic
    def allocate_batch(
        *,
        company,
        user,
        party: Party,
        settlement_voucher: Voucher,
        allocations: list[dict],
        hub_side: str,
    ) -> dict:
        """
        allocations: [{"open_item_id": uuid, "allocated_amount": "100000.00", "discount_amount": "0.00", "tds_withheld": "0.00", "retention_released": "0.00"}]
        """
        if settlement_voucher.company_id != company.id or party.company_id != company.id:
            raise ValidationError("Cross-company allocation blocked.")
        if settlement_voucher.status != Voucher.Status.POSTED:
            raise ValidationError("Only POSTED receipt/payment/note vouchers can be allocated to invoices.")
        if not allocations:
            raise ValidationError("Provide at least one target invoice allocation.")

        sett_item = (
            OpenItem.objects.select_for_update()
            .filter(
                company=company,
                voucher=settlement_voucher,
                party=party,
                hub_side=hub_side,
                is_unallocated_credit=True,
            )
            .first()
        )
        if not sett_item:
            raise ValidationError(
                f"No unallocated {hub_side.lower()} credit balance found for voucher {settlement_voucher.voucher_no}."
            )

        total_requested = Decimal("0.00")
        created_rows = []
        ordered_allocs = sorted(allocations, key=lambda r: str(r.get("open_item_id") or ""))
        for row in ordered_allocs:
            target = (
                OpenItem.objects.select_for_update()
                .filter(
                    company=company,
                    id=row["open_item_id"],
                    party=party,
                    hub_side=hub_side,
                    is_unallocated_credit=False,
                )
                .first()
            )
            if not target:
                raise ValidationError(f"Target open item {row.get('open_item_id')} not found for party {party.name}.")
            if target.status == OpenItem.Status.DISPUTED:
                raise ValidationError(
                    f"Invoice {target.document_no} is DISPUTED. Resolve dispute before allocating."
                )
            if target.status == OpenItem.Status.REVERSED:
                raise ValidationError(f"Invoice {target.document_no} is reversed.")

            alloc_amt = Decimal(str(row.get("allocated_amount") or "0.00")).quantize(Decimal("0.01"))
            disc_amt = Decimal(str(row.get("discount_amount") or "0.00")).quantize(Decimal("0.01"))
            tds_amt = Decimal(str(row.get("tds_withheld") or "0.00")).quantize(Decimal("0.01"))
            ret_rel = Decimal(str(row.get("retention_released") or "0.00")).quantize(Decimal("0.01"))
            if alloc_amt <= 0:
                raise ValidationError(f"Allocated amount for {target.document_no} must exceed zero.")
            if BillAllocation.objects.filter(
                settlement_voucher=settlement_voucher, against_voucher=target.voucher
            ).exists():
                raise ValidationError(
                    f"Duplicate allocation blocked: {settlement_voucher.voucher_no} is already allocated to {target.document_no}."
                )
            if alloc_amt > target.remaining_amount:
                raise ValidationError(
                    f"Over-allocation blocked on {target.document_no}: requested {alloc_amt} exceeds remaining {target.remaining_amount}."
                )

            total_requested += alloc_amt
            if total_requested > sett_item.remaining_amount:
                raise ValidationError(
                    f"Total allocation ({total_requested}) exceeds unallocated balance ({sett_item.remaining_amount}) on {settlement_voucher.voucher_no}."
                )

            ba = BillAllocation.objects.create(
                company=company,
                party=party,
                settlement_voucher=settlement_voucher,
                against_voucher=target.voucher,
                allocated_amount=alloc_amt,
                discount_amount=disc_amt,
                tds_withheld=tds_amt,
                retention_released=ret_rel,
            )
            target.allocated_amount += alloc_amt
            target.recompute_status(save=True)
            created_rows.append(
                {
                    "allocation_id": str(ba.id),
                    "document_no": target.document_no,
                    "allocated_amount": str(alloc_amt),
                    "remaining_after": str(target.remaining_amount),
                    "status": target.status,
                }
            )

        sett_item.allocated_amount += total_requested
        sett_item.recompute_status(save=True)

        record_audit_event(
            company=company,
            actor=user,
            action="INVOICE_ALLOCATION_POSTED",
            entity_type="Voucher",
            entity_id=str(settlement_voucher.id),
            new_state={"party": party.name, "total_allocated": str(total_requested), "items": created_rows},
        )
        return {
            "settlement_voucher_no": settlement_voucher.voucher_no,
            "party_id": str(party.id),
            "total_allocated": str(total_requested),
            "unallocated_remaining": str(sett_item.remaining_amount),
            "allocations": created_rows,
        }

    @staticmethod
    @transaction.atomic
    def adjust_party_advance(
        *,
        company,
        user,
        advance: AdvanceRecord,
        open_item: OpenItem,
        amount: Decimal,
        adjustment_date: date,
        remarks: str = "",
    ) -> dict:
        """
        Explicitly offset a Customer Advance or Supplier/Mobilization Advance against a specific OpenItem
        via a balanced double-entry ADV_ADJUSTMENT Journal Voucher + AdvanceAdjustment + BillAllocation.
        """
        adv = AdvanceRecord.objects.select_for_update().get(pk=advance.pk, company=company)
        oi = OpenItem.objects.select_for_update().get(pk=open_item.pk, company=company)
        amount = Decimal(str(amount)).quantize(Decimal("0.01"))
        if adv.party_id != oi.party_id:
            raise ValidationError("Advance and target invoice belong to different parties.")
        if amount <= 0 or amount > adv.remaining_amount:
            raise ValidationError(f"Adjustment {amount} exceeds remaining advance {adv.remaining_amount}.")
        if amount > oi.remaining_amount:
            raise ValidationError(f"Adjustment {amount} exceeds invoice open balance {oi.remaining_amount}.")

        if oi.hub_side == OpenItem.HubSide.RECEIVABLE:
            # Customer Advance Liability (Dr) -> Sundry Debtors Control (Cr)
            lines_data = [
                {
                    "account": adv.control_account,
                    "party": adv.party,
                    "debit": amount,
                    "credit": Decimal("0.00"),
                    "project": oi.project,
                    "advance_record": adv,
                    "description": f"Adjust customer advance {adv.advance_no} against {oi.document_no}",
                },
                {
                    "account": oi.control_account,
                    "party": adv.party,
                    "debit": Decimal("0.00"),
                    "credit": amount,
                    "project": oi.project,
                    "description": f"Receivable settled via advance {adv.advance_no}",
                },
            ]
        else:
            # Sundry Creditors Control (Dr) -> Supplier Advance Asset (Cr)
            lines_data = [
                {
                    "account": oi.control_account,
                    "party": adv.party,
                    "debit": amount,
                    "credit": Decimal("0.00"),
                    "project": oi.project,
                    "description": f"Settle supplier bill {oi.document_no} from advance {adv.advance_no}",
                },
                {
                    "account": adv.control_account,
                    "party": adv.party,
                    "debit": Decimal("0.00"),
                    "credit": amount,
                    "project": oi.project,
                    "advance_record": adv,
                    "description": f"Adjust supplier advance {adv.advance_no}",
                },
            ]

        v = VoucherService.create_draft(
            company=company,
            user=user,
            data={
                "voucher_type": Voucher.VoucherType.ADVANCE_RECOVERY,
                "voucher_date": adjustment_date,
                "project": oi.project,
                "party": adv.party,
                "reference_no": oi.document_no,
                "narration": remarks or f"Advance adjustment {adv.advance_no} -> {oi.document_no}",
                "gross_amount": amount,
                "net_amount": amount,
            },
            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)

        # Settlement Voucher creates an unallocated OpenItem on posting; allocate it immediately to target OpenItem
        res = InvoiceAllocationService.allocate_batch(
            company=company,
            user=user,
            party=adv.party,
            settlement_voucher=v,
            allocations=[{"open_item_id": str(oi.id), "allocated_amount": str(amount)}],
            hub_side=oi.hub_side,
        )
        return {
            "voucher_id": str(v.id),
            "voucher_no": v.voucher_no,
            "advance_remaining": str(AdvanceRecord.objects.get(pk=adv.pk).remaining_amount),
            "allocation": res,
        }

    @staticmethod
    @transaction.atomic
    def write_off_bad_debt(
        *,
        company,
        user,
        open_item: OpenItem,
        writeoff_date: date,
        amount: Decimal,
        reason: str,
    ) -> dict:
        """Write off uncollectible receivable balance via balanced Dr Bad Debt Loss / Cr Sundry Debtors."""
        oi = OpenItem.objects.select_for_update().get(pk=open_item.pk, company=company)
        if oi.hub_side != OpenItem.HubSide.RECEIVABLE or oi.is_unallocated_credit:
            raise ValidationError("Bad debt write-off only applies to Customer Receivable open invoices.")
        amount = Decimal(str(amount)).quantize(Decimal("0.01"))
        if amount <= 0 or amount > oi.remaining_amount:
            raise ValidationError(f"Write-off amount {amount} exceeds remaining receivable {oi.remaining_amount}.")

        loss_acc = _find_acc(company, Account.ControlRole.BAD_DEBT_ALLOWANCE, "59") or _find_acc(
            company, Account.ControlRole.LOSS_WRITE_OFF, "59"
        )
        if not loss_acc:
            loss_acc = Account.objects.filter(
                company=company, account_type=Account.AccountType.EXPENSE, is_group=False, is_active=True
            ).first()
        if not loss_acc:
            raise ValidationError("No Loss / Write-off expense account configured in COA.")

        v = VoucherService.create_draft(
            company=company,
            user=user,
            data={
                "voucher_type": Voucher.VoucherType.JOURNAL,
                "voucher_date": writeoff_date,
                "project": oi.project,
                "party": oi.party,
                "reference_no": oi.document_no,
                "narration": f"Bad debt write-off ({oi.document_no}): {reason}",
                "gross_amount": amount,
                "net_amount": amount,
            },
            lines_data=[
                {
                    "account": loss_acc,
                    "debit": amount,
                    "credit": Decimal("0.00"),
                    "project": oi.project,
                    "description": f"Bad debt expense — {oi.party.name} ({oi.document_no})",
                },
                {
                    "account": oi.control_account,
                    "party": oi.party,
                    "debit": Decimal("0.00"),
                    "credit": amount,
                    "project": oi.project,
                    "description": f"Write-off uncollectible balance on {oi.document_no}",
                },
            ],
        )
        v.status = Voucher.Status.APPROVED
        v.approved_by = user
        v.save(update_fields=["status", "approved_by"])
        v = PostingService.post_voucher(voucher=v, user=user)

        # Clear unallocated credit generated by Cr Debtors control line
        sett_oi = OpenItem.objects.filter(
            company=company, voucher=v, party=oi.party, is_unallocated_credit=True
        ).first()
        if sett_oi:
            sett_oi.allocated_amount = sett_oi.original_amount
            sett_oi.status = OpenItem.Status.SETTLED
            sett_oi.save(update_fields=["allocated_amount", "status"])

        BillAllocation.objects.create(
            company=company,
            party=oi.party,
            settlement_voucher=v,
            against_voucher=oi.voucher,
            allocated_amount=amount,
        )
        oi.written_off_amount += amount
        oi.recompute_status(save=True)
        record_audit_event(
            company=company,
            actor=user,
            action="BAD_DEBT_WRITEOFF",
            entity_type="OpenItem",
            entity_id=str(oi.id),
            new_state={"amount": str(amount), "voucher_no": v.voucher_no, "reason": reason},
        )
        return {"voucher_no": v.voucher_no, "remaining_balance": str(oi.remaining_amount), "status": oi.status}

