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

from apps.accounting.models import Account, Voucher
from apps.accounting.services import PostingService, VoucherService
from apps.audit.services import record_audit_event
from apps.party_hub.models import RetentionReleaseLog, RetentionSchedule


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 RetentionService:
    """Dedicated Contract Retention Receivable & Retention Payable tracking & release workflow."""

    @staticmethod
    def list_retentions(*, company, direction: str, party_id: str | None = None, project_id: str | None = None) -> list[dict]:
        qs = RetentionSchedule.objects.select_related("party", "source_voucher", "project").filter(
            company=company, direction=direction
        )
        if party_id:
            qs = qs.filter(party_id=party_id)
        if project_id:
            qs = qs.filter(project_id=project_id)

        rows = []
        for r in qs:
            rows.append(
                {
                    "id": str(r.id),
                    "party_id": str(r.party_id),
                    "party_name": r.party.name,
                    "party_code": r.party.code,
                    "direction": r.direction,
                    "voucher_id": str(r.source_voucher_id),
                    "voucher_no": r.source_voucher.voucher_no,
                    "project_name": r.project.name if r.project else "",
                    "contract_ref": r.contract_ref,
                    "certificate_no": r.certificate_no,
                    "retention_pct": str(r.retention_pct),
                    "retention_amount": str(r.retention_amount),
                    "released_amount": str(r.released_amount),
                    "remaining_retention": str(r.remaining_retention),
                    "hold_date": r.hold_date.isoformat(),
                    "bs_hold_date": r.bs_hold_date,
                    "release_milestone": r.release_milestone,
                    "defect_liability_end_date": r.defect_liability_end_date.isoformat() if r.defect_liability_end_date else "",
                    "release_due_date": r.release_due_date.isoformat() if r.release_due_date else "",
                    "is_disputed": r.is_disputed,
                    "status": r.status,
                }
            )
        return rows

    @staticmethod
    @transaction.atomic
    def release_retention(
        *,
        company,
        user,
        retention: RetentionSchedule,
        release_amount: Decimal,
        release_date: date,
        settlement_mode: str = "TRANSFER_TO_CONTROL",
        bank_account: Account | None = None,
        remarks: str = "",
    ) -> dict:
        """
        Release held retention cleanly:
        - RECEIVABLE: Cr Retention Receivable (116) / Dr Bank (if direct receipt) or Sundry Debtors (due for collection)
        - PAYABLE:    Dr Retention Payable (206)    / Cr Bank (if direct payout)  or Sundry Creditors (due for payment)
        """
        r = RetentionSchedule.objects.select_for_update().get(pk=retention.pk, company=company)
        release_amount = Decimal(str(release_amount)).quantize(Decimal("0.01"))
        if release_amount <= 0 or release_amount > r.remaining_retention:
            raise ValidationError(f"Release amount {release_amount} exceeds remaining retention {r.remaining_retention}.")
        if r.is_disputed:
            raise ValidationError("Retention is currently DISPUTED. Resolve dispute before releasing.")

        if r.direction == RetentionSchedule.Direction.RECEIVABLE:
            ret_acc = _find_acc(company, Account.ControlRole.RETENTION_RECEIVABLE, "116")
            counter_acc = (
                bank_account
                if settlement_mode == "DIRECT_BANK" and bank_account
                else (r.party.control_account or _find_acc(company, Account.ControlRole.SUNDRY_DEBTORS, "110"))
            )
            if not ret_acc or not counter_acc:
                raise ValidationError("Retention Receivable or Debtors/Bank control account missing.")
            v_type = Voucher.VoucherType.RECEIPT if settlement_mode == "DIRECT_BANK" else Voucher.VoucherType.RETENTION
            lines_data = [
                {
                    "account": counter_acc,
                    "party": r.party if counter_acc.control_role == Account.ControlRole.SUNDRY_DEBTORS else None,
                    "debit": release_amount,
                    "credit": Decimal("0.00"),
                    "project": r.project,
                    "description": f"Retention release receivable ({r.source_voucher.voucher_no})",
                },
                {
                    "account": ret_acc,
                    "party": r.party,
                    "debit": Decimal("0.00"),
                    "credit": release_amount,
                    "project": r.project,
                    "description": f"Release client retention — {r.party.name}",
                },
            ]
        else:
            ret_acc = _find_acc(company, Account.ControlRole.RETENTION_PAYABLE, "206")
            counter_acc = (
                bank_account
                if settlement_mode == "DIRECT_BANK" and bank_account
                else (r.party.control_account or _find_acc(company, Account.ControlRole.SUBCONTRACTOR_PAYABLE, "202") or _find_acc(company, Account.ControlRole.SUNDRY_CREDITORS, "201"))
            )
            if not ret_acc or not counter_acc:
                raise ValidationError("Retention Payable or Creditors/Bank control account missing.")
            v_type = Voucher.VoucherType.PAYMENT if settlement_mode == "DIRECT_BANK" else Voucher.VoucherType.RETENTION
            lines_data = [
                {
                    "account": ret_acc,
                    "party": r.party,
                    "debit": release_amount,
                    "credit": Decimal("0.00"),
                    "project": r.project,
                    "description": f"Release subcontractor/supplier retention — {r.party.name}",
                },
                {
                    "account": counter_acc,
                    "party": r.party if counter_acc.control_role in (Account.ControlRole.SUNDRY_CREDITORS, Account.ControlRole.SUBCONTRACTOR_PAYABLE) else None,
                    "debit": Decimal("0.00"),
                    "credit": release_amount,
                    "project": r.project,
                    "description": f"Retention release payable ({r.source_voucher.voucher_no})",
                },
            ]

        v = VoucherService.create_draft(
            company=company,
            user=user,
            data={
                "voucher_type": v_type,
                "voucher_date": release_date,
                "project": r.project,
                "party": r.party,
                "reference_no": r.source_voucher.voucher_no,
                "narration": remarks or f"Retention release for {r.source_voucher.voucher_no}",
                "gross_amount": release_amount,
                "net_amount": release_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)

        RetentionReleaseLog.objects.create(
            retention=r,
            release_voucher=v,
            released_amount=release_amount,
            release_date=release_date,
            remarks=remarks,
            released_by=user,
        )
        r.released_amount += release_amount
        r.status = RetentionSchedule.Status.RELEASED if r.remaining_retention == 0 else RetentionSchedule.Status.PARTIAL
        r.save(update_fields=["released_amount", "status"])

        record_audit_event(
            company=company,
            actor=user,
            action="RETENTION_RELEASED",
            entity_type="RetentionSchedule",
            entity_id=str(r.id),
            new_state={"released_amount": str(release_amount), "voucher_no": v.voucher_no, "remaining": str(r.remaining_retention)},
        )
        return {
            "retention_id": str(r.id),
            "voucher_no": v.voucher_no,
            "released_amount": str(release_amount),
            "remaining_retention": str(r.remaining_retention),
            "status": r.status,
        }
