from datetime import date, timedelta
from decimal import Decimal, ROUND_HALF_UP
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.accounting.models import Account, AdvanceAdjustment, AdvanceRecord, Party, Voucher
from apps.accounting.services import PostingService, VoucherService
from apps.audit.services import record_audit_event
from apps.construction_ops.models import OperationalDocument
from apps.localization.bs_calendar import ad_to_bs
from apps.party_hub.models import (
    ARAuditEvent,
    ARControlPolicy,
    CustomerAddress,
    CustomerAdvanceContractRule,
    CustomerContact,
    CustomerCreditHoldLog,
    CustomerCreditOverride,
    CustomerDocument,
    CustomerProfile,
    MeasurementReference,
    OpenItem,
    PartyControlMap,
    RABill,
    RABillCertification,
    RABillDeduction,
    RABillLine,
    RetentionSchedule,
    SalesInvoice,
    SalesInvoiceLine,
)
from apps.projects.models import (
    Project,
    ProjectBoqHeader,
    ProjectBoqLine,
    ProjectContract,
    ProjectVariationOrder,
)


Q2 = Decimal("0.01")
Q3 = Decimal("0.001")


def _q2(val) -> Decimal:
    return Decimal(str(val or "0.00")).quantize(Q2, rounding=ROUND_HALF_UP)


def _q3(val) -> Decimal:
    return Decimal(str(val or "0.000")).quantize(Q3, rounding=ROUND_HALF_UP)


def get_ar_policy(company) -> ARControlPolicy:
    policy, _ = ARControlPolicy.objects.get_or_create(
        company=company,
        defaults={
            "aging_buckets_json": [0, 30, 60, 90, 180, 365],
        },
    )
    return policy


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()
    )


def resolve_ar_accounts(company, party: Party | None = None, custom_rev: Account | None = None) -> dict:
    policy = get_ar_policy(company)
    cmap = None
    if party and getattr(party, "customer_profile", None) and party.customer_profile.group_id:
        cmap = PartyControlMap.objects.filter(
            company=company, hub_side=PartyControlMap.HubSide.RECEIVABLE, party_group=party.customer_profile.group
        ).first()
    if not cmap:
        cmap = PartyControlMap.objects.filter(
            company=company, hub_side=PartyControlMap.HubSide.RECEIVABLE, party_type=Party.PartyType.CUSTOMER, is_default=True
        ).first()

    debtors_acc = (
        (party.control_account if party and party.control_account_id else None)
        or (cmap.control_account if cmap else None)
        or policy.default_control_account
        or _find_acc(company, Account.ControlRole.SUNDRY_DEBTORS, "110")
    )
    revenue_acc = (
        custom_rev
        or policy.default_revenue_account
        or Account.objects.filter(company=company, account_type=Account.AccountType.INCOME, is_group=False, is_active=True)
        .order_by("code")
        .first()
    )
    vat_acc = policy.default_vat_output_account or _find_acc(company, Account.ControlRole.OUTPUT_VAT, "204")
    retention_acc = (
        (cmap.retention_account if cmap and cmap.retention_account_id else None)
        or policy.default_retention_account
        or _find_acc(company, Account.ControlRole.RETENTION_RECEIVABLE, "116")
    )
    advance_acc = (
        (cmap.advance_account if cmap and cmap.advance_account_id else None)
        or policy.default_advance_account
        or _find_acc(company, Account.ControlRole.CUSTOMER_ADVANCE, "207")
    )
    tds_acc = policy.default_tds_receivable_account or _find_acc(company, Account.ControlRole.TDS_RECEIVABLE, "115") or debtors_acc
    ded_acc = _find_acc(company, Account.ControlRole.DIRECT_EXPENSES, "50") or revenue_acc

    return {
        "debtors": debtors_acc,
        "revenue": revenue_acc,
        "vat": vat_acc,
        "retention": retention_acc,
        "advance": advance_acc,
        "tds": tds_acc,
        "deduction_expense": ded_acc,
    }


def log_ar_audit(company, entity_type: str, entity_id, action: str, user, details: dict | None = None):
    ARAuditEvent.objects.create(
        company=company,
        entity_type=entity_type,
        entity_id=str(entity_id),
        action=action,
        actor=user,
        details=details or {},
    )
    record_audit_event(
        company=company,
        actor=user,
        action=action,
        entity_type=entity_type,
        entity_id=str(entity_id),
        new_state=details or {},
    )


class CustomerGovernanceService:
    """Customer Master registration, duplicate detection, credit limit check & overrides."""

    @staticmethod
    def check_duplicates(*, company, name: str = "", pan_vat_no: str = "", phone: str = "", exclude_id=None) -> list[dict]:
        matches = []
        qs = CustomerProfile.objects.select_related("party").filter(company=company)
        if exclude_id:
            qs = qs.exclude(pk=exclude_id)
        if pan_vat_no:
            for c in qs.filter(pan_vat_no=pan_vat_no.strip()):
                matches.append({"id": str(c.id), "code": c.party.code, "name": c.party.name, "reason": f"Exact PAN/VAT match ({pan_vat_no})"})
        if phone:
            for c in qs.filter(party__phone=phone.strip()).exclude(party__phone=""):
                matches.append({"id": str(c.id), "code": c.party.code, "name": c.party.name, "reason": f"Phone match ({phone})"})
        if name and len(name.strip()) >= 3:
            norm = name.strip().lower()
            for c in qs.filter(party__name__icontains=name.strip())[:10]:
                if c.party.name.strip().lower() == norm or norm in c.party.name.strip().lower():
                    matches.append({"id": str(c.id), "code": c.party.code, "name": c.party.name, "reason": "Similar legal / display name"})
        # deduplicate by id
        seen = {}
        for m in matches:
            seen.setdefault(m["id"], m)
        return list(seen.values())

    @staticmethod
    def compute_credit_exposure(company, party: Party) -> dict:
        policy = get_ar_policy(company)
        open_items = OpenItem.objects.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])
        posted_ar = sum((oi.remaining_amount for oi in open_items), Decimal("0.00"))
        overdue_ar = sum((oi.remaining_amount for oi in open_items if oi.due_date < timezone.localdate()), Decimal("0.00"))
        unbilled_ra = Decimal("0.00")
        if policy.include_unbilled_in_credit_exposure:
            unbilled_qs = RABill.objects.filter(
                company=company,
                party=party,
                voucher__isnull=True,
            ).exclude(status__in=[RABill.WorkflowStatus.CANCELLED, RABill.WorkflowStatus.REJECTED, RABill.WorkflowStatus.SUPERSEDED])
            unbilled_ra = sum((b.net_receivable_amount for b in unbilled_qs), Decimal("0.00"))

        prof = getattr(party, "customer_profile", None)
        today = timezone.localdate()
        override = None
        if prof:
            override = (
                CustomerCreditOverride.objects.filter(company=company, customer=prof, is_active=True)
                .filter(Q(valid_until__isnull=True) | Q(valid_until__gte=today))
                .order_by("-approved_at")
                .first()
            )
        base_limit = party.credit_limit or Decimal("0.00")
        effective_limit = override.override_limit if override else base_limit
        exposure = posted_ar + unbilled_ra
        headroom = (effective_limit - exposure) if effective_limit > 0 else None
        utilization = (
            (exposure * Decimal("100") / effective_limit).quantize(Q2)
            if effective_limit > 0
            else Decimal("0.00")
        )
        return {
            "posted_ar": posted_ar,
            "overdue_ar": overdue_ar,
            "unbilled_exposure": unbilled_ra,
            "total_exposure": exposure,
            "base_credit_limit": base_limit,
            "effective_credit_limit": effective_limit,
            "override_active": bool(override),
            "utilization_pct": utilization,
            "headroom": headroom,
        }

    @staticmethod
    def enforce_credit_control(company, party: Party, new_amount: Decimal):
        prof = getattr(party, "customer_profile", None)
        if prof and (prof.is_blacklisted or prof.approval_status == CustomerProfile.ApprovalStatus.BLACKLISTED):
            raise ValidationError(f"Customer '{party.name}' is Blacklisted; billing blocked.")
        if prof and prof.credit_hold:
            raise ValidationError(f"Customer '{party.name}' is on Credit Hold; billing requires authorized override.")
        policy = get_ar_policy(company)
        if not policy.block_over_credit_limit:
            return
        if prof and prof.customer_category == CustomerProfile.Category.GOVERNMENT and prof.govt_contract_exempt_credit:
            return
        exp = CustomerGovernanceService.compute_credit_exposure(company, party)
        eff_limit = exp["effective_credit_limit"]
        if eff_limit > 0 and (exp["total_exposure"] + new_amount) > eff_limit:
            raise ValidationError(
                f"Credit limit exceeded for '{party.name}': exposure {exp['total_exposure'] + new_amount} > effective limit {eff_limit}."
            )

    @staticmethod
    @transaction.atomic
    def register_or_update_customer(*, company, user, data: dict, instance: CustomerProfile | None = None) -> CustomerProfile:
        policy = get_ar_policy(company)
        ctrl = resolve_ar_accounts(company)["debtors"]
        name = (data.get("name") or "").strip()
        code = (data.get("code") or "").strip()
        if not instance and (not name or not code):
            raise ValidationError("Customer code and name are required.")

        pan = (data.get("pan_vat_no") or "").strip()
        override_reason = (data.get("duplicate_override_reason") or "").strip()
        if not instance:
            dups = CustomerGovernanceService.check_duplicates(company=company, name=name, pan_vat_no=pan, phone=data.get("phone", ""))
            exact_pan = [d for d in dups if "PAN/VAT" in d["reason"]]
            if exact_pan and not override_reason:
                raise ValidationError(f"Duplicate customer detected: {exact_pan[0]['reason']} ({exact_pan[0]['code']}). Provide duplicate override reason.")
            party, _ = Party.objects.get_or_create(
                company=company,
                code=code,
                defaults={
                    "party_type": Party.PartyType.CUSTOMER,
                    "name": name,
                    "pan_vat_no": pan,
                    "address": data.get("address", ""),
                    "phone": data.get("phone", ""),
                    "email": data.get("email", ""),
                    "credit_limit": _q2(data.get("credit_limit") or "0.00"),
                    "payment_terms_days": int(data.get("credit_days") or policy.default_credit_days),
                    "control_account": ctrl,
                    "project_id": data.get("project_id") or None,
                },
            )
            prof = CustomerProfile(
                company=company,
                party=party,
                approved_by=user if data.get("approval_status", "APPROVED") == "APPROVED" else None,
            )
        else:
            prof = instance
            party = prof.party
            if name:
                party.name = name
            if pan:
                party.pan_vat_no = pan
            for pfield in ["address", "phone", "email"]:
                if pfield in data:
                    setattr(party, pfield, data[pfield] or "")
            if "credit_limit" in data:
                party.credit_limit = _q2(data["credit_limit"])
            if "credit_days" in data:
                party.payment_terms_days = int(data["credit_days"] or policy.default_credit_days)
            party.save()

        profile_fields = [
            "legal_name", "customer_category", "registration_no", "tax_classification", "pan_vat_no",
            "tds_applicable", "default_currency", "contract_number", "agreement_date", "blacklist_reason",
            "risk_classification", "required_approval_level", "contract_required", "supporting_docs_required",
            "govt_contract_exempt_credit", "website", "notes", "duplicate_override_reason", "bank_name",
            "bank_account_no", "approval_status", "is_active", "credit_hold", "is_blacklisted",
        ]
        for f in profile_fields:
            if f in data:
                setattr(prof, f, data[f])
        for dec_f in ["default_tds_rate", "default_retention_rate", "contract_value"]:
            if dec_f in data and data[dec_f] is not None:
                setattr(prof, dec_f, _q2(data[dec_f]))
        if "credit_days" in data and data["credit_days"] is not None:
            prof.credit_days = int(data["credit_days"])
        if "group_id" in data:
            prof.group_id = data["group_id"] or None
        if "parent_customer_id" in data:
            prof.parent_customer_id = data["parent_customer_id"] or None
        if "collection_officer_id" in data:
            prof.collection_officer_id = data["collection_officer_id"] or None

        prof.full_clean()
        prof.save()

        for c in data.get("contacts") or []:
            CustomerContact.objects.create(
                customer=prof,
                name=c["name"],
                designation=c.get("designation", ""),
                phone=c.get("phone", ""),
                email=c.get("email", ""),
                is_primary=bool(c.get("is_primary", False)),
            )
        for a in data.get("addresses") or []:
            CustomerAddress.objects.create(
                customer=prof,
                label=a.get("label", "Head Office / Billing"),
                address_line=a["address_line"],
                province=a.get("province", ""),
                district=a.get("district", ""),
                local_level=a.get("local_level", ""),
                ward=a.get("ward", ""),
                city=a.get("city", ""),
                country=a.get("country", "Nepal"),
                is_billing=bool(a.get("is_billing", True)),
                is_site=bool(a.get("is_site", False)),
            )
        for d in data.get("documents") or []:
            CustomerDocument.objects.create(
                customer=prof,
                doc_type=d["doc_type"],
                doc_number=d.get("doc_number", ""),
                file_ref=d.get("file_ref", ""),
                issue_date=d.get("issue_date") or None,
                expiry_date=d.get("expiry_date") or None,
            )

        log_ar_audit(company, "CustomerProfile", prof.id, "CUSTOMER_UPSERT", user, {"code": party.code, "name": party.name})
        return prof

    @staticmethod
    @transaction.atomic
    def grant_credit_override(*, company, user, customer: CustomerProfile, override_limit: Decimal, reason: str, valid_until=None) -> CustomerCreditOverride:
        if not reason.strip():
            raise ValidationError("Override reason is mandatory.")
        ov = CustomerCreditOverride.objects.create(
            company=company,
            customer=customer,
            override_limit=_q2(override_limit),
            reason=reason.strip(),
            valid_until=valid_until,
            approved_by=user,
        )
        CustomerCreditHoldLog.objects.create(
            company=company,
            customer=customer,
            action=CustomerCreditHoldLog.Action.OVERRIDE_GRANTED,
            previous_value=str(customer.party.credit_limit),
            new_value=str(ov.override_limit),
            reason=ov.reason,
            actor=user,
        )
        log_ar_audit(company, "CustomerProfile", customer.id, "CREDIT_OVERRIDE", user, {"override_limit": str(ov.override_limit), "reason": ov.reason})
        return ov

    @staticmethod
    @transaction.atomic
    def toggle_credit_hold(*, company, user, customer: CustomerProfile, hold: bool, reason: str) -> CustomerProfile:
        prev = customer.credit_hold
        customer.credit_hold = hold
        customer.save(update_fields=["credit_hold"])
        CustomerCreditHoldLog.objects.create(
            company=company,
            customer=customer,
            action=CustomerCreditHoldLog.Action.HOLD_PLACED if hold else CustomerCreditHoldLog.Action.HOLD_RELEASED,
            previous_value=str(prev),
            new_value=str(hold),
            reason=reason or ("Credit hold applied" if hold else "Credit hold released"),
            actor=user,
        )
        log_ar_audit(company, "CustomerProfile", customer.id, "CREDIT_HOLD_TOGGLE", user, {"hold": hold, "reason": reason})
        return customer


class SalesInvoiceService:
    """Multi-line Commercial Sales / Service / Milestone / Debit & Credit Note workflow & GL posting."""

    @staticmethod
    @transaction.atomic
    def create_draft_invoice(*, company, user, data: dict, lines_data: list[dict]) -> SalesInvoice:
        party: Party = data["party"]
        if party.company_id != company.id or party.party_type != Party.PartyType.CUSTOMER:
            raise ValidationError("Selected party must be an active Customer of this company.")
        if not lines_data:
            raise ValidationError("At least one invoice line is required.")

        inv_date: date = data["invoice_date"]
        due_date: date = data.get("due_date") or (inv_date + timedelta(days=int(party.payment_terms_days or 30)))
        inv_no = (data.get("invoice_no") or "").strip()
        if not inv_no:
            cnt = SalesInvoice.objects.filter(company=company).count() + 1
            inv_no = f"SINV-{inv_date.strftime('%Y%m')}-{cnt:04d}"

        inv = SalesInvoice.objects.create(
            company=company,
            branch=data.get("branch"),
            party=party,
            project=data.get("project"),
            contract=data.get("contract"),
            doc_type=data.get("doc_type") or SalesInvoice.DocType.TAX_INVOICE,
            invoice_no=inv_no,
            invoice_date=inv_date,
            due_date=due_date,
            currency_code=(data.get("currency_code") or "NPR").upper(),
            exchange_rate=Decimal(str(data.get("exchange_rate") or "1.000000")),
            tds_withholding_amount=_q2(data.get("tds_withholding_amount") or "0.00"),
            revenue_account=data.get("revenue_account"),
            reference_invoice=data.get("reference_invoice"),
            narration=data.get("narration", ""),
            created_by=user,
        )

        subtotal = Decimal("0.00")
        discount_total = Decimal("0.00")
        taxable_total = Decimal("0.00")
        vat_total = Decimal("0.00")

        for idx, row in enumerate(lines_data, start=1):
            qty = _q3(row.get("quantity") or "1")
            rate = _q2(row.get("unit_rate") or "0")
            disc_pct = _q2(row.get("discount_pct") or "0")
            tax_pct = _q2(row.get("tax_rate_pct") if row.get("tax_rate_pct") is not None else "13.00")
            raw_amt = (qty * rate).quantize(Q2, rounding=ROUND_HALF_UP)
            disc_amt = (raw_amt * disc_pct / Decimal("100")).quantize(Q2, rounding=ROUND_HALF_UP)
            taxable = raw_amt - disc_amt
            vat_amt = (taxable * tax_pct / Decimal("100")).quantize(Q2, rounding=ROUND_HALF_UP)
            line_total = taxable + vat_amt

            subtotal += raw_amt
            discount_total += disc_amt
            taxable_total += taxable
            vat_total += vat_amt

            SalesInvoiceLine.objects.create(
                invoice=inv,
                line_no=idx,
                item_code=row.get("item_code", ""),
                description=row["description"],
                unit=row.get("unit", "Unit"),
                quantity=qty,
                unit_rate=rate,
                discount_pct=disc_pct,
                tax_rate_pct=tax_pct,
                line_subtotal=taxable,
                vat_amount=vat_amt,
                line_total=line_total,
                revenue_account=row.get("revenue_account"),
                cost_center=row.get("cost_center"),
            )

        inv.subtotal_amount = subtotal
        inv.discount_amount = discount_total
        inv.taxable_amount = taxable_total
        inv.vat_amount = vat_total
        inv.total_amount = taxable_total + vat_total - inv.tds_withholding_amount
        inv.save(update_fields=["subtotal_amount", "discount_amount", "taxable_amount", "vat_amount", "total_amount"])
        log_ar_audit(company, "SalesInvoice", inv.id, "SALES_INVOICE_CREATED", user, {"invoice_no": inv.invoice_no, "total": str(inv.total_amount)})
        return inv

    @staticmethod
    @transaction.atomic
    def transition_and_post(*, invoice: SalesInvoice, action: str, user) -> SalesInvoice:
        invoice = SalesInvoice.objects.select_for_update().get(pk=invoice.pk)
        if action == "submit":
            if invoice.status != SalesInvoice.Status.DRAFT:
                raise ValidationError("Only DRAFT invoices can be submitted.")
            invoice.status = SalesInvoice.Status.SUBMITTED
            invoice.save(update_fields=["status", "updated_at"])
        elif action == "approve":
            if invoice.status not in (SalesInvoice.Status.DRAFT, SalesInvoice.Status.SUBMITTED):
                raise ValidationError("Invoice must be DRAFT or SUBMITTED before approval.")
            if invoice.created_by_id == user.id and not user.is_superuser and get_ar_policy(invoice.company).enforce_maker_checker_ra:
                raise ValidationError("Maker-checker control: creator cannot self-approve this invoice.")
            invoice.status = SalesInvoice.Status.APPROVED
            invoice.approved_by = user
            invoice.save(update_fields=["status", "approved_by", "updated_at"])
        elif action == "post":
            if invoice.voucher_id is not None:
                raise ValidationError("This invoice has already been posted to the General Ledger.")
            if invoice.status not in (SalesInvoice.Status.APPROVED,):
                raise ValidationError("Invoice must be APPROVED before posting to Accounts Receivable.")
            if invoice.doc_type != SalesInvoice.DocType.CREDIT_NOTE:
                CustomerGovernanceService.enforce_credit_control(invoice.company, invoice.party, invoice.total_amount)

            accs = resolve_ar_accounts(invoice.company, invoice.party, invoice.revenue_account)
            if not accs["debtors"] or not accs["revenue"]:
                raise ValidationError("Sundry Debtors control or Revenue account missing.")

            vtype = (
                Voucher.VoucherType.CREDIT_NOTE
                if invoice.doc_type == SalesInvoice.DocType.CREDIT_NOTE
                else (Voucher.VoucherType.DEBIT_NOTE if invoice.doc_type == SalesInvoice.DocType.DEBIT_NOTE else Voucher.VoucherType.SALES)
            )
            lines_data = []
            if vtype == Voucher.VoucherType.CREDIT_NOTE:
                lines_data.append({"account": accs["revenue"], "debit": invoice.taxable_amount, "credit": Decimal("0.00"), "project": invoice.project, "description": f"Credit Note {invoice.invoice_no}"})
                if invoice.vat_amount > 0 and accs["vat"]:
                    lines_data.append({"account": accs["vat"], "debit": invoice.vat_amount, "credit": Decimal("0.00"), "project": invoice.project, "description": "Output VAT Reversal"})
                lines_data.append({"account": accs["debtors"], "party": invoice.party, "debit": Decimal("0.00"), "credit": invoice.taxable_amount + invoice.vat_amount, "project": invoice.project, "description": f"Credit Note to {invoice.party.name}"})
            else:
                lines_data.append({"account": accs["debtors"], "party": invoice.party, "debit": invoice.total_amount, "credit": Decimal("0.00"), "project": invoice.project, "description": f"Invoice {invoice.invoice_no} — {invoice.party.name}"})
                if invoice.tds_withholding_amount > 0 and accs["tds"] and accs["tds"].id != accs["debtors"].id:
                    lines_data.append({"account": accs["tds"], "party": invoice.party, "debit": invoice.tds_withholding_amount, "credit": Decimal("0.00"), "project": invoice.project, "description": "Client TDS Withheld"})
                lines_data.append({"account": accs["revenue"], "debit": Decimal("0.00"), "credit": invoice.taxable_amount, "project": invoice.project, "description": invoice.narration or f"Sales {invoice.invoice_no}"})
                if invoice.vat_amount > 0 and accs["vat"]:
                    lines_data.append({"account": accs["vat"], "debit": Decimal("0.00"), "credit": invoice.vat_amount, "project": invoice.project, "description": "Output VAT 13%"})

            v = VoucherService.create_draft(
                company=invoice.company,
                user=invoice.created_by,
                data={
                    "voucher_type": vtype,
                    "voucher_date": invoice.invoice_date,
                    "due_date": invoice.due_date,
                    "project": invoice.project,
                    "party": invoice.party,
                    "branch": invoice.branch,
                    "currency": invoice.currency_code,
                    "exchange_rate": invoice.exchange_rate,
                    "reference_no": invoice.invoice_no,
                    "narration": invoice.narration or f"{invoice.doc_type} {invoice.invoice_no}",
                    "gross_amount": invoice.taxable_amount,
                    "tax_amount": invoice.vat_amount,
                    "tds_amount": invoice.tds_withholding_amount,
                    "net_amount": invoice.total_amount,
                },
                lines_data=lines_data,
            )
            v.status = Voucher.Status.APPROVED
            v.approved_by = invoice.approved_by or user
            v.save(update_fields=["status", "approved_by"])
            v = PostingService.post_voucher(voucher=v, user=user)

            oi = OpenItem.objects.filter(voucher=v, party=invoice.party, hub_side=OpenItem.HubSide.RECEIVABLE).first()
            invoice.voucher = v
            invoice.open_item = oi
            invoice.status = SalesInvoice.Status.POSTED
            invoice.posted_by = user
            invoice.posted_at = timezone.now()
            invoice.save(update_fields=["voucher", "open_item", "status", "posted_by", "posted_at", "updated_at"])
        else:
            raise ValidationError(f"Unsupported invoice transition '{action}'.")

        log_ar_audit(invoice.company, "SalesInvoice", invoice.id, f"SALES_INVOICE_{action.upper()}", user, {"status": invoice.status})
        return invoice


class RABillingService:
    """
    Construction Running Account (RA) Progress Billing Engine:
    BOQ & Measurement Book linkage -> Cumulative Qty & Excess Guard -> Multi-stage Maker-Checker Workflow
    -> Client Certification -> Single Centralized GL Posting + Retention & Advance Recovery Sync.
    """

    @staticmethod
    def get_contract_boq_billing_sheet(*, company, contract: ProjectContract) -> dict:
        if contract.company_id != company.id:
            raise ValidationError("Contract does not belong to active company.")
        project = contract.project
        boq_header = ProjectBoqHeader.objects.filter(project=project, is_active=True).order_by("-version").first()
        boq_lines = list(ProjectBoqLine.objects.filter(boq_header=boq_header).order_by("item_code")) if boq_header else []

        # Find latest certified or posted RA bill for this contract to derive previous cumulative qtys
        last_ra = (
            RABill.objects.filter(
                company=company,
                contract=contract,
                status__in=[
                    RABill.WorkflowStatus.CLIENT_CERTIFIED,
                    RABill.WorkflowStatus.PARTIALLY_CERTIFIED,
                    RABill.WorkflowStatus.POSTED,
                    RABill.WorkflowStatus.PARTIALLY_RECEIVED,
                    RABill.WorkflowStatus.SETTLED,
                ],
            )
            .order_by("-ra_sequence_no", "-bill_date")
            .first()
        )
        prev_qty_by_boq = {}
        if last_ra:
            for ln in last_ra.lines.all():
                if ln.boq_line_id:
                    prev_qty_by_boq[ln.boq_line_id] = ln.cumulative_qty

        approved_vos = list(
            ProjectVariationOrder.objects.filter(
                project=project, status=ProjectVariationOrder.Status.APPROVED
            ).order_by("variation_no")
        )
        next_seq = (RABill.objects.filter(company=company, contract=contract).count() + 1)

        items = []
        for bl in boq_lines:
            eff_contract_qty = bl.revised_qty if bl.revised_qty > 0 else bl.contract_qty
            eff_rate = bl.revised_rate if bl.revised_rate > 0 else bl.contract_rate
            prev_qty = prev_qty_by_boq.get(bl.id, bl.previous_certified_qty)
            rem_qty = max(eff_contract_qty - prev_qty, Decimal("0.000"))
            items.append({
                "boq_line_id": str(bl.id),
                "item_code": bl.item_code,
                "description": bl.description,
                "unit": bl.unit,
                "contract_qty": str(eff_contract_qty),
                "contract_rate": str(eff_rate),
                "previous_cumulative_qty": str(prev_qty),
                "remaining_qty": str(rem_qty),
                "measured_unbilled_qty": str(max(bl.current_measured_qty - prev_qty, Decimal("0.000"))),
            })

        return {
            "contract_id": str(contract.id),
            "contract_no": contract.contract_no,
            "project_id": str(project.id),
            "project_code": project.code,
            "project_name": project.name,
            "boq_header_id": str(boq_header.id) if boq_header else None,
            "previous_ra_bill_id": str(last_ra.id) if last_ra else None,
            "previous_ra_number": last_ra.ra_number if last_ra else None,
            "next_ra_sequence_no": next_seq,
            "default_retention_rate": str(contract.retention_rate),
            "default_advance_recovery_rate": str(contract.advance_recovery_rate),
            "approved_variation_orders": [{"id": str(vo.id), "vo_no": vo.variation_no, "title": vo.title, "approved_amount": str(vo.additional_value)} for vo in approved_vos],
            "items": items,
        }

    @staticmethod
    @transaction.atomic
    def create_or_update_ra_bill(*, company, user, data: dict, lines_data: list[dict], deductions_data: list[dict] | None = None, instance: RABill | None = None) -> RABill:
        contract: ProjectContract = data["contract"]
        project: Project = contract.project
        party: Party = data["party"]
        if contract.company_id != company.id or party.company_id != company.id:
            raise ValidationError("Contract or Customer belongs to another company.")
        if instance and instance.voucher_id is not None:
            raise ValidationError("Posted RA Bill is immutable and cannot be edited.")
        if instance and instance.status not in (RABill.WorkflowStatus.DRAFT, RABill.WorkflowStatus.RETURNED):
            raise ValidationError(f"RA Bill in status '{instance.status}' cannot be modified.")
        if not lines_data:
            raise ValidationError("RA Bill requires at least one BOQ / work progress line.")

        bill_date: date = data["bill_date"]
        due_date: date = data.get("due_date") or (bill_date + timedelta(days=int(party.payment_terms_days or 30)))

        # Duplicate Measurement Book guard
        mb_doc = data.get("measurement_book")
        if mb_doc:
            existing_mb_ref = MeasurementReference.objects.filter(company=company, measurement_doc=mb_doc).exclude(ra_bill=instance)
            if existing_mb_ref.exists():
                raise ValidationError(f"Measurement Book '{mb_doc.doc_number}' is already billed in RA '{existing_mb_ref.first().ra_bill.ra_number}'.")

        sheet = RABillingService.get_contract_boq_billing_sheet(company=company, contract=contract)
        seq_no = int(data.get("ra_sequence_no") or sheet["next_ra_sequence_no"])
        ra_no = (data.get("ra_number") or f"RA-{project.code}-{seq_no:03d}").strip()
        vat_rate = _q2(data.get("vat_rate_pct") if data.get("vat_rate_pct") is not None else "13.00")

        if not instance:
            ra = RABill.objects.create(
                company=company,
                branch=data.get("branch"),
                party=party,
                project=project,
                contract=contract,
                boq_header_id=data.get("boq_header_id") or sheet["boq_header_id"],
                previous_ra_bill_id=data.get("previous_ra_bill_id") or sheet["previous_ra_bill_id"],
                measurement_book=mb_doc,
                bill_category=data.get("bill_category") or RABill.BillCategory.PROGRESS_RA,
                ra_number=ra_no,
                ra_sequence_no=seq_no,
                bill_date=bill_date,
                period_from=data.get("period_from"),
                period_to=data.get("period_to"),
                due_date=due_date,
                currency_code=(data.get("currency_code") or getattr(contract, "currency", None) or getattr(project, "currency", None) or "NPR").upper(),
                exchange_rate=Decimal(str(data.get("exchange_rate") or "1.000000")),
                vat_rate_pct=vat_rate,
                remarks=data.get("remarks", ""),
                created_by=user,
            )
        else:
            ra = instance
            ra.bill_date = bill_date
            ra.due_date = due_date
            ra.period_from = data.get("period_from")
            ra.period_to = data.get("period_to")
            ra.vat_rate_pct = vat_rate
            ra.remarks = data.get("remarks", "")
            ra.measurement_book = mb_doc
            ra.version += 1
            ra.status = RABill.WorkflowStatus.DRAFT
            ra.lines.all().delete()
            ra.deductions.all().delete()

        # Map previous cumulative by boq_line_id
        prev_map = {item["boq_line_id"]: Decimal(item["previous_cumulative_qty"]) for item in sheet["items"]}

        prev_gross_sum = Decimal("0.00")
        curr_gross_sum = Decimal("0.00")
        cum_gross_sum = Decimal("0.00")

        for idx, row in enumerate(lines_data, start=1):
            boq_line = None
            if row.get("boq_line_id") or row.get("boq_line"):
                bl_ref = row.get("boq_line") or row.get("boq_line_id")
                boq_line = bl_ref if isinstance(bl_ref, ProjectBoqLine) else ProjectBoqLine.objects.get(pk=bl_ref, project=project)

            c_qty = _q3(row.get("contract_qty") if row.get("contract_qty") is not None else (boq_line.revised_qty if boq_line and boq_line.revised_qty > 0 else (boq_line.contract_qty if boq_line else "0")))
            c_rate = _q2(row.get("contract_rate") if row.get("contract_rate") is not None else (boq_line.revised_rate if boq_line and boq_line.revised_rate > 0 else (boq_line.contract_rate if boq_line else "0")))
            prev_qty = _q3(row.get("previous_cumulative_qty") if row.get("previous_cumulative_qty") is not None else (prev_map.get(str(boq_line.id), Decimal("0.000")) if boq_line else "0"))
            curr_qty = _q3(row.get("current_qty") or "0.000")
            if curr_qty < 0:
                raise ValidationError(f"Line {idx}: Current RA quantity cannot be negative.")
            cum_qty = prev_qty + curr_qty

            vo = row.get("variation_order")
            if isinstance(vo, str):
                vo = ProjectVariationOrder.objects.get(pk=vo, project=project)

            is_excess = c_qty > 0 and cum_qty > c_qty
            if is_excess:
                if not vo or vo.status != ProjectVariationOrder.Status.APPROVED:
                    raise ValidationError(
                        f"BOQ item '{row.get('item_code') or (boq_line.item_code if boq_line else idx)}' cumulative qty ({cum_qty}) "
                        f"exceeds contract BOQ qty ({c_qty}). Link an APPROVED Variation Order first."
                    )

            rem_qty = max(c_qty - cum_qty, Decimal("0.000"))
            prev_val = (prev_qty * c_rate).quantize(Q2, rounding=ROUND_HALF_UP)
            curr_val = (curr_qty * c_rate).quantize(Q2, rounding=ROUND_HALF_UP)
            cum_val = (cum_qty * c_rate).quantize(Q2, rounding=ROUND_HALF_UP)
            contract_val = (c_qty * c_rate).quantize(Q2, rounding=ROUND_HALF_UP)
            bal_val = max(contract_val - cum_val, Decimal("0.00"))

            prev_gross_sum += prev_val
            curr_gross_sum += curr_val
            cum_gross_sum += cum_val

            RABillLine.objects.create(
                ra_bill=ra,
                boq_line=boq_line,
                variation_order=vo,
                line_no=idx,
                item_code=row.get("item_code") or (boq_line.item_code if boq_line else f"ITM-{idx:02d}"),
                description=row.get("description") or (boq_line.description if boq_line else "Work Executed"),
                unit=row.get("unit") or (boq_line.unit if boq_line else "Cum"),
                contract_qty=c_qty,
                contract_rate=c_rate,
                previous_cumulative_qty=prev_qty,
                current_qty=curr_qty,
                cumulative_qty=cum_qty,
                remaining_qty=rem_qty,
                previous_value=prev_val,
                current_value=curr_val,
                cumulative_value=cum_val,
                balance_value=bal_val,
                is_variation_excess=is_excess,
                measurement_ref=row.get("measurement_ref", ""),
            )

        if curr_gross_sum <= 0:
            raise ValidationError("RA Bill current gross executed value must exceed zero.")

        vat_amt = (curr_gross_sum * vat_rate / Decimal("100")).quantize(Q2, rounding=ROUND_HALF_UP)
        gross_with_vat = curr_gross_sum + vat_amt

        # Process deductions or auto-derive from Contract / Policy defaults
        ded_rows = deductions_data
        if ded_rows is None:
            ded_rows = []
            ret_pct = _q2(data.get("retention_pct") if data.get("retention_pct") is not None else contract.retention_rate)
            if ret_pct > 0:
                ret_base = gross_with_vat if contract.retention_on_vat else curr_gross_sum
                ded_rows.append({
                    "deduction_type": RABillDeduction.DeductionType.RETENTION,
                    "description": f"Contract Retention @ {ret_pct}%",
                    "base_amount": ret_base,
                    "rate_pct": ret_pct,
                    "amount": (ret_base * ret_pct / Decimal("100")).quantize(Q2, rounding=ROUND_HALF_UP),
                })
            adv_amt = _q2(data.get("advance_recovery_amount") or "0.00")
            if adv_amt > 0:
                ded_rows.append({
                    "deduction_type": RABillDeduction.DeductionType.ADVANCE_RECOVERY,
                    "description": "Mobilization Advance Recovery",
                    "base_amount": curr_gross_sum,
                    "rate_pct": Decimal("0.000"),
                    "amount": adv_amt,
                })
            tds_amt = _q2(data.get("tds_deduction_amount") or "0.00")
            if tds_amt > 0:
                ded_rows.append({
                    "deduction_type": RABillDeduction.DeductionType.CLIENT_TDS,
                    "description": "Client Withholding Tax (TDS)",
                    "base_amount": curr_gross_sum,
                    "rate_pct": Decimal("0.000"),
                    "amount": tds_amt,
                })

        ret_total = Decimal("0.00")
        adv_total = Decimal("0.00")
        tds_total = Decimal("0.00")
        other_total = Decimal("0.00")
        for d in ded_rows:
            amt = _q2(d.get("amount") or "0.00")
            if amt <= 0 and _q2(d.get("rate_pct") or "0") > 0:
                base = _q2(d.get("base_amount") or curr_gross_sum)
                amt = (base * Decimal(str(d["rate_pct"])) / Decimal("100")).quantize(Q2, rounding=ROUND_HALF_UP)
            if amt <= 0:
                continue
            dtype = d["deduction_type"]
            RABillDeduction.objects.create(
                ra_bill=ra,
                deduction_type=dtype,
                description=d.get("description", dtype),
                base_amount=_q2(d.get("base_amount") or curr_gross_sum),
                rate_pct=_q3(d.get("rate_pct") or "0.000"),
                amount=amt,
                gl_account=d.get("gl_account"),
                advance_record=d.get("advance_record"),
            )
            if dtype == RABillDeduction.DeductionType.RETENTION:
                ret_total += amt
            elif dtype == RABillDeduction.DeductionType.ADVANCE_RECOVERY:
                adv_total += amt
            elif dtype == RABillDeduction.DeductionType.CLIENT_TDS:
                tds_total += amt
            else:
                other_total += amt

        total_ded = ret_total + adv_total + tds_total + other_total
        net_rec = gross_with_vat - total_ded
        if net_rec <= 0:
            raise ValidationError("RA Bill net receivable amount must exceed zero after deductions.")

        ra.previous_cumulative_gross = prev_gross_sum
        ra.current_gross_amount = curr_gross_sum
        ra.cumulative_gross_amount = cum_gross_sum
        ra.vat_amount = vat_amt
        ra.gross_with_vat = gross_with_vat
        ra.retention_amount = ret_total
        ra.advance_recovery_amount = adv_total
        ra.tds_deduction_amount = tds_total
        ra.other_deductions_amount = other_total
        ra.total_deductions = total_ded
        ra.net_receivable_amount = net_rec
        ra.save()

        if mb_doc:
            MeasurementReference.objects.update_or_create(
                ra_bill=ra,
                measurement_doc=mb_doc,
                defaults={"company": company, "verified_qty": sum((l.current_qty for l in ra.lines.all()), Decimal("0.000"))},
            )

        log_ar_audit(company, "RABill", ra.id, "RA_BILL_SAVED", user, {"ra_number": ra.ra_number, "current_gross": str(curr_gross_sum), "net_receivable": str(net_rec)})
        return ra

    @staticmethod
    def _enforce_maker_checker(ra: RABill, user, target_stage: str):
        policy = get_ar_policy(ra.company)
        if not policy.enforce_maker_checker_ra or user.is_superuser:
            return
        if target_stage in (
            RABill.WorkflowStatus.ACCOUNTS_REVIEWED,
            RABill.WorkflowStatus.AUTHORIZED,
            RABill.WorkflowStatus.POSTED,
        ) and ra.created_by_id == user.id:
            raise ValidationError(
                f"Maker-checker segregation enforced: creator ({user.username}) cannot perform '{target_stage}'."
            )

    @staticmethod
    @transaction.atomic
    def transition_workflow(*, ra_bill: RABill, action: str, user, payload: dict | None = None) -> RABill:
        payload = payload or {}
        ra = RABill.objects.select_for_update().get(pk=ra_bill.pk)
        S = RABill.WorkflowStatus

        transitions = {
            "verify_measurement": ((S.DRAFT, S.RETURNED), S.MEASUREMENT_VERIFIED, "verified_by"),
            "approve_engineer": ((S.MEASUREMENT_VERIFIED,), S.ENGINEER_APPROVED, "engineer_approved_by"),
            "review_pm": ((S.ENGINEER_APPROVED,), S.PM_REVIEWED, "pm_reviewed_by"),
            "review_accounts": ((S.PM_REVIEWED,), S.ACCOUNTS_REVIEWED, "accounts_reviewed_by"),
            "authorize": ((S.ACCOUNTS_REVIEWED,), S.AUTHORIZED, "authorized_by"),
            "submit_client": ((S.AUTHORIZED,), S.SUBMITTED_TO_CLIENT, None),
        }

        if action in transitions:
            allowed_from, next_status, actor_field = transitions[action]
            if ra.status not in allowed_from:
                raise ValidationError(f"Cannot execute '{action}' from status '{ra.status}'. Expected {allowed_from}.")
            RABillingService._enforce_maker_checker(ra, user, next_status)
            ra.status = next_status
            if actor_field:
                setattr(ra, actor_field, user)
            ra.save()
        elif action == "certify":
            if ra.status not in (S.SUBMITTED_TO_CLIENT, S.PARTIALLY_CERTIFIED):
                raise ValidationError("RA Bill must be SUBMITTED_TO_CLIENT before recording client certification.")
            cert_no = (payload.get("certificate_no") or "").strip()
            cert_date = payload.get("certified_date") or timezone.localdate()
            cert_gross = _q2(payload.get("certified_gross_amount") or ra.current_gross_amount)
            if not cert_no:
                raise ValidationError("Client certificate number is required.")
            if cert_gross <= 0 or cert_gross > ra.current_gross_amount:
                raise ValidationError("Certified gross must be positive and cannot exceed submitted RA gross.")

            is_partial = cert_gross < ra.current_gross_amount or bool(payload.get("is_partial", False))
            cert_vat = (cert_gross * ra.vat_rate_pct / Decimal("100")).quantize(Q2, rounding=ROUND_HALF_UP)
            scale = (cert_gross / ra.current_gross_amount) if ra.current_gross_amount > 0 else Decimal("1")
            cert_ret = (ra.retention_amount * scale).quantize(Q2, rounding=ROUND_HALF_UP)
            cert_adv = (ra.advance_recovery_amount * scale).quantize(Q2, rounding=ROUND_HALF_UP)
            cert_tds = (ra.tds_deduction_amount * scale).quantize(Q2, rounding=ROUND_HALF_UP)
            cert_other = (ra.other_deductions_amount * scale).quantize(Q2, rounding=ROUND_HALF_UP)
            cert_ded = cert_ret + cert_adv + cert_tds + cert_other
            cert_net = _q2(payload.get("certified_net_amount")) if payload.get("certified_net_amount") else (cert_gross + cert_vat - cert_ded)

            RABillCertification.objects.create(
                ra_bill=ra,
                certificate_no=cert_no,
                certified_date=cert_date,
                certified_gross_amount=cert_gross,
                certified_deductions_amount=cert_ded,
                certified_net_amount=cert_net,
                certified_by_client_officer=payload.get("certified_by_client_officer", ""),
                remarks=payload.get("remarks", ""),
                supporting_doc_ref=payload.get("supporting_doc_ref", ""),
                recorded_by=user,
            )
            ra.certified_gross_amount = cert_gross
            ra.certified_net_amount = cert_net
            ra.vat_amount = cert_vat
            ra.gross_with_vat = cert_gross + cert_vat
            ra.retention_amount = cert_ret
            ra.advance_recovery_amount = cert_adv
            ra.tds_deduction_amount = cert_tds
            ra.other_deductions_amount = cert_other
            ra.total_deductions = cert_ded
            ra.net_receivable_amount = cert_net
            ra.status = S.PARTIALLY_CERTIFIED if is_partial else S.CLIENT_CERTIFIED
            ra.save()
        elif action == "return":
            if ra.voucher_id is not None:
                raise ValidationError("Posted RA Bill cannot be returned.")
            ra.status = S.RETURNED
            ra.return_reason = payload.get("reason", "Returned for correction")
            ra.save(update_fields=["status", "return_reason", "updated_at"])
        elif action == "reject":
            if ra.voucher_id is not None:
                raise ValidationError("Posted RA Bill cannot be rejected.")
            ra.status = S.REJECTED
            ra.return_reason = payload.get("reason", "Rejected")
            ra.save(update_fields=["status", "return_reason", "updated_at"])
        elif action == "post":
            return RABillingService.post_to_ar(ra_bill=ra, user=user)
        else:
            raise ValidationError(f"Unsupported RA Bill transition '{action}'.")

        log_ar_audit(ra.company, "RABill", ra.id, f"RA_BILL_{action.upper()}", user, {"status": ra.status})
        return ra

    @staticmethod
    @transaction.atomic
    def post_to_ar(*, ra_bill: RABill, user) -> RABill:
        ra = RABill.objects.select_for_update().get(pk=ra_bill.pk)
        if ra.voucher_id is not None:
            raise ValidationError(f"RA Bill {ra.ra_number} has already been posted to AR (Voucher {ra.voucher.voucher_no}).")

        policy = get_ar_policy(ra.company)
        allowed_post_statuses = [RABill.WorkflowStatus.CLIENT_CERTIFIED, RABill.WorkflowStatus.PARTIALLY_CERTIFIED]
        if not policy.require_client_certification_before_posting:
            allowed_post_statuses.append(RABill.WorkflowStatus.AUTHORIZED)
        if ra.status not in allowed_post_statuses:
            raise ValidationError(
                f"Only Certified RA Bills can post to Accounts Receivable (current status: {ra.status})."
            )
        RABillingService._enforce_maker_checker(ra, user, RABill.WorkflowStatus.POSTED)

        post_gross = ra.certified_gross_amount or ra.current_gross_amount
        post_vat = ra.vat_amount
        post_ret = ra.retention_amount
        post_adv = ra.advance_recovery_amount
        post_tds = ra.tds_deduction_amount
        post_other = ra.other_deductions_amount
        net_rec = (post_gross + post_vat) - (post_ret + post_adv + post_tds + post_other)
        if net_rec <= 0:
            raise ValidationError("Certified net receivable must exceed zero.")

        CustomerGovernanceService.enforce_credit_control(ra.company, ra.party, net_rec)

        accs = resolve_ar_accounts(ra.company, ra.party)
        if not accs["debtors"] or not accs["revenue"]:
            raise ValidationError("Sundry Debtors control or Contract Revenue GL account missing in COA.")

        # Validate open Customer Advance liability sufficiency before posting recovery
        open_advances = list(
            AdvanceRecord.objects.select_for_update()
            .filter(company=ra.company, party=ra.party, advance_type=AdvanceRecord.AdvanceType.CUSTOMER_ADVANCE)
            .exclude(status__in=[AdvanceRecord.Status.SETTLED, AdvanceRecord.Status.CANCELLED])
            .order_by("issue_date", "advance_no")
        )
        total_avail_adv = sum((a.remaining_amount for a in open_advances), Decimal("0.00"))
        if post_adv > 0 and total_avail_adv > 0 and post_adv > total_avail_adv:
            raise ValidationError(
                f"Advance recovery ({post_adv}) exceeds customer's unrecovered advance balance ({total_avail_adv})."
            )

        lines_data = [
            {
                "account": accs["debtors"],
                "party": ra.party,
                "debit": net_rec,
                "credit": Decimal("0.00"),
                "project": ra.project,
                "description": f"Certified Net Receivable — {ra.ra_number}",
            }
        ]
        if post_ret > 0:
            if not accs["retention"]:
                raise ValidationError("Retention Receivable GL account missing for certified retention.")
            lines_data.append({
                "account": accs["retention"],
                "party": ra.party,
                "debit": post_ret,
                "credit": Decimal("0.00"),
                "project": ra.project,
                "description": f"Contract Retention Receivable — {ra.ra_number}",
            })
        if post_adv > 0:
            if not accs["advance"]:
                raise ValidationError("Customer Advance Liability GL account missing for advance recovery.")
            lines_data.append({
                "account": accs["advance"],
                "party": ra.party,
                "debit": post_adv,
                "credit": Decimal("0.00"),
                "project": ra.project,
                "advance_record": open_advances[0] if open_advances else None,
                "description": f"Mobilization Advance Recovery — {ra.ra_number}",
            })
        if post_tds > 0:
            lines_data.append({
                "account": accs["tds"],
                "party": ra.party if accs["tds"].is_party_control else None,
                "debit": post_tds,
                "credit": Decimal("0.00"),
                "project": ra.project,
                "description": f"Client Withholding TDS — {ra.ra_number}",
            })
        if post_other > 0:
            lines_data.append({
                "account": accs["deduction_expense"],
                "debit": post_other,
                "credit": Decimal("0.00"),
                "project": ra.project,
                "description": f"Approved Contract Deductions — {ra.ra_number}",
            })

        # Credits: Contract Revenue + Output VAT
        lines_data.append({
            "account": accs["revenue"],
            "debit": Decimal("0.00"),
            "credit": post_gross,
            "project": ra.project,
            "description": f"Certified Contract Work Revenue — {ra.ra_number}",
        })
        if post_vat > 0 and accs["vat"]:
            lines_data.append({
                "account": accs["vat"],
                "debit": Decimal("0.00"),
                "credit": post_vat,
                "project": ra.project,
                "description": f"Output VAT @ {ra.vat_rate_pct}% — {ra.ra_number}",
            })

        vtype = Voucher.VoucherType.VARIATION_ORDER if ra.bill_category == RABill.BillCategory.VARIATION_CLAIM else Voucher.VoucherType.CLIENT_RA_BILL
        v = VoucherService.create_draft(
            company=ra.company,
            user=ra.created_by,
            data={
                "voucher_type": vtype,
                "voucher_date": ra.bill_date,
                "due_date": ra.due_date,
                "project": ra.project,
                "party": ra.party,
                "branch": ra.branch,
                "currency": ra.currency_code,
                "exchange_rate": ra.exchange_rate,
                "reference_no": ra.ra_number,
                "narration": ra.remarks or f"Client RA Bill {ra.ra_number} ({ra.project.code})",
                "gross_amount": post_gross,
                "tax_amount": post_vat,
                "tds_amount": post_tds,
                "retention_amount": post_ret,
                "advance_recovery_amount": post_adv,
                "net_amount": net_rec,
            },
            lines_data=lines_data,
        )
        v.status = Voucher.Status.APPROVED
        v.approved_by = ra.authorized_by or user
        v.save(update_fields=["status", "approved_by"])
        v = PostingService.post_voucher(voucher=v, user=user)

        # Link synced OpenItem + enrich RetentionSchedule certificate/contract metadata
        oi = OpenItem.objects.filter(voucher=v, party=ra.party, hub_side=OpenItem.HubSide.RECEIVABLE, is_unallocated_credit=False).first()
        latest_cert = ra.certifications.first()
        RetentionSchedule.objects.filter(
            source_voucher=v, party=ra.party, direction=RetentionSchedule.Direction.RECEIVABLE
        ).update(
            contract_ref=ra.contract.contract_no,
            certificate_no=latest_cert.certificate_no if latest_cert else ra.ra_number,
            defect_liability_end_date=(ra.bill_date + timedelta(days=int(getattr(ra.project, "defect_liability_months", None) or 12) * 30)),
            release_due_date=(ra.bill_date + timedelta(days=int(getattr(ra.project, "defect_liability_months", None) or 12) * 30)),
        )

        # Reconcile any un-adjusted AdvanceRecord balances FIFO (avoiding double-count from PostingService)
        already_adjusted = AdvanceAdjustment.objects.filter(voucher=v).aggregate(s=Sum("adjusted_amount"))["s"] or Decimal("0.00")
        rem_adv_to_reduce = max(post_adv - already_adjusted, Decimal("0.00"))
        for adv in open_advances:
            adv.refresh_from_db()
            if rem_adv_to_reduce <= 0:
                break
            if AdvanceAdjustment.objects.filter(advance=adv, voucher=v).exists():
                continue
            chunk = min(rem_adv_to_reduce, adv.remaining_amount)
            if chunk > 0:
                adv.adjusted_amount += chunk
                adv.status = AdvanceRecord.Status.SETTLED if adv.remaining_amount == 0 else AdvanceRecord.Status.PARTIALLY_ADJUSTED
                adv.save(update_fields=["adjusted_amount", "status"])
                AdvanceAdjustment.objects.create(
                    company=ra.company,
                    advance=adv,
                    voucher=v,
                    adjusted_amount=chunk,
                    supporting_bill_ref=ra.ra_number,
                    notes=f"Auto-recovered via RA Bill {ra.ra_number}",
                    adjusted_by=user,
                )
                rem_adv_to_reduce -= chunk

        # Update cumulative BOQ completed quantities
        for line in ra.lines.select_related("boq_line").all():
            if line.boq_line:
                line.boq_line.previous_certified_qty = line.cumulative_qty
                line.boq_line.completed_qty = line.cumulative_qty
                line.boq_line.save(update_fields=["previous_certified_qty", "completed_qty"])

        ra.voucher = v
        ra.open_item = oi
        ra.status = RABill.WorkflowStatus.POSTED
        ra.posted_by = user
        ra.posted_at = timezone.now()
        ra.save(update_fields=["voucher", "open_item", "status", "posted_by", "posted_at", "updated_at"])

        log_ar_audit(ra.company, "RABill", ra.id, "RA_BILL_POSTED_TO_AR", user, {"voucher_no": v.voucher_no, "net_receivable": str(net_rec)})
        return ra

    @staticmethod
    def compare_ra_bill(*, ra_bill: RABill) -> dict:
        prev = ra_bill.previous_ra_bill
        prev_lines = {l.boq_line_id or l.item_code: l for l in prev.lines.all()} if prev else {}
        comparison_rows = []
        for l in ra_bill.lines.all():
            key = l.boq_line_id or l.item_code
            p = prev_lines.get(key)
            prev_curr_qty = p.current_qty if p else Decimal("0.000")
            qty_delta = l.current_qty - prev_curr_qty
            comparison_rows.append({
                "item_code": l.item_code,
                "description": l.description,
                "unit": l.unit,
                "contract_qty": str(l.contract_qty),
                "contract_rate": str(l.contract_rate),
                "previous_ra_current_qty": str(prev_curr_qty),
                "this_ra_current_qty": str(l.current_qty),
                "qty_delta": str(qty_delta),
                "previous_cumulative_qty": str(l.previous_cumulative_qty),
                "cumulative_qty": str(l.cumulative_qty),
                "remaining_qty": str(l.remaining_qty),
                "current_value": str(l.current_value),
                "cumulative_value": str(l.cumulative_value),
                "is_variation_excess": l.is_variation_excess,
                "flag": "EXCESS_VO" if l.is_variation_excess else ("QTY_SPIKE" if prev_curr_qty > 0 and l.current_qty > prev_curr_qty * Decimal("2") else "NORMAL"),
            })
        return {
            "ra_bill_id": str(ra_bill.id),
            "ra_number": ra_bill.ra_number,
            "previous_ra_number": prev.ra_number if prev else None,
            "previous_cumulative_gross": str(ra_bill.previous_cumulative_gross),
            "current_gross_amount": str(ra_bill.current_gross_amount),
            "cumulative_gross_amount": str(ra_bill.cumulative_gross_amount),
            "lines": comparison_rows,
        }
