from datetime import date
from decimal import Decimal
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db.models import Q, Sum
from django.utils import timezone

from apps.accounting.models import Account, LedgerEntry, Voucher
from apps.accounting.services import LedgerService, ReportingService
from apps.audit.models import AuditEvent
from apps.banking.models import BankAccount, BankReconciliationSession, CashAccount, ChequeLeaf
from apps.banking.services import BankingService
from apps.document_engine.models import DocumentRecord, DocumentType
from apps.loans.models import BankFacility, BankGuarantee, LoanScheduleInstallment
from apps.loans.services import LoanService
from apps.projects.models import CostCode, Project


DOCUMENT_TYPE_CATALOG = [
    # A. Accounting & Finance (20)
    ("PAYMENT_VOUCHER", "Payment Voucher", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "PV", False, False),
    ("RECEIPT_VOUCHER", "Receipt Voucher", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "RV", False, False),
    ("JOURNAL_VOUCHER", "Journal Voucher", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "JV", False, False),
    ("CONTRA_VOUCHER", "Contra Voucher", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "CV", False, False),
    ("SALES_INVOICE", "Sales Invoice", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "INV", False, True),
    ("PURCHASE_INVOICE", "Purchase Invoice", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "PINV", False, False),
    ("TAX_INVOICE", "Tax Invoice", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "TINV", False, True),
    ("PROFORMA_INVOICE", "Proforma Invoice", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "PI", False, False),
    ("DEBIT_NOTE", "Debit Note", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "DN", False, False),
    ("CREDIT_NOTE", "Credit Note", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "CN", False, False),
    ("GENERAL_LEDGER", "General Ledger", "ACCOUNTING", "ACCOUNTING", "accounting.Account", "GL", False, False),
    ("TRIAL_BALANCE", "Trial Balance", "ACCOUNTING", "REPORTS", "accounting.LedgerEntry", "TB", False, False),
    ("CASH_BOOK", "Cash Book", "ACCOUNTING", "TREASURY", "banking.CashAccount", "CB", False, False),
    ("BANK_BOOK", "Bank Book", "ACCOUNTING", "TREASURY", "banking.BankAccount", "BB", False, False),
    ("BALANCE_SHEET", "Balance Sheet", "ACCOUNTING", "REPORTS", "accounting.LedgerEntry", "BS", False, False),
    ("PROFIT_LOSS", "Profit & Loss Statement", "ACCOUNTING", "REPORTS", "accounting.LedgerEntry", "PL", False, False),
    ("CASH_FLOW_STATEMENT", "Cash Flow Statement", "ACCOUNTING", "REPORTS", "accounting.LedgerEntry", "CF", False, False),
    ("AP_AR_STATEMENT", "AP / AR Aging Statement", "ACCOUNTING", "REPORTS", "accounting.LedgerEntry", "APAR", False, False),
    ("BANK_RECONCILIATION", "Bank Reconciliation Statement", "ACCOUNTING", "TREASURY", "banking.BankReconciliationSession", "BRS", False, False),
    ("LOAN_STATEMENT", "Loan Facility Statement", "ACCOUNTING", "TREASURY", "loans.BankFacility", "LS", False, False),

    # B. Construction & Job Work (19 + Project Financial Workbook)
    ("CONSTRUCTION_WORK_ORDER", "Construction Work Order", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "CWO", False, False),
    ("JOB_WORK_ORDER", "Job Work Order", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "JWO", False, False),
    ("JOB_WORK_SHEET", "Job Work Sheet", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "JWS", False, False),
    ("JOB_COST_SHEET", "Job Cost Sheet", "CONSTRUCTION", "PROJECTS", "projects.Project", "JCS", False, False),
    ("BOQ_STATEMENT", "Bill of Quantities (BOQ) Statement", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "BOQ", False, False),
    ("MEASUREMENT_BOOK", "Measurement Book (MB)", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "MB", False, False),
    ("RA_BILL", "Running Account (RA) Bill", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "RA", False, False),
    ("PROJECT_PROGRESS_CERT", "Project Progress Certificate", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "PPC", False, False),
    ("WORK_COMPLETION_CERT", "Work Completion Certificate", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "WCC", False, False),
    ("SUBCONTRACTOR_WORK_ORDER", "Subcontractor Work Order", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "SWO", False, False),
    ("CONTRACTOR_PAYMENT_CERT", "Contractor Payment Certificate", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "CPC", False, False),
    ("SITE_EXPENSE_STATEMENT", "Site Expense Statement", "CONSTRUCTION", "PROJECTS", "projects.Project", "SES", False, False),
    ("LABOR_COST_SHEET", "Labor Cost Sheet", "CONSTRUCTION", "PROJECTS", "projects.Project", "LCS", False, False),
    ("MATERIAL_CONSUMPTION", "Material Consumption Statement", "CONSTRUCTION", "PROJECTS", "projects.Project", "MCS", False, False),
    ("EQUIPMENT_UTILIZATION", "Equipment Utilization Report", "CONSTRUCTION", "PROJECTS", "projects.Project", "EUR", False, False),
    ("WORK_VARIATION_ORDER", "Work Variation Order", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "VO", False, False),
    ("PROJECT_COST_SUMMARY", "Project Cost Summary", "CONSTRUCTION", "PROJECTS", "projects.Project", "PCS", False, False),
    ("PROJECT_BUDGET_VS_ACTUAL", "Project Budget-vs-Actual Report", "CONSTRUCTION", "PROJECTS", "projects.Project", "BVA", False, False),
    ("SITE_MATERIAL_REQUISITION", "Site Material Requisition", "CONSTRUCTION", "PROJECTS", "document_engine.DocumentRecord", "SMR", False, False),
    ("PROJECT_FINANCIAL_REPORT", "Project Financial Workbook", "CONSTRUCTION", "PROJECTS", "projects.Project", "PFR", False, False),

    # C. Delivery, Inventory & Dispatch (11)
    ("DELIVERY_CHALLAN", "Delivery Challan", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "DC", False, True),
    ("GOODS_DELIVERY_NOTE", "Goods Delivery Note", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "GDN", False, True),
    ("GOODS_RECEIPT_NOTE", "Goods Receipt Note (GRN)", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "GRN", False, False),
    ("MATERIAL_ISSUE_NOTE", "Material Issue Note", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "MIN", False, False),
    ("MATERIAL_RETURN_NOTE", "Material Return Note", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "MRN", False, False),
    ("STOCK_TRANSFER_NOTE", "Stock Transfer Note", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "STN", False, False),
    ("GATE_PASS", "Authorized Gate Pass", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "GP", False, True),
    ("DISPATCH_NOTE", "Dispatch Note", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "DISP", False, False),
    ("RETURN_DELIVERY_NOTE", "Return Delivery Note", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "RDN", False, False),
    ("PROOF_OF_DELIVERY", "Proof of Delivery (POD)", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "POD", False, False),
    ("MATERIAL_RECONCILIATION", "Material Issued-vs-Received Reconciliation", "DELIVERY", "OPERATIONS", "document_engine.DocumentRecord", "MREC", False, False),

    # D. Additional Business, Banking & HR (18)
    ("PURCHASE_ORDER", "Purchase Order", "BUSINESS_HR", "OPERATIONS", "document_engine.DocumentRecord", "PO", False, False),
    ("PURCHASE_REQUISITION", "Purchase Requisition", "BUSINESS_HR", "OPERATIONS", "document_engine.DocumentRecord", "PR", False, False),
    ("SALES_ORDER", "Sales Order", "BUSINESS_HR", "OPERATIONS", "document_engine.DocumentRecord", "SO", False, False),
    ("SUPPLIER_STATEMENT", "Supplier Statement", "BUSINESS_HR", "OPERATIONS", "accounting.Party", "SUP", False, False),
    ("CUSTOMER_STATEMENT", "Customer Statement", "BUSINESS_HR", "OPERATIONS", "accounting.Party", "CUS", False, False),
    ("PARTY_CONFIRMATION", "Party Balance Confirmation", "BUSINESS_HR", "ACCOUNTING", "party_hub.PartyStatement", "PCONF", False, False),
    ("DEBTORS_AGING", "Debtors Aging Report (AR)", "ACCOUNTING", "REPORTS", "party_hub.OpenItem", "ARAG", False, False),
    ("CREDITORS_AGING", "Creditors Aging Report (AP)", "ACCOUNTING", "REPORTS", "party_hub.OpenItem", "APAG", False, False),
    ("RECEIPT_ADVICE", "Customer Receipt & Allocation Advice", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "RADV", False, False),
    ("PAYMENT_ADVICE", "Supplier Payment & Allocation Advice", "ACCOUNTING", "ACCOUNTING", "accounting.Voucher", "PADV", False, False),
    ("EMPLOYEE_PAYSLIP", "Employee Payslip", "BUSINESS_HR", "OPERATIONS", "document_engine.DocumentRecord", "PAY", True, False),
    ("ATTENDANCE_REGISTER", "Attendance Register", "BUSINESS_HR", "OPERATIONS", "document_engine.DocumentRecord", "ATT", True, False),
    ("TIMESHEET", "Site & Employee Timesheet", "BUSINESS_HR", "OPERATIONS", "document_engine.DocumentRecord", "TS", True, False),
    ("PAYROLL_REGISTER", "Payroll Register", "BUSINESS_HR", "OPERATIONS", "document_engine.DocumentRecord", "PRG", True, False),
    ("BANK_GUARANTEE", "Bank Guarantee Certificate", "BUSINESS_HR", "TREASURY", "loans.BankGuarantee", "BG", False, False),
    ("LOAN_REPAYMENT_SCHEDULE", "Loan Repayment Schedule", "BUSINESS_HR", "TREASURY", "loans.BankFacility", "LRS", False, False),
    ("CHEQUE_REGISTER", "Cheque Register", "BUSINESS_HR", "TREASURY", "banking.ChequeLeaf", "CHQ", False, False),
    ("PROJECT_ADVANCE_SETTLEMENT", "Project Advance Settlement", "BUSINESS_HR", "PROJECTS", "document_engine.DocumentRecord", "PAS", False, False),
    ("EXPENSE_REIMBURSEMENT", "Expense Reimbursement", "BUSINESS_HR", "ACCOUNTING", "document_engine.DocumentRecord", "EXP", False, False),
    ("INTERNAL_MEMO", "Internal Office Memo", "BUSINESS_HR", "GOVERNANCE", "document_engine.DocumentRecord", "MEMO", False, False),
    ("APPROVAL_NOTE", "Management Approval Note", "BUSINESS_HR", "GOVERNANCE", "document_engine.DocumentRecord", "APP", False, False),
    ("MEETING_REPORT", "Project & Board Meeting Report", "BUSINESS_HR", "GOVERNANCE", "document_engine.DocumentRecord", "MTG", False, False),
    ("AUDIT_REPORT", "System & Financial Audit Report", "BUSINESS_HR", "GOVERNANCE", "audit.AuditEvent", "AUD", True, False),
]


def ensure_default_document_types() -> None:
    """Idempotently populate the central document_types catalog."""
    for code, name, cat, mod, src_model, prefix, sensitive, thermal in DOCUMENT_TYPE_CATALOG:
        DocumentType.objects.get_or_create(
            code=code,
            defaults={
                "name": name,
                "category": cat,
                "module_code": mod,
                "source_model": src_model,
                "default_prefix": prefix,
                "is_sensitive": sensitive,
                "supports_thermal": thermal,
            },
        )


VOUCHER_DOC_TYPE_MAP = {
    "PAYMENT_VOUCHER": "PAYMENT",
    "RECEIPT_VOUCHER": "RECEIPT",
    "JOURNAL_VOUCHER": "JOURNAL",
    "CONTRA_VOUCHER": "CONTRA",
    "SALES_INVOICE": "SALES",
    "PURCHASE_INVOICE": "PURCHASE",
    "TAX_INVOICE": "SALES",
    "PROFORMA_INVOICE": "SALES",
    "DEBIT_NOTE": "DEBIT_NOTE",
    "CREDIT_NOTE": "CREDIT_NOTE",
    "MATERIAL_PURCHASE": "MATERIAL_PURCHASE",
    "SITE_PURCHASE": "SITE_PURCHASE",
    "DIRECT_EXPENSE": "DIRECT_EXPENSE",
    "INDIRECT_EXPENSE": "INDIRECT_EXPENSE",
    "LABOR_PAYMENT": "LABOR_PAYMENT",
    "SUBCONTRACTOR_BILL": "SUBCONTRACTOR_BILL",
    "CLIENT_RA_BILL": "CLIENT_RA_BILL",
    "MOBILIZATION_ADVANCE": "MOBILIZATION_ADVANCE",
    "MATERIAL_CONSUMPTION": "MATERIAL_CONSUMPTION",
    "EQUIPMENT_HIRE": "EQUIPMENT_HIRE",
    "RA_BILL": "CLIENT_RA_BILL",
}


def build_sample_payload(company, doc_type: DocumentType) -> dict:
    """Safe preview fixture when designing templates in Document Studio."""
    today = timezone.localdate()
    return {
        "document_type": doc_type.code,
        "title": doc_type.name,
        "title_ne": "नमुना कागजात",
        "source_model": doc_type.source_model or "document_engine.Sample",
        "source_id": "sample",
        "document_number": f"{doc_type.default_prefix}-2083-00001",
        "issue_date": today,
        "status": "APPROVED",
        "currency": company.base_currency or "NPR",
        "party": {
            "name": "Panchakanya Steel & Builders Pvt. Ltd.",
            "pan_vat": "601234567",
            "address": "Lalitpur-3, Pulchowk, Nepal",
            "contact": "+977-01-5550199",
        },
        "project": {"code": "PRJ-01", "name": "Kathmandu Ring Road Flyover", "site": "Site A · Kalanki"},
        "metadata": [
            {"label": "Reference No", "value": "REF-2083-88"},
            {"label": "Fiscal Year", "value": "2083/84"},
            {"label": "Prepared By", "value": "Chief Accountant"},
            {"label": "Approved By", "value": "Finance Director"},
        ],
        "columns": [
            {"key": "sn", "label": "#", "type": "int", "align": "center"},
            {"key": "description", "label": "Description / Account", "type": "text", "align": "left"},
            {"key": "qty", "label": "Qty", "type": "number", "align": "right"},
            {"key": "rate", "label": "Rate", "type": "money", "align": "right"},
            {"key": "amount", "label": "Amount", "type": "money", "align": "right"},
        ],
        "rows": [
            {"sn": 1, "description": "TMT Rebar 16mm Grade Fe-500D", "qty": 10, "rate": Decimal("5000.00"), "amount": Decimal("50000.00")},
            {"sn": 2, "description": "Site Haulage & Crane Unloading", "qty": 1, "rate": Decimal("2000.00"), "amount": Decimal("2000.00")},
        ],
        "totals": {
            "subtotal": Decimal("52000.00"),
            "tax_label": "VAT 13%",
            "tax_amount": Decimal("6760.00"),
            "grand_total": Decimal("58760.00"),
        },
        "narration": "Sample preview layout for enterprise template verification.",
        "terms": [
            "1. Computer generated enterprise ERP document.",
            "2. Subject to company authorization and Nepal VAT/PAN rules where applicable.",
        ],
        "worksheets": [],
    }


def _extract_voucher_payload(company, doc_type: DocumentType, source_id: str) -> dict:
    voucher = (
        Voucher.objects.select_related("branch", "project", "site", "created_by", "approved_by", "posted_by", "fiscal_year")
        .prefetch_related("lines__account", "lines__cost_code")
        .filter(company=company, id=source_id)
        .first()
    )
    if not voucher:
        raise ObjectDoesNotExist(f"Voucher {source_id} not found in active company.")

    rows = []
    subtotal = Decimal("0.00")
    tax_amt = Decimal("0.00")
    for line in voucher.lines.all():
        amt = line.debit if line.debit > 0 else line.credit
        side = "Dr" if line.debit > 0 else "Cr"
        if "TAX" in line.account.name.upper() or "VAT" in line.account.name.upper():
            tax_amt += amt
        else:
            subtotal += line.debit
        rows.append(
            {
                "sn": line.line_no,
                "description": f"{line.account.code} — {line.account.name}" + (f" ({line.description})" if line.description else ""),
                "qty": side,
                "rate": line.debit,
                "amount": line.credit if line.credit > 0 else line.debit,
                "cost_code": line.cost_code.code if line.cost_code else "",
            }
        )

    total_voucher = sum((l.debit for l in voucher.lines.all()), Decimal("0.00"))
    net_sub = (total_voucher - tax_amt) if tax_amt > 0 and total_voucher >= tax_amt else total_voucher
    return {
        "document_type": doc_type.code,
        "title": doc_type.name,
        "title_ne": "लेखा भौचर / बीजक",
        "source_model": "accounting.Voucher",
        "source_id": str(voucher.id),
        "document_number": voucher.voucher_no or f"DRAFT-{str(voucher.id)[:8].upper()}",
        "issue_date": voucher.voucher_date,
        "status": voucher.status,
        "currency": voucher.currency,
        "branch": voucher.branch,
        "project_obj": voucher.project,
        "site_obj": voucher.site,
        "party": {
            "name": voucher.party_name or company.name,
            "pan_vat": voucher.party_pan or company.pan_vat_no,
            "address": voucher.site.location if voucher.site else (voucher.project.location if voucher.project else getattr(company, "address", "")),
            "contact": "",
        },
        "project": {
            "code": voucher.project.code if voucher.project else "-",
            "name": voucher.project.name if voucher.project else "-",
            "site": voucher.site.name if voucher.site else "-",
        },
        "metadata": [
            {"label": "Voucher Type", "value": voucher.get_voucher_type_display()},
            {"label": "Fiscal Year", "value": voucher.fiscal_year.name if voucher.fiscal_year else ""},
            {"label": "Reference No", "value": voucher.reference_no or "-"},
            {"label": "Prepared By", "value": voucher.created_by.get_full_name() or voucher.created_by.username},
            {"label": "Approved By", "value": (voucher.approved_by.get_full_name() or voucher.approved_by.username) if voucher.approved_by else "Pending"},
            {"label": "Posted By", "value": (voucher.posted_by.get_full_name() or voucher.posted_by.username) if voucher.posted_by else "Not Posted"},
        ],
        "columns": [
            {"key": "sn", "label": "#", "type": "int", "align": "center"},
            {"key": "description", "label": "Particulars / Ledger Account", "type": "text", "align": "left"},
            {"key": "qty", "label": "Dr/Cr", "type": "text", "align": "center"},
            {"key": "rate", "label": "Debit", "type": "money", "align": "right"},
            {"key": "amount", "label": "Credit / Amount", "type": "money", "align": "right"},
        ],
        "rows": rows,
        "totals": {
            "subtotal": net_sub.quantize(Decimal("0.01")),
            "tax_label": "VAT / Tax",
            "tax_amount": tax_amt.quantize(Decimal("0.01")),
            "grand_total": total_voucher.quantize(Decimal("0.01")),
        },
        "narration": voucher.narration,
        "terms": ["Prepared and verified inside Maya OS double-entry accounting ledger."],
        "worksheets": [],
    }


def _extract_project_financial_workbook(company, project: Project | None) -> dict:
    """Build multi-sheet Project Financial Report.xlsx covering all 8 enterprise tabs."""
    today = timezone.localdate()
    proj_filter = {"project": project} if project else {}
    projects = [project] if project else list(Project.objects.filter(company=company).order_by("code"))

    summary_rows = []
    for p in projects:
        exp_agg = LedgerEntry.objects.filter(
            company=company, project=p, account__account_type=Account.AccountType.EXPENSE
        ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        rev_agg = LedgerEntry.objects.filter(
            company=company, project=p, account__account_type=Account.AccountType.INCOME
        ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        actual_cost = (exp_agg["d"] or Decimal("0.00")) - (exp_agg["c"] or Decimal("0.00"))
        billed_rev = (rev_agg["c"] or Decimal("0.00")) - (rev_agg["d"] or Decimal("0.00"))
        variance = p.budget_amount - actual_cost
        summary_rows.append(
            {
                "project_code": p.code,
                "project_name": p.name,
                "contract_amount": float(p.contract_amount),
                "budget_amount": float(p.budget_amount),
                "actual_cost": float(actual_cost),
                "variance": float(variance),
                "billed_revenue": float(billed_rev),
                "status": p.status,
            }
        )

    ledger_rows = []
    for e in (
        LedgerEntry.objects.select_related("account", "project", "cost_code", "voucher")
        .filter(company=company, **proj_filter)
        .order_by("posting_date", "id")[:500]
    ):
        ledger_rows.append(
            {
                "date": e.posting_date.isoformat(),
                "voucher_no": e.voucher.voucher_no if e.voucher else "",
                "project": e.project.code if e.project else "-",
                "account": f"{e.account.code} - {e.account.name}",
                "cost_code": e.cost_code.category if e.cost_code else "GENERAL",
                "debit": float(e.base_debit),
                "credit": float(e.base_credit),
                "narration": e.narration,
            }
        )

    def category_rows(cat: str):
        qs = (
            LedgerEntry.objects.select_related("account", "cost_code", "voucher", "project")
            .filter(company=company, cost_code__category=cat, **proj_filter)
            .order_by("posting_date")[:300]
        )
        return [
            {
                "date": e.posting_date.isoformat(),
                "voucher_no": e.voucher.voucher_no if e.voucher else "",
                "project": e.project.code if e.project else "-",
                "cost_code": f"{e.cost_code.code} - {e.cost_code.name}",
                "debit": float(e.base_debit),
                "credit": float(e.base_credit),
                "narration": e.narration,
            }
            for e in qs
        ]

    bva_rows = []
    for cc in CostCode.objects.filter(company=company):
        agg = LedgerEntry.objects.filter(company=company, cost_code=cc, **proj_filter).aggregate(
            d=Sum("base_debit"), c=Sum("base_credit")
        )
        spent = (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
        bva_rows.append(
            {
                "cost_code": cc.code,
                "category": cc.category,
                "name": cc.name,
                "actual_spent": float(spent),
            }
        )

    inv_qs = Voucher.objects.filter(
        company=company,
        voucher_type__in=[Voucher.VoucherType.SALES, Voucher.VoucherType.PURCHASE],
        **({"project": project} if project else {}),
    ).prefetch_related("lines")[:300]
    invoice_rows = [
        {
            "date": v.voucher_date.isoformat(),
            "voucher_no": v.voucher_no or "DRAFT",
            "type": v.voucher_type,
            "party": v.party_name,
            "status": v.status,
            "amount": float(sum((l.debit for l in v.lines.all()), Decimal("0.00"))),
        }
        for v in inv_qs
    ]

    tb = ReportingService.get_trial_balance(company=company, project_id=str(project.id) if project else None)
    outstanding_rows = [
        {
            "account_code": r["code"],
            "account_name": r["name"],
            "type": r["account_type"],
            "debit_bal": float(r["closing_debit"]),
            "credit_bal": float(r["closing_credit"]),
        }
        for r in tb["rows"]
        if r["code"].startswith(("11", "20"))
    ]

    worksheets = [
        {
            "name": "Summary",
            "title": "Executive Project Financial Overview",
            "columns": [
                {"key": "project_code", "label": "Project", "type": "text"},
                {"key": "project_name", "label": "Name", "type": "text"},
                {"key": "contract_amount", "label": "Contract Value", "type": "money"},
                {"key": "budget_amount", "label": "Approved Budget", "type": "money"},
                {"key": "actual_cost", "label": "Actual Cost", "type": "money"},
                {"key": "variance", "label": "Budget Variance", "type": "money"},
                {"key": "billed_revenue", "label": "Billed Revenue", "type": "money"},
                {"key": "status", "label": "Status", "type": "text"},
            ],
            "rows": summary_rows,
            "chart": {"title": "Budget vs Actual Cost", "category_col": 1, "value_cols": [3, 4]},
            "sum_columns": [2, 3, 4, 5, 6],
        },
        {
            "name": "Project Ledger",
            "title": "Project Ledger Transactions",
            "columns": [
                {"key": "date", "label": "Date", "type": "date"},
                {"key": "voucher_no", "label": "Voucher No", "type": "text"},
                {"key": "project", "label": "Project", "type": "text"},
                {"key": "account", "label": "Account", "type": "text"},
                {"key": "cost_code", "label": "Category", "type": "text"},
                {"key": "debit", "label": "Debit", "type": "money"},
                {"key": "credit", "label": "Credit", "type": "money"},
                {"key": "narration", "label": "Narration", "type": "text"},
            ],
            "rows": ledger_rows,
            "sum_columns": [5, 6],
        },
        {
            "name": "Material Costs",
            "title": "Material Expenses",
            "columns": [
                {"key": "date", "label": "Date", "type": "date"},
                {"key": "voucher_no", "label": "Voucher No", "type": "text"},
                {"key": "project", "label": "Project", "type": "text"},
                {"key": "cost_code", "label": "Cost Code", "type": "text"},
                {"key": "debit", "label": "Debit", "type": "money"},
                {"key": "credit", "label": "Credit", "type": "money"},
                {"key": "narration", "label": "Narration", "type": "text"},
            ],
            "rows": category_rows("MATERIAL"),
            "sum_columns": [4, 5],
        },
        {
            "name": "Labor Costs",
            "title": "Employee & Labor Costs",
            "columns": [
                {"key": "date", "label": "Date", "type": "date"},
                {"key": "voucher_no", "label": "Voucher No", "type": "text"},
                {"key": "project", "label": "Project", "type": "text"},
                {"key": "cost_code", "label": "Cost Code", "type": "text"},
                {"key": "debit", "label": "Debit", "type": "money"},
                {"key": "credit", "label": "Credit", "type": "money"},
                {"key": "narration", "label": "Narration", "type": "text"},
            ],
            "rows": category_rows("LABOR"),
            "sum_columns": [4, 5],
        },
        {
            "name": "Equipment Costs",
            "title": "Equipment & Fuel Costs",
            "columns": [
                {"key": "date", "label": "Date", "type": "date"},
                {"key": "voucher_no", "label": "Voucher No", "type": "text"},
                {"key": "project", "label": "Project", "type": "text"},
                {"key": "cost_code", "label": "Cost Code", "type": "text"},
                {"key": "debit", "label": "Debit", "type": "money"},
                {"key": "credit", "label": "Credit", "type": "money"},
                {"key": "narration", "label": "Narration", "type": "text"},
            ],
            "rows": category_rows("EQUIPMENT"),
            "sum_columns": [4, 5],
        },
        {
            "name": "Budget vs Actual",
            "title": "Cost Code Variance",
            "columns": [
                {"key": "cost_code", "label": "Code", "type": "text"},
                {"key": "category", "label": "Category", "type": "text"},
                {"key": "name", "label": "Cost Head", "type": "text"},
                {"key": "actual_spent", "label": "Actual Spent", "type": "money"},
            ],
            "rows": bva_rows,
            "sum_columns": [3],
        },
        {
            "name": "Invoice Register",
            "title": "Project Sales & Purchase Invoices",
            "columns": [
                {"key": "date", "label": "Date", "type": "date"},
                {"key": "voucher_no", "label": "Voucher No", "type": "text"},
                {"key": "type", "label": "Type", "type": "text"},
                {"key": "party", "label": "Party", "type": "text"},
                {"key": "status", "label": "Status", "type": "text"},
                {"key": "amount", "label": "Amount", "type": "money"},
            ],
            "rows": invoice_rows,
            "sum_columns": [5],
        },
        {
            "name": "Outstanding",
            "title": "Payables & Receivables Summary",
            "columns": [
                {"key": "account_code", "label": "Code", "type": "text"},
                {"key": "account_name", "label": "Account", "type": "text"},
                {"key": "type", "label": "Type", "type": "text"},
                {"key": "debit_bal", "label": "Receivable (Dr)", "type": "money"},
                {"key": "credit_bal", "label": "Payable (Cr)", "type": "money"},
            ],
            "rows": outstanding_rows,
            "sum_columns": [3, 4],
        },
    ]

    total_actual = sum((Decimal(str(r["actual_cost"])) for r in summary_rows), Decimal("0.00"))
    return {
        "document_type": "PROJECT_FINANCIAL_REPORT",
        "title": "Project Financial Report",
        "title_ne": "परियोजना वित्तीय प्रतिवेदन",
        "source_model": "projects.Project",
        "source_id": str(project.id) if project else "all",
        "document_number": f"PFR-{project.code}" if project else "PFR-ALL",
        "issue_date": today,
        "status": "ISSUED",
        "currency": company.base_currency or "NPR",
        "party": {"name": company.name, "pan_vat": company.pan_vat_no, "address": getattr(company, "address", ""), "contact": ""},
        "project": {
            "code": project.code if project else "ALL",
            "name": project.name if project else "Consolidated Projects",
            "site": "-",
        },
        "metadata": [
            {"label": "Generated On", "value": today.isoformat()},
            {"label": "Projects Included", "value": str(len(projects))},
        ],
        "columns": worksheets[0]["columns"],
        "rows": summary_rows,
        "totals": {"subtotal": total_actual, "tax_label": "Budget Variance", "tax_amount": Decimal("0.00"), "grand_total": total_actual},
        "narration": "Consolidated enterprise construction financial analysis.",
        "terms": [],
        "worksheets": worksheets,
    }


def extract_document_payload(*, company, doc_type_code: str, source_id: str, filters: dict | None = None) -> dict:
    """Resolve structured, read-only business data from the authoritative module source."""
    ensure_default_document_types()
    doc_type = DocumentType.objects.filter(code=doc_type_code, is_active=True).first()
    if not doc_type:
        raise ValidationError(f"Unknown or inactive document type: {doc_type_code}")

    if source_id == "sample":
        return build_sample_payload(company, doc_type)

    filters = filters or {}
    today = timezone.localdate()

    # 1. Vouchers & Invoices (also handle direct construction/inventory operational vouchers)
    if doc_type_code in VOUCHER_DOC_TYPE_MAP or doc_type_code in (
        "CONTRACTOR_PAYMENT_CERT",
        "SITE_EXPENSE_STATEMENT",
        "PURCHASE_ORDER",
        "SALES_ORDER",
        "GOODS_RECEIPT_NOTE",
        "DELIVERY_CHALLAN",
        "MATERIAL_ISSUE_NOTE",
        "MATERIAL_RETURN_NOTE",
    ):
        if doc_type_code in VOUCHER_DOC_TYPE_MAP and doc_type_code != "RA_BILL":
            return _extract_voucher_payload(company, doc_type, source_id)
        if Voucher.objects.filter(company=company, id=source_id).exists():
            return _extract_voucher_payload(company, doc_type, source_id)

    # 2. General Ledger / Bank Book / Cash Book
    if doc_type_code in ("GENERAL_LEDGER", "BANK_BOOK", "CASH_BOOK"):
        account = None
        if doc_type_code == "BANK_BOOK":
            ba = BankAccount.objects.select_related("gl_account", "bank_branch__bank").filter(company=company, id=source_id).first()
            account = ba.gl_account if ba else Account.objects.filter(company=company, id=source_id).first()
        elif doc_type_code == "CASH_BOOK":
            ca = CashAccount.objects.select_related("gl_account").filter(company=company, id=source_id).first()
            account = ca.gl_account if ca else Account.objects.filter(company=company, id=source_id).first()
        else:
            account = Account.objects.filter(company=company, id=source_id).first()
        if not account:
            raise ObjectDoesNotExist(f"Ledger account {source_id} not found.")
        df = date.fromisoformat(filters["date_from"]) if filters.get("date_from") else None
        dt = date.fromisoformat(filters["date_to"]) if filters.get("date_to") else None
        ledger = LedgerService.get_account_ledger(company=company, account=account, date_from=df, date_to=dt)
        rows = [
            {
                "sn": idx,
                "date": e["posting_date"],
                "voucher_no": e["voucher_no"] or "",
                "description": e["narration"],
                "qty": e["bs_date"],
                "rate": Decimal(e["debit"]),
                "amount": Decimal(e["credit"]),
                "balance": f"{e['running_balance']} {e['running_side']}",
            }
            for idx, e in enumerate(ledger["entries"], start=1)
        ]
        return {
            "document_type": doc_type_code,
            "title": f"{doc_type.name} — {account.code} {account.name}",
            "title_ne": "खाता बही",
            "source_model": doc_type.source_model,
            "source_id": str(source_id),
            "document_number": f"{doc_type.default_prefix}-{account.code}",
            "issue_date": dt or today,
            "status": "ISSUED",
            "currency": company.base_currency or "NPR",
            "party": {"name": company.name, "pan_vat": company.pan_vat_no, "address": getattr(company, "address", ""), "contact": ""},
            "project": {"code": "-", "name": "General Ledger", "site": "-"},
            "metadata": [
                {"label": "Account", "value": f"{account.code} — {account.name}"},
                {"label": "Opening Balance", "value": f"{ledger['opening_balance']} {ledger['opening_side']}"},
                {"label": "Closing Balance", "value": f"{ledger['closing_balance']} {ledger['closing_side']}"},
            ],
            "columns": [
                {"key": "date", "label": "Date (AD)", "type": "date", "align": "left"},
                {"key": "qty", "label": "Date (BS)", "type": "text", "align": "left"},
                {"key": "voucher_no", "label": "Voucher No", "type": "text", "align": "left"},
                {"key": "description", "label": "Narration", "type": "text", "align": "left"},
                {"key": "rate", "label": "Debit", "type": "money", "align": "right"},
                {"key": "amount", "label": "Credit", "type": "money", "align": "right"},
                {"key": "balance", "label": "Running Balance", "type": "text", "align": "right"},
            ],
            "rows": rows,
            "totals": {
                "subtotal": Decimal(ledger["total_debit"]),
                "tax_label": "Total Credit",
                "tax_amount": Decimal(ledger["total_credit"]),
                "grand_total": Decimal(ledger["closing_balance"]),
            },
            "narration": f"Ledger statement from live posted GL entries ({len(rows)} rows).",
            "terms": [],
            "worksheets": [],
        }

    # 3. Trial Balance / P&L / Balance Sheet / Cash Flow / AP_AR
    if doc_type_code in ("TRIAL_BALANCE", "PROFIT_LOSS", "BALANCE_SHEET", "CASH_FLOW_STATEMENT", "AP_AR_STATEMENT"):
        proj_id = None if source_id in ("all", "company", "current") else source_id
        if doc_type_code == "PROFIT_LOSS":
            pl = ReportingService.get_profit_and_loss(company=company, project_id=proj_id)
            rows = [{"sn": idx + 1, "code": r["code"], "description": r["name"], "category": r["account_type"], "rate": Decimal("0.00"), "amount": Decimal(r["amount"])} for idx, r in enumerate(pl["income"] + pl["expenses"])]
            grand = Decimal(pl["net_profit"])
        elif doc_type_code == "BALANCE_SHEET":
            bs = ReportingService.get_balance_sheet(company=company)
            rows = [{"sn": idx + 1, "code": r["code"], "description": r["name"], "category": r["account_type"], "rate": Decimal("0.00"), "amount": Decimal(r["amount"])} for idx, r in enumerate(bs["assets"] + bs["liabilities"] + bs["equity"])]
            grand = Decimal(bs["total_assets"])
        else:
            tb = ReportingService.get_trial_balance(company=company, project_id=proj_id)
            rows = [
                {
                    "sn": idx + 1,
                    "code": r["code"],
                    "description": r["name"],
                    "category": r["account_type"],
                    "rate": Decimal(r["closing_debit"]),
                    "amount": Decimal(r["closing_credit"]),
                }
                for idx, r in enumerate(tb["rows"])
                if doc_type_code != "AP_AR_STATEMENT" or r["code"].startswith(("11", "20"))
            ]
            grand = Decimal(
                str(tb.get("totals", {}).get("closing_debit") or tb.get("total_closing_debit") or sum((Decimal(r["closing_debit"]) for r in tb.get("rows", [])), Decimal("0.00")))
            )
        return {
            "document_type": doc_type_code,
            "title": doc_type.name,
            "title_ne": "वित्तीय विवरण",
            "source_model": "accounting.LedgerEntry",
            "source_id": str(source_id),
            "document_number": f"{doc_type.default_prefix}-{today.strftime('%Y%m')}",
            "issue_date": today,
            "status": "ISSUED",
            "currency": company.base_currency or "NPR",
            "party": {"name": company.name, "pan_vat": company.pan_vat_no, "address": getattr(company, "address", ""), "contact": ""},
            "project": {"code": proj_id or "ALL", "name": "Financial Statement", "site": "-"},
            "metadata": [{"label": "As Of Date", "value": today.isoformat()}],
            "columns": [
                {"key": "code", "label": "Code", "type": "text", "align": "left"},
                {"key": "description", "label": "Account Head", "type": "text", "align": "left"},
                {"key": "category", "label": "Classification", "type": "text", "align": "left"},
                {"key": "rate", "label": "Debit", "type": "money", "align": "right"},
                {"key": "amount", "label": "Credit / Amount", "type": "money", "align": "right"},
            ],
            "rows": rows,
            "totals": {"subtotal": grand, "tax_label": "Balanced Check", "tax_amount": Decimal("0.00"), "grand_total": grand},
            "narration": "Authoritative financial statement extracted from posted LedgerEntry records.",
            "terms": [],
            "worksheets": [],
        }

    # 4. Bank Reconciliation
    if doc_type_code == "BANK_RECONCILIATION":
        sess = BankReconciliationSession.objects.select_related("bank_account__bank_branch__bank").filter(company=company, id=source_id).first()
        if not sess:
            raise ObjectDoesNotExist(f"Reconciliation session {source_id} not found.")
        return {
            "document_type": doc_type_code,
            "title": f"Bank Reconciliation — {sess.bank_account.account_name}",
            "title_ne": "बैंक मिलान विवरण",
            "source_model": "banking.BankReconciliationSession",
            "source_id": str(sess.id),
            "document_number": f"BRS-{sess.as_of_date.strftime('%Y%m%d')}",
            "issue_date": sess.as_of_date,
            "status": sess.status,
            "currency": sess.bank_account.currency,
            "party": {"name": sess.bank_account.bank_branch.bank.name, "pan_vat": "", "address": sess.bank_account.account_number_masked, "contact": ""},
            "project": {"code": "-", "name": sess.bank_account.account_name, "site": sess.bank_account.bank_branch.name},
            "metadata": [
                {"label": "Statement Closing", "value": str(sess.statement_closing_balance)},
                {"label": "Book Closing", "value": str(sess.book_closing_balance)},
                {"label": "Difference", "value": str(sess.difference_amount)},
            ],
            "columns": [
                {"key": "sn", "label": "#", "type": "int", "align": "center"},
                {"key": "description", "label": "Reconciliation Component", "type": "text", "align": "left"},
                {"key": "qty", "label": "Status", "type": "text", "align": "center"},
                {"key": "rate", "label": "Book Amount", "type": "money", "align": "right"},
                {"key": "amount", "label": "Statement Amount", "type": "money", "align": "right"},
            ],
            "rows": [
                {"sn": 1, "description": "Closing Balance Per Bank Book & Statement", "qty": sess.status, "rate": sess.book_closing_balance, "amount": sess.statement_closing_balance},
                {"sn": 2, "description": "Unreconciled Variance", "qty": "VARIANCE", "rate": Decimal("0.00"), "amount": sess.difference_amount},
            ],
            "totals": {"subtotal": sess.book_closing_balance, "tax_label": "Difference", "tax_amount": sess.difference_amount, "grand_total": sess.statement_closing_balance},
            "narration": sess.notes,
            "terms": [],
            "worksheets": [],
        }

    # 5. Loans & Repayment Schedules & Bank Guarantees
    if doc_type_code in ("LOAN_STATEMENT", "LOAN_REPAYMENT_SCHEDULE"):
        fac = BankFacility.objects.select_related("bank_account__bank_branch__bank", "project").filter(company=company, id=source_id).first()
        if not fac:
            raise ObjectDoesNotExist(f"Loan facility {source_id} not found.")
        rows = [
            {
                "sn": inst.installment_no,
                "date": inst.due_date.isoformat(),
                "description": f"Installment #{inst.installment_no} ({inst.status})",
                "qty": str(inst.principal_due),
                "rate": inst.interest_due,
                "amount": (inst.principal_due + inst.interest_due).quantize(Decimal("0.01")),
            }
            for inst in fac.installments.all().order_by("installment_no")
        ]
        out = LoanService.get_outstanding_principal(fac)
        return {
            "document_type": doc_type_code,
            "title": f"{doc_type.name} — {fac.facility_code}",
            "title_ne": "ऋण तथा किस्ता विवरण",
            "source_model": "loans.BankFacility",
            "source_id": str(fac.id),
            "document_number": fac.facility_code,
            "issue_date": fac.sanction_date,
            "status": fac.status,
            "currency": fac.currency,
            "party": {"name": fac.bank_account.bank_branch.bank.name, "pan_vat": "", "address": fac.bank_account.bank_branch.name, "contact": ""},
            "project": {"code": fac.project.code if fac.project else "-", "name": fac.facility_name, "site": "-"},
            "metadata": [
                {"label": "Facility Type", "value": fac.get_facility_type_display()},
                {"label": "Sanctioned Limit", "value": f"{fac.currency} {fac.sanctioned_limit:,.2f}"},
                {"label": "Outstanding Principal", "value": f"{fac.currency} {out:,.2f}"},
                {"label": "Interest Rate", "value": f"{fac.effective_interest_rate}% p.a."},
            ],
            "columns": [
                {"key": "sn", "label": "#", "type": "int", "align": "center"},
                {"key": "date", "label": "Due Date", "type": "date", "align": "left"},
                {"key": "description", "label": "Installment", "type": "text", "align": "left"},
                {"key": "qty", "label": "Principal", "type": "money", "align": "right"},
                {"key": "rate", "label": "Interest", "type": "money", "align": "right"},
                {"key": "amount", "label": "Total Due", "type": "money", "align": "right"},
            ],
            "rows": rows,
            "totals": {"subtotal": fac.sanctioned_limit, "tax_label": "Outstanding", "tax_amount": out, "grand_total": out},
            "narration": f"Sanction ref: {fac.sanction_ref or '-'}",
            "terms": [],
            "worksheets": [],
        }

    if doc_type_code == "BANK_GUARANTEE":
        bg = BankGuarantee.objects.select_related("bank_account__bank_branch__bank", "project").filter(company=company, id=source_id).first()
        if not bg:
            raise ObjectDoesNotExist(f"Bank Guarantee {source_id} not found.")
        return {
            "document_type": doc_type_code,
            "title": f"Bank Guarantee — {bg.bg_number}",
            "title_ne": "बैंक जमानत प्रमाणपत्र",
            "source_model": "loans.BankGuarantee",
            "source_id": str(bg.id),
            "document_number": bg.bg_number,
            "issue_date": bg.issue_date,
            "status": bg.status,
            "currency": bg.currency,
            "party": {"name": bg.beneficiary, "pan_vat": "", "address": bg.bank_account.bank_branch.bank.name, "contact": ""},
            "project": {"code": bg.project.code if bg.project else "-", "name": bg.project.name if bg.project else "-", "site": "-"},
            "metadata": [
                {"label": "BG Type", "value": bg.get_bg_type_display()},
                {"label": "Issue Date", "value": bg.issue_date.isoformat()},
                {"label": "Expiry Date", "value": bg.expiry_date.isoformat()},
            ],
            "columns": [
                {"key": "sn", "label": "#", "type": "int", "align": "center"},
                {"key": "description", "label": "Component", "type": "text", "align": "left"},
                {"key": "qty", "label": "Margin %", "type": "text", "align": "right"},
                {"key": "rate", "label": "Commission", "type": "money", "align": "right"},
                {"key": "amount", "label": "Guaranteed / Margin", "type": "money", "align": "right"},
            ],
            "rows": [
                {"sn": 1, "description": f"Guarantee Liability ({bg.beneficiary})", "qty": f"{bg.margin_percent}%", "rate": bg.commission_amount, "amount": bg.amount},
                {"sn": 2, "description": "Cash Margin Locked", "qty": "-", "rate": Decimal("0.00"), "amount": bg.margin_amount},
            ],
            "totals": {"subtotal": bg.amount, "tax_label": "Cash Margin", "tax_amount": bg.margin_amount, "grand_total": bg.amount},
            "narration": bg.notes,
            "terms": [],
            "worksheets": [],
        }

    # 6. Cheque Register (all 14 Enterprise Cheque Reports & A4 Printing)
    if doc_type_code == "CHEQUE_REGISTER":
        f = filters or {}
        if f.get("report_type"):
            from apps.treasury.cheques.reporting.service import (
                CHEQUE_REPORT_TYPES,
                ChequeReportingService,
            )

            rpt = ChequeReportingService.generate_report(
                company=company, report_type=f["report_type"], filters=f
            )
            rpt_label = next(
                (item["label"] for item in CHEQUE_REPORT_TYPES if item["code"] == rpt["report_type"]),
                rpt["report_type"].replace("_", " ").title(),
            )
            rpt_rows = rpt["rows"][:300]
            if rpt_rows:
                keys = list(rpt_rows[0].keys())
                cols = [
                    {
                        "key": k,
                        "label": k.replace("_", " ").title(),
                        "type": "money" if "amount" in k or "charge" in k else "text",
                        "align": "right" if "amount" in k or "charge" in k else "left",
                    }
                    for k in keys
                ]
            else:
                cols = [{"key": "info", "label": "Notice", "type": "text", "align": "left"}]
                rpt_rows = [{"info": "No cheque records matched selected filters."}]
            return {
                "document_type": doc_type_code,
                "title": rpt_label,
                "title_ne": "चेक दर्ता तथा क्लियरिङ विवरण",
                "source_model": "banking.ChequeLeaf",
                "source_id": str(source_id),
                "document_number": f"CHQ-{rpt['report_type'][:8]}-{today.strftime('%Y%m')}",
                "issue_date": today,
                "status": "ISSUED",
                "currency": company.base_currency or "NPR",
                "party": {"name": company.name, "pan_vat": company.pan_vat_no, "address": getattr(company, "address", ""), "contact": ""},
                "project": {"code": "-", "name": "Enterprise Cheque Register", "site": "-"},
                "metadata": [{"label": "Report Rows", "value": str(rpt["count"])}],
                "columns": cols,
                "rows": rpt_rows,
                "totals": {"subtotal": Decimal("0.00"), "tax_label": "Rows", "tax_amount": Decimal(rpt["count"]), "grand_total": Decimal("0.00")},
                "narration": f"{rpt_label} generated via Enterprise Cheque Register & Clearing Center.",
                "terms": [],
                "worksheets": [],
            }

        leaves = ChequeLeaf.objects.select_related("bank_account", "cheque_book__bank_account").filter(company=company).exclude(status=ChequeLeaf.Status.AVAILABLE).order_by("-cheque_date", "cheque_number")[:250]
        rows = [
            {
                "sn": idx,
                "description": f"{l.cheque_number} ({l.direction}) · {l.party_name or l.drawer_name or '-'} ({l.bank_account.account_name})",
                "qty": l.status,
                "rate": l.cheque_date.isoformat() if l.cheque_date else "-",
                "amount": l.amount,
            }
            for idx, l in enumerate(leaves, start=1)
        ]
        total_chq = sum((l.amount for l in leaves), Decimal("0.00"))
        return {
            "document_type": doc_type_code,
            "title": "Enterprise Cheque Register",
            "title_ne": "चेक दर्ता किताब",
            "source_model": "banking.ChequeLeaf",
            "source_id": str(source_id),
            "document_number": f"CHQ-{today.strftime('%Y%m')}",
            "issue_date": today,
            "status": "ISSUED",
            "currency": company.base_currency or "NPR",
            "party": {"name": company.name, "pan_vat": company.pan_vat_no, "address": getattr(company, "address", ""), "contact": ""},
            "project": {"code": "-", "name": "All Bank Cheque Books", "site": "-"},
            "metadata": [{"label": "Total Cheques", "value": str(len(rows))}],
            "columns": [
                {"key": "sn", "label": "#", "type": "int", "align": "center"},
                {"key": "description", "label": "Cheque & Party / Drawer", "type": "text", "align": "left"},
                {"key": "qty", "label": "Status", "type": "text", "align": "center"},
                {"key": "rate", "label": "Cheque Date", "type": "text", "align": "center"},
                {"key": "amount", "label": "Amount", "type": "money", "align": "right"},
            ],
            "rows": rows,
            "totals": {"subtotal": total_chq, "tax_label": "Cleared/Pending", "tax_amount": Decimal("0.00"), "grand_total": total_chq},
            "narration": "Cheque leaf inventory & clearing lifecycle register.",
            "terms": [],
            "worksheets": [],
        }

    # 7. Multi-Sheet Project Workbook & Project Cost/Budget Reports
    if doc_type_code in ("PROJECT_FINANCIAL_REPORT", "PROJECT_COST_SUMMARY", "PROJECT_BUDGET_VS_ACTUAL", "JOB_COST_SHEET", "SITE_EXPENSE_STATEMENT", "LABOR_COST_SHEET", "MATERIAL_CONSUMPTION", "EQUIPMENT_UTILIZATION"):
        proj = None if source_id in ("all", "company") else Project.objects.filter(company=company, id=source_id).first()
        if source_id not in ("all", "company") and not proj:
            raise ObjectDoesNotExist(f"Project {source_id} not found.")
        wb = _extract_project_financial_workbook(company, proj)
        wb["document_type"] = doc_type_code
        wb["title"] = f"{doc_type.name}" + (f" — {proj.code}" if proj else "")
        return wb

    # 8. Audit Report
    if doc_type_code == "AUDIT_REPORT":
        events = AuditEvent.objects.select_related("actor").filter(company=company).order_by("-created_at")[:200]
        rows = [
            {
                "sn": idx,
                "description": f"{ev.action} · {ev.entity_type} ({ev.entity_id})",
                "qty": ev.actor.username if ev.actor else "system",
                "rate": ev.created_at.strftime("%Y-%m-%d %H:%M"),
                "amount": Decimal("0.00"),
            }
            for idx, ev in enumerate(events, start=1)
        ]
        return {
            "document_type": doc_type_code,
            "title": "System & Financial Audit Report",
            "title_ne": "लेखापरीक्षण प्रतिवेदन",
            "source_model": "audit.AuditEvent",
            "source_id": str(source_id),
            "document_number": f"AUD-{today.strftime('%Y%m%d')}",
            "issue_date": today,
            "status": "ISSUED",
            "currency": company.base_currency or "NPR",
            "party": {"name": company.name, "pan_vat": company.pan_vat_no, "address": getattr(company, "address", ""), "contact": ""},
            "project": {"code": "-", "name": "Immutable Audit Log", "site": "-"},
            "metadata": [{"label": "Event Count", "value": str(len(rows))}],
            "columns": [
                {"key": "sn", "label": "#", "type": "int", "align": "center"},
                {"key": "description", "label": "Action / Entity", "type": "text", "align": "left"},
                {"key": "qty", "label": "Actor", "type": "text", "align": "left"},
                {"key": "rate", "label": "Timestamp", "type": "text", "align": "left"},
                {"key": "amount", "label": "Value", "type": "money", "align": "right"},
            ],
            "rows": rows,
            "totals": {"subtotal": Decimal("0.00"), "tax_label": "Entries", "tax_amount": Decimal(len(rows)), "grand_total": Decimal("0.00")},
            "narration": "Append-only governance audit log.",
            "terms": [],
            "worksheets": [],
        }

    # 8b. Construction Operational Documents (GRN, PO, PR, Issue Note, MB, Work Order, Delivery Challan)
    try:
        from apps.construction_ops.models import OperationalDocument

        op_doc = OperationalDocument.objects.select_related("project", "site", "party").prefetch_related("lines").filter(
            company=company, id=source_id
        ).first()
        if op_doc:
            rows = [
                {
                    "sn": l.line_no,
                    "description": f"{l.item_code} — {l.item_name} ({l.unit})",
                    "qty": l.quantity,
                    "rate": l.unit_rate,
                    "amount": l.amount,
                }
                for l in op_doc.lines.all()
            ]
            return {
                "document_type": doc_type.code,
                "title": op_doc.get_doc_kind_display(),
                "title_ne": "निर्माण सञ्चालन कागजात",
                "source_model": "construction_ops.OperationalDocument",
                "source_id": str(op_doc.id),
                "document_number": op_doc.doc_number,
                "issue_date": op_doc.doc_date,
                "status": op_doc.status,
                "currency": company.base_currency or "NPR",
                "branch": op_doc.branch,
                "project_obj": op_doc.project,
                "site_obj": op_doc.site,
                "party": {"name": op_doc.party.name if op_doc.party else company.name, "pan_vat": op_doc.party.pan_vat_no if op_doc.party else "", "address": "", "contact": ""},
                "project": {"code": op_doc.project.code if op_doc.project else "-", "name": op_doc.project.name if op_doc.project else "-", "site": op_doc.site.name if op_doc.site else "-"},
                "metadata": [{"label": "GL Posting Note", "value": "Operational Workflow (No Premature GL)"}],
                "columns": [
                    {"key": "sn", "label": "#", "type": "int", "align": "center"},
                    {"key": "description", "label": "Item / BOQ Description", "type": "text", "align": "left"},
                    {"key": "qty", "label": "Quantity", "type": "number", "align": "right"},
                    {"key": "rate", "label": "Rate", "type": "money", "align": "right"},
                    {"key": "amount", "label": "Amount", "type": "money", "align": "right"},
                ],
                "rows": rows,
                "totals": {"subtotal": op_doc.total_amount, "tax_label": "Tax", "tax_amount": Decimal("0.00"), "grand_total": op_doc.total_amount},
                "narration": op_doc.remarks,
                "terms": ["Operational document — printing does not alter accounting or inventory balances."],
                "worksheets": [],
            }
    except Exception:
        pass

    # 8B. Phase 3/4 Live ERP Models (PO, GRN, Issue, Payslip, Payroll Register, Budget Variance)
    if doc_type_code == "PURCHASE_ORDER":
        try:
            from apps.procurement.models import PurchaseOrder
            po = PurchaseOrder.objects.select_related("vendor__party", "project", "site").prefetch_related("lines__item").filter(company=company, id=source_id).first()
            if po:
                return {
                    "document_type": doc_type.code, "title": f"Purchase Order — {po.po_number}", "title_ne": "खरिद आदेश",
                    "source_model": "procurement.PurchaseOrder", "source_id": str(po.id),
                    "document_number": po.po_number, "issue_date": po.po_date, "status": po.status, "currency": company.base_currency or "NPR",
                    "party": {"name": po.vendor.party.name, "pan_vat": po.vendor.pan_vat_no, "address": po.vendor.party.address, "contact": po.vendor.party.phone},
                    "project": {"code": po.project.code if po.project else "-", "name": po.project.name if po.project else "-", "site": po.site.name if po.site else "-"},
                    "metadata": [{"label": "Order Kind", "value": po.get_order_kind_display()}, {"label": "Terms", "value": f"{po.payment_terms_days} days"}],
                    "columns": [
                        {"key": "sn", "label": "#", "type": "int", "align": "center"},
                        {"key": "description", "label": "Material / Service", "type": "text", "align": "left"},
                        {"key": "qty", "label": "Ordered Qty", "type": "number", "align": "right"},
                        {"key": "rate", "label": "Unit Rate", "type": "money", "align": "right"},
                        {"key": "amount", "label": "Line Total", "type": "money", "align": "right"},
                    ],
                    "rows": [{"sn": i, "description": l.description, "qty": l.ordered_qty, "rate": l.unit_rate, "amount": l.line_total} for i, l in enumerate(po.lines.all(), 1)],
                    "totals": {"subtotal": po.subtotal_amount, "tax_label": "VAT", "tax_amount": po.tax_amount, "grand_total": po.total_amount},
                    "narration": po.justification, "terms": [f"Payment terms: Net {po.payment_terms_days} days."], "worksheets": [],
                }
        except Exception:
            pass

    if doc_type_code == "GOODS_RECEIPT_NOTE":
        try:
            from apps.inventory.models import GoodsReceiptNote
            grn = GoodsReceiptNote.objects.select_related("vendor", "warehouse", "project", "site").prefetch_related("lines__item").filter(company=company, id=source_id).first()
            if grn:
                return {
                    "document_type": doc_type.code, "title": f"Goods Receipt Note — {grn.grn_number}", "title_ne": "सामान प्राप्ति नोट (GRN)",
                    "source_model": "inventory.GoodsReceiptNote", "source_id": str(grn.id),
                    "document_number": grn.grn_number, "issue_date": grn.grn_date, "status": grn.status, "currency": company.base_currency or "NPR",
                    "party": {"name": grn.vendor.name, "pan_vat": grn.vendor.pan_vat_no, "address": grn.warehouse.name, "contact": ""},
                    "project": {"code": grn.project.code if grn.project else "-", "name": grn.project.name if grn.project else "-", "site": grn.site.name if grn.site else "-"},
                    "metadata": [{"label": "Warehouse", "value": grn.warehouse.name}, {"label": "Challan No", "value": grn.challan_no or "-"}],
                    "columns": [
                        {"key": "sn", "label": "#", "type": "int", "align": "center"},
                        {"key": "description", "label": "Item Description", "type": "text", "align": "left"},
                        {"key": "qty", "label": "Accepted Qty", "type": "number", "align": "right"},
                        {"key": "rate", "label": "Rate", "type": "money", "align": "right"},
                        {"key": "amount", "label": "Amount", "type": "money", "align": "right"},
                    ],
                    "rows": [{"sn": i, "description": f"{l.item.item_code} — {l.item.name}", "qty": l.accepted_qty, "rate": l.unit_rate, "amount": l.amount} for i, l in enumerate(grn.lines.all(), 1)],
                    "totals": {"subtotal": grn.total_amount, "tax_label": "Tax", "tax_amount": Decimal("0.00"), "grand_total": grn.total_amount},
                    "narration": grn.remarks, "terms": [], "worksheets": [],
                }
        except Exception:
            pass

    if doc_type_code == "PAYROLL_REGISTER":
        try:
            from apps.hr.models import PayrollRun
            run = PayrollRun.objects.select_related("project").prefetch_related("lines__employee").filter(company=company, id=source_id).first()
            if run:
                return {
                    "document_type": doc_type.code, "title": f"Payroll Register — {run.run_no}", "title_ne": "तलब तथा पारिश्रमिक रजिष्टर",
                    "source_model": "hr.PayrollRun", "source_id": str(run.id),
                    "document_number": run.run_no, "issue_date": run.pay_date, "status": run.status, "currency": company.base_currency or "NPR",
                    "party": {"name": company.name, "pan_vat": company.pan_vat_no, "address": run.period_label, "contact": ""},
                    "project": {"code": run.project.code if run.project else "ALL", "name": run.project.name if run.project else "All Projects", "site": "-"},
                    "metadata": [{"label": "Period", "value": run.period_label}],
                    "columns": [
                        {"key": "sn", "label": "#", "type": "int", "align": "center"},
                        {"key": "description", "label": "Employee", "type": "text", "align": "left"},
                        {"key": "qty", "label": "Gross Pay", "type": "money", "align": "right"},
                        {"key": "rate", "label": "Deductions (PF/Tax/Adv)", "type": "money", "align": "right"},
                        {"key": "amount", "label": "Net Payable", "type": "money", "align": "right"},
                    ],
                    "rows": [{"sn": i, "description": f"{l.employee.employee_code} — {l.employee.full_name}", "qty": l.gross_pay, "rate": l.pf_ssf_deduction + l.tds_tax + l.advance_recovery + l.loan_deduction, "amount": l.net_pay} for i, l in enumerate(run.lines.all(), 1)],
                    "totals": {"subtotal": run.total_gross, "tax_label": "Total Deductions", "tax_amount": run.total_deductions, "grand_total": run.total_net_pay},
                    "narration": f"Payroll Run {run.run_no} ({run.period_label})", "terms": [], "worksheets": [],
                }
        except Exception:
            pass

    if doc_type_code == "PROJECT_BUDGET_VS_ACTUAL":
        try:
            from apps.budgeting.models import Budget
            from apps.budgeting.services import BudgetControlService
            b = Budget.objects.select_related("project").filter(company=company, id=source_id).first()
            if b:
                s = BudgetControlService.get_budget_summary(company, b)
                return {
                    "document_type": doc_type.code, "title": f"Budget vs Actual — {b.budget_code}", "title_ne": "बजेट तथा वास्तविक खर्च विवरण",
                    "source_model": "budgeting.Budget", "source_id": str(b.id),
                    "document_number": b.budget_code, "issue_date": timezone.localdate(), "status": b.status, "currency": company.base_currency or "NPR",
                    "party": {"name": company.name, "pan_vat": company.pan_vat_no, "address": "", "contact": ""},
                    "project": {"code": b.project.code if b.project else "CO", "name": b.title, "site": "-"},
                    "metadata": [{"label": "Version", "value": f"v{b.current_version_no}"}],
                    "columns": [
                        {"key": "sn", "label": "#", "type": "int", "align": "center"},
                        {"key": "description", "label": "Cost Category / Code", "type": "text", "align": "left"},
                        {"key": "qty", "label": "Effective Budget", "type": "money", "align": "right"},
                        {"key": "rate", "label": "Actual + Committed", "type": "money", "align": "right"},
                        {"key": "amount", "label": "Available Budget", "type": "money", "align": "right"},
                    ],
                    "rows": [{"sn": i, "description": f"{l['cost_category']} {l['cost_code']}", "qty": Decimal(l["effective_budget"]), "rate": Decimal(l["actual_cost"]) + Decimal(l["open_commitments"]), "amount": Decimal(l["available_budget"])} for i, l in enumerate(s["lines"], 1)],
                    "totals": {"subtotal": Decimal(s["totals"]["effective"]), "tax_label": "Actual + Committed", "tax_amount": Decimal(s["totals"]["actual"]) + Decimal(s["totals"]["committed"]), "grand_total": Decimal(s["totals"]["available"])},
                    "narration": b.notes, "terms": [], "worksheets": [],
                }
        except Exception:
            pass

    if doc_type_code in ("CUSTOMER_STATEMENT", "SUPPLIER_STATEMENT", "PARTY_CONFIRMATION"):
        try:
            from apps.accounting.models import Party
            from apps.party_hub.models import PartyStatement
            from apps.party_hub.services.statements import StatementGenerationService

            stmt_obj = PartyStatement.objects.select_related("party").filter(company=company, id=source_id).first()
            party = stmt_obj.party if stmt_obj else Party.objects.filter(company=company, id=source_id).first()
            if party:
                data = StatementGenerationService.build_statement_payload(
                    company=company,
                    party=party,
                    from_date=stmt_obj.from_date if stmt_obj else None,
                    to_date=stmt_obj.to_date if stmt_obj else None,
                )
                bal = data["balances"]
                rows = [
                    {
                        "sn": 0,
                        "description": f"Opening Balance ({data['period']['from_date']})",
                        "qty": Decimal("1.00"),
                        "rate": Decimal(bal["opening_balance"]) if bal["opening_side"] == "Dr" else Decimal("0.00"),
                        "amount": Decimal(bal["opening_balance"]) if bal["opening_side"] == "Cr" else Decimal("0.00"),
                    }
                ]
                for i, e in enumerate(data["entries"], 1):
                    rows.append(
                        {
                            "sn": i,
                            "description": f"{e['bs_date'] or e['entry_date']} | {e['voucher_no']} | {e['narration'] or e['entry_kind']}",
                            "qty": Decimal(e["debit"]),
                            "rate": Decimal(e["credit"]),
                            "amount": Decimal(e["running_balance"]),
                        }
                    )
                return {
                    "document_type": doc_type.code,
                    "title": f"{doc_type.name} — {party.name}",
                    "title_ne": "ग्राहक / आपूर्तिकर्ता खाता विवरण",
                    "source_model": "accounting.Party",
                    "source_id": str(party.id),
                    "document_number": stmt_obj.statement_no if stmt_obj else f"{doc_type.default_prefix}-{party.code}",
                    "issue_date": timezone.localdate(),
                    "status": stmt_obj.confirmation_status if stmt_obj else "ISSUED",
                    "currency": company.base_currency or "NPR",
                    "party": {
                        "name": party.name,
                        "pan_vat": party.pan_vat_no,
                        "address": party.address,
                        "contact": party.phone or party.email,
                    },
                    "project": {"code": "SUBLEDGER", "name": f"Control: {data['party']['control_account'] or '-'}", "site": "-"},
                    "metadata": [
                        {"label": "Period", "value": f"{data['period']['from_date']} to {data['period']['to_date']}"},
                        {"label": "Closing Balance", "value": f"{bal['closing_balance']} {bal['closing_side']}"},
                        {"label": "Overdue / Retention / Advance", "value": f"{bal['overdue_balance']} / {bal['retention_balance']} / {bal['advance_balance']}"},
                    ],
                    "columns": [
                        {"key": "sn", "label": "#", "type": "int", "align": "center"},
                        {"key": "description", "label": "Date / Voucher / Particulars", "type": "text", "align": "left"},
                        {"key": "qty", "label": "Debit", "type": "money", "align": "right"},
                        {"key": "rate", "label": "Credit", "type": "money", "align": "right"},
                        {"key": "amount", "label": "Running Balance", "type": "money", "align": "right"},
                    ],
                    "rows": rows,
                    "totals": {
                        "subtotal": Decimal(bal["period_debit"]),
                        "tax_label": "Period Credit",
                        "tax_amount": Decimal(bal["period_credit"]),
                        "grand_total": Decimal(bal["closing_balance"]),
                    },
                    "narration": f"Balance Confirmation Status: {stmt_obj.confirmation_status if stmt_obj else 'LIVE STATEMENT'}. Overdue: {bal['overdue_balance']} | Held Retention: {bal['retention_balance']} | Advances: {bal['advance_balance']}.",
                    "terms": ["Please confirm or raise any reconciliation exceptions within 15 days of statement receipt."],
                    "worksheets": [],
                }
        except Exception:
            pass

    if doc_type_code in ("DEBTORS_AGING", "CREDITORS_AGING"):
        try:
            from apps.party_hub.models import OpenItem
            from apps.party_hub.services.analytics import AgingAnalysisService

            side = OpenItem.HubSide.RECEIVABLE if doc_type_code == "DEBTORS_AGING" else OpenItem.HubSide.PAYABLE
            ag = AgingAnalysisService.compute_aging(company=company, hub_side=side)
            return {
                "document_type": doc_type.code,
                "title": doc_type.name,
                "title_ne": "उमेरगत बक्यौता विवरण",
                "source_model": "party_hub.OpenItem",
                "source_id": str(source_id),
                "document_number": f"{doc_type.default_prefix}-{timezone.localdate().strftime('%Y%m%d')}",
                "issue_date": timezone.localdate(),
                "status": "ISSUED",
                "currency": company.base_currency or "NPR",
                "party": {"name": company.name, "pan_vat": company.pan_vat_no, "address": "", "contact": ""},
                "project": {"code": "ALL", "name": f"As of {ag['as_of_date']} ({ag['basis']})", "site": "-"},
                "metadata": [
                    {"label": "Held Retention", "value": ag["retention_total"]},
                    {"label": "Advances", "value": ag["advance_total"]},
                    {"label": "Unallocated Cash", "value": ag["unallocated_total"]},
                ],
                "columns": [
                    {"key": "sn", "label": "#", "type": "int", "align": "center"},
                    {"key": "description", "label": "Party (Current / 1-30 / 31-60 / 61-90 / 91-180 / 181-365 / 365+)", "type": "text", "align": "left"},
                    {"key": "qty", "label": "Current", "type": "money", "align": "right"},
                    {"key": "rate", "label": "Overdue (1-365+)", "type": "money", "align": "right"},
                    {"key": "amount", "label": "Total Open", "type": "money", "align": "right"},
                ],
                "rows": [
                    {
                        "sn": i,
                        "description": f"{r['code']} {r['name']} [Retention: {r['retention_held']}]",
                        "qty": Decimal(r["current"]),
                        "rate": Decimal(r["total_open"]) - Decimal(r["current"]),
                        "amount": Decimal(r["total_open"]),
                    }
                    for i, r in enumerate(ag["rows"], 1)
                ],
                "totals": {
                    "subtotal": Decimal(ag["totals"]["current"]),
                    "tax_label": "Overdue Total",
                    "tax_amount": Decimal(ag["totals"]["total"]) - Decimal(ag["totals"]["current"]),
                    "grand_total": Decimal(ag["totals"]["total"]),
                },
                "narration": "Retention and Advances are reported separately and excluded from ordinary invoice aging.",
                "terms": [],
                "worksheets": [],
            }
        except Exception:
            pass

    if doc_type_code in ("RECEIPT_ADVICE", "PAYMENT_ADVICE"):
        try:
            from apps.accounting.models import BillAllocation
            v = Voucher.objects.select_related("party", "project").filter(company=company, id=source_id).first()
            if v:
                allocs = list(BillAllocation.objects.select_related("against_voucher").filter(settlement_voucher=v))
                return {
                    "document_type": doc_type.code,
                    "title": f"{doc_type.name} — {v.voucher_no}",
                    "title_ne": "भुक्तानी / प्राप्ति मिलान विवरण",
                    "source_model": "accounting.Voucher",
                    "source_id": str(v.id),
                    "document_number": v.voucher_no or str(v.id)[:8],
                    "issue_date": v.voucher_date,
                    "status": v.status,
                    "currency": v.currency,
                    "party": {"name": v.party.name if v.party else v.party_name, "pan_vat": v.party.pan_vat_no if v.party else v.party_pan, "address": v.party.address if v.party else "", "contact": ""},
                    "project": {"code": v.project.code if v.project else "-", "name": v.project.name if v.project else "-", "site": "-"},
                    "metadata": [{"label": "Voucher Date", "value": v.voucher_date.isoformat()}, {"label": "Reference", "value": v.reference_no or "-"}],
                    "columns": [
                        {"key": "sn", "label": "#", "type": "int", "align": "center"},
                        {"key": "description", "label": "Settled Invoice / Bill", "type": "text", "align": "left"},
                        {"key": "qty", "label": "TDS / Discount", "type": "money", "align": "right"},
                        {"key": "rate", "label": "Retention Released", "type": "money", "align": "right"},
                        {"key": "amount", "label": "Allocated Amount", "type": "money", "align": "right"},
                    ],
                    "rows": [
                        {
                            "sn": i,
                            "description": f"{a.against_voucher.voucher_no} ({a.against_voucher.supplier_invoice_no or a.against_voucher.voucher_type})",
                            "qty": a.tds_withheld + a.discount_amount,
                            "rate": a.retention_released,
                            "amount": a.allocated_amount,
                        }
                        for i, a in enumerate(allocs, 1)
                    ],
                    "totals": {"subtotal": v.net_amount or v.gross_amount, "tax_label": "TDS", "tax_amount": v.tds_amount, "grand_total": v.net_amount or v.gross_amount},
                    "narration": v.narration,
                    "terms": [],
                    "worksheets": [],
                }
        except Exception:
            pass

    # 9. Standalone DocumentRecord (Construction Job-Work, Delivery Challan, GRN, PO, HR Payslip, etc.)
    rec = DocumentRecord.objects.select_related("project", "site", "branch").filter(
        company=company, document_type=doc_type
    ).filter(Q(id=source_id) | Q(source_id=source_id)).first()
    if not rec:
        raise ObjectDoesNotExist(f"Document record '{source_id}' for {doc_type_code} not found.")

    p = rec.payload_data or {}
    return {
        "document_type": doc_type.code,
        "title": p.get("title") or doc_type.name,
        "title_ne": p.get("title_ne") or doc_type.name,
        "source_model": rec.source_model,
        "source_id": rec.source_id,
        "document_number": rec.document_number or f"DRAFT-{str(rec.id)[:8].upper()}",
        "issue_date": rec.issue_date or rec.created_at.date(),
        "status": rec.status,
        "currency": rec.currency,
        "branch": rec.branch,
        "project_obj": rec.project,
        "site_obj": rec.site,
        "party": p.get("party") or {"name": rec.party_name or company.name, "pan_vat": rec.party_pan, "address": "", "contact": ""},
        "project": {
            "code": rec.project.code if rec.project else "-",
            "name": rec.project.name if rec.project else "-",
            "site": rec.site.name if rec.site else "-",
        },
        "metadata": p.get("metadata") or [],
        "columns": p.get("columns")
        or [
            {"key": "sn", "label": "#", "type": "int", "align": "center"},
            {"key": "description", "label": "Description / Item", "type": "text", "align": "left"},
            {"key": "qty", "label": "Qty", "type": "number", "align": "right"},
            {"key": "rate", "label": "Rate", "type": "money", "align": "right"},
            {"key": "amount", "label": "Amount", "type": "money", "align": "right"},
        ],
        "rows": p.get("rows") or [],
        "totals": p.get("totals")
        or {
            "subtotal": rec.total_amount,
            "tax_label": "Tax",
            "tax_amount": Decimal("0.00"),
            "grand_total": rec.total_amount,
        },
        "narration": p.get("narration") or "",
        "terms": p.get("terms") or [],
        "worksheets": p.get("worksheets") or [],
    }
