from decimal import Decimal, ROUND_HALF_UP
from django.db.models import Sum
from apps.accounting.models import (
    Account,
    AccountRelationship,
    AccountingPolicy,
    AdvanceRecord,
    EquipmentAsset,
    LedgerEntry,
    Party,
    PartyLedgerEntry,
    PayrollLiability,
    PostingRule,
    StaffLoan,
    Voucher,
)
from apps.localization.bs_calendar import ad_to_bs
from apps.localization.tax import compute_vat_and_tds
from apps.tenancy.models import FiscalPeriod


def _find_account_by_role(company, role: str, fallback_prefixes: tuple[str, ...] = ()) -> Account | None:
    acc = Account.objects.select_related("parent").filter(
        company=company, control_role=role, is_group=False, is_active=True
    ).first()
    if acc:
        return acc
    for pfx in fallback_prefixes:
        acc = Account.objects.select_related("parent").filter(
            company=company, code__startswith=pfx, is_group=False, is_active=True
        ).first()
        if acc:
            return acc
    return None


def _current_account_balance(company, account: Account) -> Decimal:
    agg = LedgerEntry.objects.filter(company=company, account=account).aggregate(
        d=Sum("base_debit"), c=Sum("base_credit")
    )
    d = (agg["d"] or Decimal("0.00")) + account.opening_debit
    c = (agg["c"] or Decimal("0.00")) + account.opening_credit
    return (d - c).quantize(Decimal("0.01"))


class PostingRuleEngine:
    """
    Single server-side engine shared by both Logic Preview and Atomic Posting.
    Never duplicates rules across frontend/backend or per-voucher screens.
    """

    @staticmethod
    def get_or_create_policy(company) -> AccountingPolicy:
        policy, _ = AccountingPolicy.objects.get_or_create(company=company)
        return policy

    @staticmethod
    def derive_scenario_lines(
        *,
        company,
        voucher_type: str,
        scenario: dict,
        party: Party | None = None,
        project=None,
        site=None,
        cost_code=None,
    ) -> list[dict]:
        """
        Derive balanced Dr/Cr lines dynamically from AccountingPolicy, PostingRule, and Nepal Tax config
        when a structured commercial/construction payload is submitted (e.g. Subcontractor RA Bill, Material Purchase).
        """
        policy = PostingRuleEngine.get_or_create_policy(company)
        q = Decimal("0.01")
        gross = Decimal(str(scenario.get("taxable_amount") or scenario.get("gross_amount") or "0.00")).quantize(q)
        if gross <= 0:
            return []

        vat_rate = Decimal(str(scenario.get("vat_rate") or company.default_vat_rate or "0.00"))
        tds_rate = Decimal(str(scenario.get("tds_rate") or "0.00"))
        retention_pct = Decimal(str(scenario.get("retention_pct") or "0.00"))
        advance_recovery = Decimal(str(scenario.get("advance_recovery_amount") or "0.00")).quantize(q)

        tax_calc = compute_vat_and_tds(gross, vat_rate=vat_rate, tds_rate=tds_rate)
        vat_amt = tax_calc["vat_amount"]
        tds_amt = tax_calc["tds_amount"]
        ret_amt = (gross * retention_pct / Decimal("100")).quantize(q, rounding=ROUND_HALF_UP)

        rule = PostingRule.objects.select_related(
            "debit_account", "credit_account", "tax_account", "tds_account", "retention_account", "advance_account"
        ).filter(company=company, voucher_type=voucher_type, is_active=True).first()

        lines: list[dict] = []

        if voucher_type in ("PURCHASE", "MATERIAL_PURCHASE", "SITE_PURCHASE"):
            is_perpetual = policy.inventory_method == AccountingPolicy.InventoryMethod.PERPETUAL and voucher_type == "MATERIAL_PURCHASE"
            dr_acc = (
                (rule.debit_account if rule else None)
                or (_find_account_by_role(company, Account.ControlRole.INVENTORY, ("13", "105")) if is_perpetual else _find_account_by_role(company, Account.ControlRole.PROJECT_WIP, ("50", "51")))
            )
            vat_acc = (rule.tax_account if rule else None) or _find_account_by_role(company, Account.ControlRole.INPUT_VAT, ("125", "120"))
            cr_acc = (party.control_account if party and party.control_account else None) or (rule.credit_account if rule else None) or _find_account_by_role(company, Account.ControlRole.SUNDRY_CREDITORS, ("201", "20"))
            if dr_acc and cr_acc:
                lines.append({"account": dr_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "site": site, "cost_code": cost_code, "description": "Material / Inventory Purchase", "is_auto_generated": True})
                if vat_amt > 0 and vat_acc:
                    lines.append({"account": vat_acc, "debit": vat_amt, "credit": Decimal("0.00"), "project": project, "description": f"Input VAT @ {vat_rate}%", "is_auto_generated": True})
                total_payable = gross + (vat_amt if vat_acc else Decimal("0.00"))
                if tds_amt > 0:
                    tds_acc = (rule.tds_account if rule else None) or _find_account_by_role(company, Account.ControlRole.TDS_PAYABLE, ("205",))
                    if tds_acc:
                        lines.append({"account": tds_acc, "debit": Decimal("0.00"), "credit": tds_amt, "description": f"TDS Withholding @ {tds_rate}%", "is_auto_generated": True})
                        total_payable -= tds_amt
                lines.append({"account": cr_acc, "party": party, "debit": Decimal("0.00"), "credit": total_payable, "project": project, "description": "Supplier Payable Control", "is_auto_generated": True})

        elif voucher_type == "MATERIAL_CONSUMPTION":
            wip_acc = (rule.debit_account if rule else None) or _find_account_by_role(company, Account.ControlRole.PROJECT_WIP, ("14", "501"))
            inv_acc = (rule.credit_account if rule else None) or _find_account_by_role(company, Account.ControlRole.INVENTORY, ("13", "105"))
            if wip_acc and inv_acc:
                lines.append({"account": wip_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "site": site, "cost_code": cost_code, "description": "Project WIP / Material Consumption", "is_auto_generated": True})
                lines.append({"account": inv_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "site": site, "description": "Inventory Stock Issue", "is_auto_generated": True})

        elif voucher_type == "SUBCONTRACTOR_BILL":
            dr_acc = (rule.debit_account if rule else None) or _find_account_by_role(company, Account.ControlRole.PROJECT_WIP, ("52", "50"))
            ret_acc = (rule.retention_account if rule else None) or _find_account_by_role(company, Account.ControlRole.RETENTION_PAYABLE, ("206",))
            tds_acc = (rule.tds_account if rule else None) or _find_account_by_role(company, Account.ControlRole.TDS_PAYABLE, ("205",))
            cr_acc = (party.control_account if party and party.control_account else None) or (rule.credit_account if rule else None) or _find_account_by_role(company, Account.ControlRole.SUBCONTRACTOR_PAYABLE, ("202", "201"))
            if dr_acc and cr_acc:
                lines.append({"account": dr_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "site": site, "cost_code": cost_code, "contractor": party, "description": "Certified Subcontract Work", "is_auto_generated": True})
                net_sub = gross
                if ret_amt > 0 and ret_acc:
                    lines.append({"account": ret_acc, "party": party, "debit": Decimal("0.00"), "credit": ret_amt, "project": project, "description": f"Retention Payable @ {retention_pct}%", "is_auto_generated": True})
                    net_sub -= ret_amt
                if tds_amt > 0 and tds_acc:
                    lines.append({"account": tds_acc, "debit": Decimal("0.00"), "credit": tds_amt, "description": f"Contractor TDS @ {tds_rate}%", "is_auto_generated": True})
                    net_sub -= tds_amt
                if advance_recovery > 0:
                    adv_acc = (rule.advance_account if rule else None) or _find_account_by_role(company, Account.ControlRole.SUPPLIER_ADVANCE, ("115",))
                    if adv_acc:
                        lines.append({"account": adv_acc, "party": party, "debit": Decimal("0.00"), "credit": advance_recovery, "project": project, "description": "Mobilization Advance Recovery", "is_auto_generated": True})
                        net_sub -= advance_recovery
                lines.append({"account": cr_acc, "party": party, "debit": Decimal("0.00"), "credit": net_sub, "project": project, "description": "Net Subcontractor Payable", "is_auto_generated": True})

        elif voucher_type in ("SALES", "CLIENT_RA_BILL"):
            dr_acc = (party.control_account if party and party.control_account else None) or _find_account_by_role(company, Account.ControlRole.SUNDRY_DEBTORS, ("110", "11"))
            rev_acc = (rule.credit_account if rule else None) or _find_account_by_role(company, Account.ControlRole.NONE, ("40", "401"))
            vat_acc = (rule.tax_account if rule else None) or _find_account_by_role(company, Account.ControlRole.OUTPUT_VAT, ("204", "210"))
            ret_acc = (rule.retention_account if rule else None) or _find_account_by_role(company, Account.ControlRole.RETENTION_RECEIVABLE, ("116",))
            adv_acc = (rule.advance_account if rule else None) or _find_account_by_role(company, Account.ControlRole.CUSTOMER_ADVANCE, ("207",))
            if dr_acc and rev_acc:
                total_billed = gross + (vat_amt if vat_acc else Decimal("0.00"))
                net_receivable = total_billed
                if ret_amt > 0 and ret_acc:
                    lines.append({"account": ret_acc, "party": party, "debit": ret_amt, "credit": Decimal("0.00"), "project": project, "description": f"Client Retention Receivable @ {retention_pct}%", "is_auto_generated": True})
                    net_receivable -= ret_amt
                if advance_recovery > 0 and adv_acc:
                    lines.append({"account": adv_acc, "party": party, "debit": advance_recovery, "credit": Decimal("0.00"), "project": project, "description": "Customer Advance Adjusted", "is_auto_generated": True})
                    net_receivable -= advance_recovery
                lines.append({"account": dr_acc, "party": party, "debit": net_receivable, "credit": Decimal("0.00"), "project": project, "description": "Sundry Debtors / Client Receivable", "is_auto_generated": True})
                lines.append({"account": rev_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Certified Contract Revenue", "is_auto_generated": True})
                if vat_amt > 0 and vat_acc:
                    lines.append({"account": vat_acc, "debit": Decimal("0.00"), "credit": vat_amt, "description": f"Output VAT @ {vat_rate}%", "is_auto_generated": True})

        elif voucher_type == "MOBILIZATION_ADVANCE":
            bank_acc = (rule.debit_account if rule else None) or _find_account_by_role(company, Account.ControlRole.BANK, ("102",))
            adv_acc = (rule.credit_account if rule else None) or _find_account_by_role(company, Account.ControlRole.CUSTOMER_ADVANCE, ("207",))
            if bank_acc and adv_acc:
                lines.append({"account": bank_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": "Mobilization Advance Bank Receipt", "is_auto_generated": True})
                lines.append({"account": adv_acc, "party": party, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Customer Contract Advance Liability (Not Revenue)", "is_auto_generated": True})

        elif voucher_type == "MACHINE_INCOME":
            inc_acc = (
                (Account.objects.filter(company=company, id=scenario.get("income_account"), is_group=False).first() if scenario.get("income_account") else None)
                or (rule.credit_account if rule else None)
                or _find_account_by_role(company, Account.ControlRole.OTHER_INCOME, ("415", "41", "40"))
            )
            vat_acc = (rule.tax_account if rule else None) or _find_account_by_role(company, Account.ControlRole.OUTPUT_VAT, ("204", "210"))
            raw_eq = scenario.get("equipment")
            eq_obj = (
                raw_eq
                if isinstance(raw_eq, EquipmentAsset)
                else (EquipmentAsset.objects.filter(company=company, id=raw_eq).first() if raw_eq else None)
            )
            bank_acc = (
                Account.objects.filter(company=company, id=scenario.get("bank_account"), is_group=False).first()
                if scenario.get("bank_account")
                else None
            )
            entry_style = str(scenario.get("entry_style") or ("CREDIT" if party and not bank_acc else "CASH")).upper()
            if entry_style == "CASH" or bank_acc:
                dr_acc = bank_acc or _find_account_by_role(company, Account.ControlRole.CASH, ("101",)) or _find_account_by_role(company, Account.ControlRole.BANK, ("102",))
                dr_party = None
                dr_desc = "Cash/Bank Machine Hire Income Receipt"
            else:
                dr_acc = (party.control_account if party and party.control_account else None) or _find_account_by_role(company, Account.ControlRole.SUNDRY_DEBTORS, ("110", "11"))
                dr_party = party
                dr_desc = "Customer Machine Hire Receivable"

            if dr_acc and inc_acc:
                total_rec = gross + (vat_amt if vat_acc and vat_amt > 0 else Decimal("0.00"))
                lines.append({"account": dr_acc, "party": dr_party, "debit": total_rec, "credit": Decimal("0.00"), "project": project, "site": site, "equipment": eq_obj, "description": dr_desc, "is_auto_generated": True})
                lines.append({"account": inc_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "site": site, "cost_code": cost_code, "equipment": eq_obj, "description": "Machine & Equipment Hire Income", "is_auto_generated": True})
                if vat_amt > 0 and vat_acc:
                    lines.append({"account": vat_acc, "debit": Decimal("0.00"), "credit": vat_amt, "project": project, "description": f"Output VAT @ {vat_rate}%", "is_auto_generated": True})

        elif voucher_type == "WAGE_ACCRUAL":
            lab_acc = _find_account_by_role(company, Account.ControlRole.DIRECT_EXPENSES, ("502", "50"))
            wag_acc = _find_account_by_role(company, Account.ControlRole.WAGES_PAYABLE, ("2035", "203"))
            if lab_acc and wag_acc:
                lines.append({"account": lab_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "site": site, "cost_code": cost_code, "description": "Labor & Site Wages Expense", "is_auto_generated": True})
                lines.append({"account": wag_acc, "party": party, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Wages Payable Control", "is_auto_generated": True})

        elif voucher_type == "DEPRECIATION":
            dep_exp = _find_account_by_role(company, Account.ControlRole.DEPRECIATION_EXP, ("605",))
            acc_dep = _find_account_by_role(company, Account.ControlRole.ACCUM_DEPRECIATION, ("159",))
            if dep_exp and acc_dep:
                lines.append({"account": dep_exp, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": "Equipment & Asset Depreciation", "is_auto_generated": True})
                lines.append({"account": acc_dep, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Accumulated Depreciation", "is_auto_generated": True})

        elif voucher_type in ("STAFF_ADVANCE",):
            adv_acc = _find_account_by_role(company, Account.ControlRole.EMPLOYEE_ADVANCE, ("117",))
            bank_acc = _find_account_by_role(company, Account.ControlRole.BANK, ("102",)) or _find_account_by_role(company, Account.ControlRole.CASH, ("101",))
            if adv_acc and bank_acc:
                lines.append({"account": adv_acc, "party": party, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": "Staff Advance Asset", "is_auto_generated": True})
                lines.append({"account": bank_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Advance Bank / Cash Disbursement", "is_auto_generated": True})

        elif voucher_type == "CONTRA":
            src = Account.objects.filter(company=company, id=scenario.get("source_account"), is_group=False).first()
            dst = Account.objects.filter(company=company, id=scenario.get("destination_account"), is_group=False).first()
            if src and dst:
                lines.append({"account": dst, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": f"Contra Transfer In ({src.code} -> {dst.code})", "is_auto_generated": True})
                lines.append({"account": src, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": f"Contra Transfer Out ({src.code} -> {dst.code})", "is_auto_generated": True})

        elif voucher_type in ("PAYMENT", "RECEIPT"):
            bank_acc = Account.objects.filter(company=company, id=scenario.get("bank_account"), is_group=False).first() or _find_account_by_role(company, Account.ControlRole.BANK, ("102",)) or _find_account_by_role(company, Account.ControlRole.CASH, ("101",))
            is_receipt = voucher_type == "RECEIPT"
            explicit_debit = Account.objects.filter(company=company, id=scenario.get("debit_account"), is_group=False).first() if scenario.get("debit_account") else None
            party_acc = (
                explicit_debit
                or (party.control_account if party and party.control_account else None)
                or _find_account_by_role(company, Account.ControlRole.SUNDRY_DEBTORS if is_receipt else Account.ControlRole.SUNDRY_CREDITORS, ("110",) if is_receipt else ("201",))
            )
            if bank_acc and party_acc:
                if is_receipt:
                    lines.append({"account": bank_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": "Inward Receipt Bank/Cash", "is_auto_generated": True})
                    lines.append({"account": party_acc, "party": party, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Customer Receivable Settlement", "is_auto_generated": True})
                else:
                    net_pay = gross - tds_amt
                    lines.append({"account": party_acc, "party": party, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": "Supplier/Party Payable Settlement", "is_auto_generated": True})
                    if tds_amt > 0:
                        tds_acc = _find_account_by_role(company, Account.ControlRole.TDS_PAYABLE, ("205",))
                        if tds_acc:
                            lines.append({"account": tds_acc, "debit": Decimal("0.00"), "credit": tds_amt, "description": f"TDS Deducted @ {tds_rate}%", "is_auto_generated": True})
                    lines.append({"account": bank_acc, "debit": Decimal("0.00"), "credit": net_pay, "project": project, "description": "Payment Bank/Cash Outflow", "is_auto_generated": True})

        elif voucher_type in ("MATERIAL_ISSUE", "MATERIAL_RETURN"):
            wip_acc = _find_account_by_role(company, Account.ControlRole.PROJECT_WIP, ("14", "501"))
            inv_acc = _find_account_by_role(company, Account.ControlRole.INVENTORY, ("13", "105"))
            if wip_acc and inv_acc:
                if voucher_type == "MATERIAL_ISSUE":
                    lines.append({"account": wip_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "site": site, "cost_code": cost_code, "description": "Material Issued to Project WIP", "is_auto_generated": True})
                    lines.append({"account": inv_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "site": site, "description": "Warehouse Inventory Stock Reduction", "is_auto_generated": True})
                else:
                    lines.append({"account": inv_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "site": site, "description": "Material Returned to Warehouse Stock", "is_auto_generated": True})
                    lines.append({"account": wip_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "site": site, "cost_code": cost_code, "description": "Project WIP Reversal on Return", "is_auto_generated": True})

        elif voucher_type == "SITE_EXPENSE":
            exp_acc = Account.objects.filter(company=company, id=scenario.get("expense_account"), is_group=False).first() or _find_account_by_role(company, Account.ControlRole.DIRECT_EXPENSES, ("50", "51"))
            cash_acc = Account.objects.filter(company=company, id=scenario.get("cash_advance_account"), is_group=False).first() or _find_account_by_role(company, Account.ControlRole.CASH, ("101",))
            if exp_acc and cash_acc:
                lines.append({"account": exp_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "site": site, "cost_code": cost_code, "description": "Site Direct Field Expense", "is_auto_generated": True})
                lines.append({"account": cash_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "site": site, "description": "Site Petty Cash / Imprest", "is_auto_generated": True})

        elif voucher_type in ("PAYROLL", "LABOR_PAYMENT"):
            wages_exp = _find_account_by_role(company, Account.ControlRole.DIRECT_EXPENSES, ("502", "50"))
            bank_acc = Account.objects.filter(company=company, id=scenario.get("bank_account"), is_group=False).first() or _find_account_by_role(company, Account.ControlRole.WAGES_PAYABLE, ("203",)) or _find_account_by_role(company, Account.ControlRole.BANK, ("102",))
            tds_acc = _find_account_by_role(company, Account.ControlRole.TDS_PAYABLE, ("205",))
            adv_acc = _find_account_by_role(company, Account.ControlRole.EMPLOYEE_ADVANCE, ("117",))
            ded_amt = Decimal(str(scenario.get("deductions_amount") or tds_amt or "0.00")).quantize(q)
            if wages_exp and bank_acc:
                lines.append({"account": wages_exp, "debit": gross, "credit": Decimal("0.00"), "project": project, "site": site, "cost_code": cost_code, "description": "Payroll & Labor Gross Cost", "is_auto_generated": True})
                net_wages = gross
                if ded_amt > 0 and tds_acc:
                    lines.append({"account": tds_acc, "debit": Decimal("0.00"), "credit": ded_amt, "description": "Payroll Tax / Statutory Deduction", "is_auto_generated": True})
                    net_wages -= ded_amt
                if advance_recovery > 0 and adv_acc:
                    lines.append({"account": adv_acc, "party": party, "debit": Decimal("0.00"), "credit": advance_recovery, "description": "Staff Advance Recovery", "is_auto_generated": True})
                    net_wages -= advance_recovery
                lines.append({"account": bank_acc, "party": party, "debit": Decimal("0.00"), "credit": max(Decimal("0.00"), net_wages), "project": project, "description": "Net Salary / Labor Disbursement", "is_auto_generated": True})

        elif voucher_type in ("LOAN_DISBURSEMENT", "LOAN_REPAYMENT"):
            bank_acc = Account.objects.filter(company=company, id=scenario.get("bank_account"), is_group=False).first() or _find_account_by_role(company, Account.ControlRole.BANK, ("102",))
            loan_acc = Account.objects.filter(company=company, id=scenario.get("liability_account"), is_group=False).first() or _find_account_by_role(company, Account.ControlRole.NONE, ("22", "20"))
            int_acc = Account.objects.filter(company=company, id=scenario.get("interest_account"), is_group=False).first() or _find_account_by_role(company, Account.ControlRole.NONE, ("60", "55"))
            if bank_acc and loan_acc:
                if voucher_type == "LOAN_DISBURSEMENT":
                    lines.append({"account": bank_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": "Loan Facility Drawdown Inflow", "is_auto_generated": True})
                    lines.append({"account": loan_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Loan Liability Drawdown", "is_auto_generated": True})
                else:
                    prin = Decimal(str(scenario.get("principal_amount") or gross)).quantize(q)
                    intr = Decimal(str(scenario.get("interest_amount") or "0.00")).quantize(q)
                    lines.append({"account": loan_acc, "debit": prin, "credit": Decimal("0.00"), "project": project, "description": "Loan Principal Repayment", "is_auto_generated": True})
                    if intr > 0 and int_acc:
                        lines.append({"account": int_acc, "debit": intr, "credit": Decimal("0.00"), "project": project, "description": "Loan Interest Expense", "is_auto_generated": True})
                    lines.append({"account": bank_acc, "debit": Decimal("0.00"), "credit": prin + (intr if intr > 0 and int_acc else Decimal("0.00")), "project": project, "description": "EMI / Loan Bank Outflow", "is_auto_generated": True})

        elif voucher_type in ("SUPPLIER_ADVANCE", "CUSTOMER_ADVANCE", "RETENTION", "STAFF_SETTLEMENT", "ASSET_ACQUISITION", "ASSET_DISPOSAL"):
            bank_acc = Account.objects.filter(company=company, id=scenario.get("bank_account"), is_group=False).first() or _find_account_by_role(company, Account.ControlRole.BANK, ("102",))
            if voucher_type == "SUPPLIER_ADVANCE":
                adv_acc = _find_account_by_role(company, Account.ControlRole.SUPPLIER_ADVANCE, ("115",))
                if adv_acc and bank_acc:
                    lines.append({"account": adv_acc, "party": party, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": "Supplier Mobilization Advance", "is_auto_generated": True})
                    lines.append({"account": bank_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Bank Advance Outflow", "is_auto_generated": True})
            elif voucher_type == "CUSTOMER_ADVANCE":
                adv_acc = _find_account_by_role(company, Account.ControlRole.CUSTOMER_ADVANCE, ("207",))
                if adv_acc and bank_acc:
                    lines.append({"account": bank_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": "Customer Advance Receipt", "is_auto_generated": True})
                    lines.append({"account": adv_acc, "party": party, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Customer Advance Liability", "is_auto_generated": True})
            elif voucher_type == "RETENTION":
                ret_pay = _find_account_by_role(company, Account.ControlRole.RETENTION_PAYABLE, ("206",))
                if ret_pay and bank_acc:
                    lines.append({"account": ret_pay, "party": party, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": "Retention Release", "is_auto_generated": True})
                    lines.append({"account": bank_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Retention Settlement Outflow", "is_auto_generated": True})
            elif voucher_type == "STAFF_SETTLEMENT":
                exp_acc = _find_account_by_role(company, Account.ControlRole.DIRECT_EXPENSES, ("50", "51"))
                adv_acc = _find_account_by_role(company, Account.ControlRole.EMPLOYEE_ADVANCE, ("117",))
                if exp_acc and adv_acc:
                    lines.append({"account": exp_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "site": site, "cost_code": cost_code, "description": "Verified Expense against Staff Advance", "is_auto_generated": True})
                    lines.append({"account": adv_acc, "party": party, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Staff Advance Liquidated", "is_auto_generated": True})
            elif voucher_type == "ASSET_ACQUISITION":
                asset_acc = _find_account_by_role(company, Account.ControlRole.NONE, ("15",))
                if asset_acc and bank_acc:
                    lines.append({"account": asset_acc, "debit": gross, "credit": Decimal("0.00"), "project": project, "description": "Fixed Asset Capitalization", "is_auto_generated": True})
                    lines.append({"account": bank_acc, "debit": Decimal("0.00"), "credit": gross, "project": project, "description": "Asset Purchase Payment", "is_auto_generated": True})
            elif voucher_type == "ASSET_DISPOSAL":
                asset_acc = _find_account_by_role(company, Account.ControlRole.NONE, ("15",))
                acc_dep = _find_account_by_role(company, Account.ControlRole.ACCUM_DEPRECIATION, ("159",))
                gain_acc = _find_account_by_role(company, Account.ControlRole.OTHER_INCOME, ("42", "40"))
                loss_acc = _find_account_by_role(company, Account.ControlRole.LOSS_WRITE_OFF, ("69", "60"))
                proceeds = Decimal(str(scenario.get("proceeds_amount") or gross)).quantize(q)
                accum_d = Decimal(str(scenario.get("accumulated_depreciation") or "0.00")).quantize(q)
                cost_amt = Decimal(str(scenario.get("asset_cost") or gross)).quantize(q)
                if asset_acc and bank_acc:
                    if proceeds > 0:
                        lines.append({"account": bank_acc, "debit": proceeds, "credit": Decimal("0.00"), "description": "Asset Disposal Sale Proceeds", "is_auto_generated": True})
                    if accum_d > 0 and acc_dep:
                        lines.append({"account": acc_dep, "debit": accum_d, "credit": Decimal("0.00"), "description": "Derecognize Accumulated Depreciation", "is_auto_generated": True})
                    lines.append({"account": asset_acc, "debit": Decimal("0.00"), "credit": cost_amt, "description": "Derecognize Asset Original Cost", "is_auto_generated": True})
                    net_gl = (proceeds + accum_d) - cost_amt
                    if net_gl > 0 and gain_acc:
                        lines.append({"account": gain_acc, "debit": Decimal("0.00"), "credit": net_gl, "description": "Gain on Asset Disposal", "is_auto_generated": True})
                    elif net_gl < 0 and loss_acc:
                        lines.append({"account": loss_acc, "debit": abs(net_gl), "credit": Decimal("0.00"), "description": "Loss on Asset Disposal", "is_auto_generated": True})

        return lines

    @staticmethod
    def build_voucher_accounting_plan(
        *,
        company,
        voucher_type: str,
        voucher_date,
        lines_data: list[dict],
        party: Party | None = None,
        supplier_invoice_no: str = "",
        is_control_override: bool = False,
        voucher_id=None,
        voucher_type_config=None,
        inventory_items: list[dict] | None = None,
        bill_wise_allocations: list[dict] | None = None,
        operational_payload: dict | None = None,
    ) -> dict:
        """
        Generate live non-mutating Logic View & validation plan matching atomic PostingService rules.
        """
        policy = PostingRuleEngine.get_or_create_policy(company)
        errors: list[str] = []
        warnings: list[str] = []

        if voucher_type_config:
            if not voucher_type_config.is_active:
                errors.append(f"Voucher type '{voucher_type_config.name}' is inactive.")
            if voucher_type_config.effective_from and voucher_date < voucher_type_config.effective_from:
                errors.append(f"Voucher date {voucher_date} is earlier than permitted effective date {voucher_type_config.effective_from}.")
            if voucher_type_config.effective_to and voucher_date > voucher_type_config.effective_to:
                errors.append(f"Voucher date {voucher_date} exceeds permitted effective date {voucher_type_config.effective_to}.")

        period = FiscalPeriod.objects.select_related("fiscal_year").filter(
            fiscal_year__company=company, start_date__lte=voucher_date, end_date__gte=voucher_date
        ).first()
        if not period:
            errors.append(f"No fiscal period configured for {voucher_date}.")
        elif period.fiscal_year.is_closed or period.status != FiscalPeriod.Status.OPEN:
            errors.append(f"Fiscal period '{period.name}' is {period.status}; posting blocked.")

        if (
            policy.duplicate_invoice_check
            and supplier_invoice_no
            and party
            and Voucher.objects.filter(
                company=company, party=party, supplier_invoice_no=supplier_invoice_no
            ).exclude(id=voucher_id).exclude(status__in=[Voucher.Status.CANCELLED, Voucher.Status.REJECTED]).exists()
        ):
            errors.append(f"Duplicate supplier invoice '{supplier_invoice_no}' already exists for {party.name}.")

        if len(lines_data) < 2:
            errors.append("A double-entry voucher requires at least 2 balanced lines.")

        total_debit = Decimal("0.00")
        total_credit = Decimal("0.00")
        journal_preview = []
        tax_summary = {"vat": Decimal("0.00"), "tds": Decimal("0.00")}
        retention_summary = {"receivable": Decimal("0.00"), "payable": Decimal("0.00")}
        inventory_impact = Decimal("0.00")
        wip_impact = Decimal("0.00")
        statement_delta = {"ASSET": Decimal("0.00"), "LIABILITY": Decimal("0.00"), "EQUITY": Decimal("0.00"), "INCOME": Decimal("0.00"), "EXPENSE": Decimal("0.00")}

        rate_limit_check = Decimal("0.00")
        advance_impacts = []
        payroll_impacts = []
        party_impacts = {}
        cash_bank_impacts = {}
        project_cost_impacts = {}
        for idx, line in enumerate(lines_data, start=1):
            acc: Account = line["account"]
            d = Decimal(str(line.get("debit") or "0.00")).quantize(Decimal("0.01"))
            c = Decimal(str(line.get("credit") or "0.00")).quantize(Decimal("0.01"))
            if acc.company_id != company.id:
                errors.append(f"Account {acc.code} belongs to another company.")
            if not acc.is_active:
                errors.append(f"Account {acc.code} is inactive.")
            if acc.is_group:
                errors.append(f"Cannot post directly to group account {acc.code} — {acc.name}.")
            if d < 0 or c < 0 or (d > 0 and c > 0) or (d == 0 and c == 0):
                errors.append(f"Line #{idx} ({acc.code}) must have strictly non-zero Debit OR Credit.")

            line_party = line.get("party") or party
            if (
                policy.enforce_control_subledgers
                and (
                    acc.requires_subledger
                    or acc.control_role
                    in (
                        Account.ControlRole.SUNDRY_DEBTORS,
                        Account.ControlRole.SUNDRY_CREDITORS,
                        Account.ControlRole.SUBCONTRACTOR_PAYABLE,
                        Account.ControlRole.EMPLOYEE_PAYABLE,
                        Account.ControlRole.WAGES_PAYABLE,
                    )
                )
                and not line_party
                and not is_control_override
            ):
                errors.append(
                    f"Control account '{acc.code} — {acc.name}' requires a Customer/Supplier/Subcontractor/Employee subledger (or authorized control override)."
                )

            rel = AccountRelationship.objects.filter(company=company, account=acc, is_active=True).first()
            if rel and rel.require_project and not line.get("project"):
                errors.append(f"Line #{idx} ({acc.code} — {acc.name}) requires a Project selection per accounting relationship policy.")

            amt = d if d > 0 else c
            cost_splits = line.get("cost_allocations") or []
            if cost_splits:
                split_total = sum((Decimal(str(s.get("amount") or "0.00")).quantize(Decimal("0.01")) for s in cost_splits), Decimal("0.00"))
                if split_total != amt:
                    errors.append(
                        f"Line #{idx} ({acc.code}) cost centre split total ({split_total}) must equal line amount ({amt})."
                    )
                if all(s.get("allocation_mode", "PERCENTAGE") == "PERCENTAGE" for s in cost_splits):
                    pct_total = sum((Decimal(str(s.get("percentage") or "0.00")) for s in cost_splits), Decimal("0.00"))
                    if pct_total != Decimal("100.00"):
                        errors.append(
                            f"Line #{idx} ({acc.code}) percentage allocation total ({pct_total}%) must equal 100.00%."
                        )
            elif (
                voucher_type_config
                and voucher_type_config.cost_centre_required
                and acc.account_type in (Account.AccountType.EXPENSE, Account.AccountType.INCOME)
                and not line.get("cost_center")
                and not line.get("project")
            ):
                errors.append(
                    f"Line #{idx} ({acc.code}) requires a Cost Centre or Project per Voucher Type configuration."
                )
            adv_ref = line.get("advance_record")
            if adv_ref:
                if isinstance(adv_ref, AdvanceRecord):
                    adv_obj = adv_ref
                else:
                    adv_obj = AdvanceRecord.objects.filter(company=company, id=adv_ref).first()
                if not adv_obj:
                    errors.append(f"Line #{idx}: Referenced advance record not found.")
                elif adv_obj.status in (AdvanceRecord.Status.SETTLED, AdvanceRecord.Status.CANCELLED) or adv_obj.remaining_amount <= 0:
                    errors.append(f"Line #{idx}: Advance {adv_obj.advance_no} is already closed or fully settled.")
                elif amt > adv_obj.remaining_amount:
                    errors.append(f"Line #{idx}: Adjustment {amt} exceeds remaining advance ({adv_obj.remaining_amount}) on {adv_obj.advance_no}.")
                else:
                    advance_impacts.append(
                        {
                            "advance_no": adv_obj.advance_no,
                            "party_name": adv_obj.party.name,
                            "original_amount": str(adv_obj.original_amount),
                            "before_remaining": str(adv_obj.remaining_amount),
                            "adjusted_amount": str(amt),
                            "after_remaining": str(adv_obj.remaining_amount - amt),
                        }
                    )

            pr_ref = line.get("payroll_liability")
            if pr_ref:
                pr_obj = pr_ref if isinstance(pr_ref, PayrollLiability) else PayrollLiability.objects.filter(company=company, id=pr_ref).first()
                if not pr_obj:
                    errors.append(f"Line #{idx}: Referenced payroll liability not found.")
                elif amt > pr_obj.outstanding_amount:
                    errors.append(f"Line #{idx}: Amount {amt} exceeds unpaid payroll ({pr_obj.outstanding_amount}) on {pr_obj.payroll_ref}.")
                else:
                    payroll_impacts.append(
                        {
                            "payroll_ref": pr_obj.payroll_ref,
                            "employee_name": pr_obj.employee.full_name,
                            "before_unpaid": str(pr_obj.outstanding_amount),
                            "settled_amount": str(amt),
                            "after_unpaid": str(pr_obj.outstanding_amount - amt),
                        }
                    )

            loan_ref = line.get("staff_loan")
            if loan_ref:
                loan_obj = loan_ref if isinstance(loan_ref, StaffLoan) else StaffLoan.objects.filter(company=company, id=loan_ref).first()
                if not loan_obj:
                    errors.append(f"Line #{idx}: Referenced staff loan not found.")
                elif amt > loan_obj.remaining_principal:
                    errors.append(f"Line #{idx}: Repayment {amt} exceeds remaining loan principal ({loan_obj.remaining_principal}) on {loan_obj.loan_no}.")

            if line_party and str(line_party.id) not in party_impacts:
                p_agg = PartyLedgerEntry.objects.filter(company=company, party=line_party).aggregate(dd=Sum("debit"), cc=Sum("credit"))
                p_before = (line_party.opening_debit - line_party.opening_credit) + (p_agg["dd"] or Decimal("0.00")) - (p_agg["cc"] or Decimal("0.00"))
                party_impacts[str(line_party.id)] = {
                    "party_id": str(line_party.id),
                    "party_name": line_party.name,
                    "party_type": line_party.party_type,
                    "before_balance": str(p_before),
                    "delta": Decimal("0.00"),
                }
            if line_party:
                party_impacts[str(line_party.id)]["delta"] += (d - c)

            total_debit += d
            total_credit += c
            curr_bal = _current_account_balance(company, acc)
            proj_bal = curr_bal + d - c

            if acc.control_role in (Account.ControlRole.CASH, Account.ControlRole.BANK):
                cb_key = str(acc.id)
                if cb_key not in cash_bank_impacts:
                    cash_bank_impacts[cb_key] = {
                        "account_code": acc.code,
                        "account_name": acc.name,
                        "role": acc.control_role,
                        "before_balance": str(curr_bal),
                        "change": Decimal("0.00"),
                    }
                cash_bank_impacts[cb_key]["change"] += (d - c)

            if line.get("project") or line.get("cost_center") or line.get("cost_code"):
                p_obj = line.get("project")
                cc_obj = line.get("cost_center")
                p_label = p_obj.code if hasattr(p_obj, "code") else str(p_obj or "HO")
                cc_label = cc_obj.code if hasattr(cc_obj, "code") else str(cc_obj or "")
                pc_key = f"{p_label}:{cc_label}"
                if pc_key not in project_cost_impacts:
                    project_cost_impacts[pc_key] = {
                        "project_code": p_label,
                        "cost_center_code": cc_label,
                        "debit": Decimal("0.00"),
                        "credit": Decimal("0.00"),
                    }
                project_cost_impacts[pc_key]["debit"] += d
                project_cost_impacts[pc_key]["credit"] += c

            # Warn when projected balance flips opposite of normal balance
            if acc.normal_balance == "DEBIT" and proj_bal < 0:
                warnings.append(f"Account '{acc.code} — {acc.name}' is Debit-normal; projected balance ({proj_bal}) goes into Credit.")
            elif acc.normal_balance == "CREDIT" and proj_bal > 0:
                warnings.append(f"Account '{acc.code} — {acc.name}' is Credit-normal; projected balance ({proj_bal}) goes into Debit.")

            if acc.control_role in (Account.ControlRole.INPUT_VAT, Account.ControlRole.OUTPUT_VAT):
                tax_summary["vat"] += (d - c)
            if acc.control_role in (Account.ControlRole.TDS_PAYABLE, Account.ControlRole.TDS_RECEIVABLE):
                tax_summary["tds"] += (c - d)
            if acc.control_role == Account.ControlRole.RETENTION_RECEIVABLE:
                retention_summary["receivable"] += (d - c)
            if acc.control_role == Account.ControlRole.RETENTION_PAYABLE:
                retention_summary["payable"] += (c - d)
            if acc.control_role == Account.ControlRole.INVENTORY:
                inventory_impact += (d - c)
            if acc.control_role == Account.ControlRole.PROJECT_WIP:
                wip_impact += (d - c)
            if acc.control_role == Account.ControlRole.SUNDRY_DEBTORS:
                rate_limit_check += (d - c)

            # Financial statement impact delta
            if acc.account_type in (Account.AccountType.ASSET, Account.AccountType.EXPENSE):
                statement_delta[acc.account_type] += (d - c)
            else:
                statement_delta[acc.account_type] += (c - d)

            # Human-readable accounting explanation
            side = "DEBIT" if d > 0 else "CREDIT"
            increases = acc.normal_balance == side
            verb = "increases" if increases else "decreases"
            explanation = f"{acc.effective_class.replace('_', ' ').title()} ({acc.normal_balance} normal) {verb} by {d if d > 0 else c}."
            if acc.control_role == Account.ControlRole.INVENTORY:
                explanation += f" ({policy.inventory_method} inventory control)"
            elif acc.control_role == Account.ControlRole.CUSTOMER_ADVANCE:
                explanation += " Treated as contract liability until revenue recognition."

            journal_preview.append(
                {
                    "line_no": idx,
                    "account_id": str(acc.id),
                    "account_code": acc.code,
                    "account_name": acc.name,
                    "account_group": f"{acc.parent.code} — {acc.parent.name}" if acc.parent else acc.account_type,
                    "account_class": acc.effective_class,
                    "normal_balance": acc.normal_balance,
                    "control_role": acc.control_role,
                    "party_name": line_party.name if line_party else "",
                    "debit": str(d),
                    "credit": str(c),
                    "current_balance": str(curr_bal),
                    "projected_balance": str(proj_bal),
                    "explanation": explanation,
                }
            )

        if total_debit != total_credit:
            errors.append(f"Unbalanced voucher: Total Debit ({total_debit}) != Total Credit ({total_credit}).")
        elif total_debit <= 0:
            errors.append("Voucher total must exceed zero.")

        if party and party.credit_limit > 0 and rate_limit_check > 0:
            agg_p = PartyLedgerEntry.objects.filter(company=company, party=party).aggregate(d=Sum("debit"), c=Sum("credit"))
            curr_p = (party.opening_debit - party.opening_credit) + (agg_p["d"] or Decimal("0.00")) - (agg_p["c"] or Decimal("0.00"))
            if curr_p + rate_limit_check > party.credit_limit:
                warnings.append(f"Debtor exposure ({curr_p + rate_limit_check}) exceeds configured credit limit ({party.credit_limit}).")

        bs_str = ""
        try:
            bs_str = ad_to_bs(voucher_date).isoformat()
        except Exception:
            bs_str = ""

        inv_mvmt_preview = [
            {
                "item_id": str(row.get("item_id") or getattr(row.get("item"), "id", "") or ""),
                "warehouse_id": str(row.get("warehouse_id") or getattr(row.get("warehouse"), "id", "") or ""),
                "quantity": str(row.get("quantity") or "0.000"),
                "rate": str(row.get("rate") or "0.00"),
                "direction": "OUT" if voucher_type in ("SALES", "DELIVERY_NOTE", "REJECTIONS_OUT", "MATERIAL_ISSUE", "MATERIAL_CONSUMPTION", "MATERIAL_OUT") else "IN",
            }
            for row in (inventory_items or [])
        ]

        party_list = [
            {
                "party_id": v["party_id"],
                "party_name": v["party_name"],
                "party_type": v["party_type"],
                "before_balance": v["before_balance"],
                "after_balance": str(Decimal(v["before_balance"]) + v["delta"]),
            }
            for v in party_impacts.values()
        ]
        cash_bank_list = [
            {
                **v,
                "change": str(v["change"]),
                "after_balance": str(Decimal(v["before_balance"]) + v["change"]),
            }
            for v in cash_bank_impacts.values()
        ]
        project_cost_list = [
            {
                **v,
                "debit": str(v["debit"]),
                "credit": str(v["credit"]),
                "net": str(v["debit"] - v["credit"]),
            }
            for v in project_cost_impacts.values()
        ]

        return {
            "is_balanced": total_debit == total_credit and total_debit > 0,
            "is_valid": len(errors) == 0,
            "validation_errors": errors,
            "warnings": warnings,
            "voucher_type": voucher_type,
            "bs_date": bs_str,
            "total_debit": str(total_debit),
            "total_credit": str(total_credit),
            "difference": str(total_debit - total_credit),
            "policy_applied": {
                "inventory_method": policy.inventory_method,
                "revenue_recognition": policy.revenue_recognition,
                "enforce_control_subledgers": policy.enforce_control_subledgers,
            },
            "journal_preview": journal_preview,
            "tax_tds_impact": {k: str(v) for k, v in tax_summary.items()},
            "retention_impact": {k: str(v) for k, v in retention_summary.items()},
            "inventory_impact": str(inventory_impact),
            "inventory_movements": inv_mvmt_preview,
            "cash_bank_impact": cash_bank_list,
            "project_cost_impact": project_cost_list,
            "invoice_allocations": list(bill_wise_allocations or []),
            "project_wip_impact": str(wip_impact),
            "statement_impact": {k: str(v) for k, v in statement_delta.items()},
            "advance_impacts": advance_impacts,
            "payroll_impacts": payroll_impacts,
            "party_impacts": party_list,
            "resulting_balances": {
                "cash_bank": cash_bank_list,
                "parties": party_list,
                "advances": advance_impacts,
                "payroll": payroll_impacts,
            },
        }

