from decimal import Decimal
from django.db import transaction
from django.db.models import Sum

from apps.accounting.models import (
    Account,
    AdvanceRecord,
    BoqItem,
    CostCategory,
    CostCenter,
    EmployeeProfile,
    EquipmentAsset,
    LedgerEntry,
    Party,
    PayrollLiability,
    StaffLoan,
    VoucherDesignRevision,
    VoucherLayoutBlueprint,
    VoucherThemeConfig,
    WorkPackage,
)

DEFAULT_THEMES_CATALOG = [
    {
        "theme_code": "TALLY_CLASSIC",
        "name": "Tally Classic",
        "accent_color": "#0f766e",
        "header_bg": "#064e3b",
        "density": "compact",
        "border_radius": "rounded-sm",
        "font_style": "JetBrains Mono, ui-monospace, monospace",
        "icon_name": "Terminal",
        "spacing_scale": "tight",
        "header_style": "classic-bar",
        "card_style": "flat-ledger",
        "typography_config": {"heading_size": "13px", "body_size": "12px", "numeric_tabular": True},
        "color_tokens": {"surface": "#f7fee7", "border": "#a7f3d0", "badge_bg": "#ecfdf5", "badge_text": "#065f46"},
    },
    {
        "theme_code": "ENTERPRISE_MODERN",
        "name": "Enterprise Modern",
        "accent_color": "#4f46e5",
        "header_bg": "#0f172a",
        "density": "comfortable",
        "border_radius": "rounded-xl",
        "font_style": "Inter, system-ui, sans-serif",
        "icon_name": "LayoutGrid",
        "spacing_scale": "normal",
        "header_style": "gradient",
        "card_style": "elevated",
        "typography_config": {"heading_size": "15px", "body_size": "13px", "numeric_tabular": True},
        "color_tokens": {"surface": "#ffffff", "border": "#e2e8f0", "badge_bg": "#eef2ff", "badge_text": "#3730a3"},
    },
    {
        "theme_code": "CONSTRUCTION_SITE",
        "name": "Construction Site",
        "accent_color": "#d97706",
        "header_bg": "#78350f",
        "density": "compact",
        "border_radius": "rounded-lg",
        "font_style": "Plus Jakarta Sans, Inter, sans-serif",
        "icon_name": "HardHat",
        "spacing_scale": "normal",
        "header_style": "hazard-accent",
        "card_style": "bordered",
        "typography_config": {"heading_size": "14px", "body_size": "12px", "numeric_tabular": True},
        "color_tokens": {"surface": "#fffbeb", "border": "#fde68a", "badge_bg": "#fef3c7", "badge_text": "#92400e"},
    },
    {
        "theme_code": "BANKING_TREASURY",
        "name": "Banking and Treasury",
        "accent_color": "#0369a1",
        "header_bg": "#0c4a6e",
        "density": "comfortable",
        "border_radius": "rounded-xl",
        "font_style": "Inter, system-ui, sans-serif",
        "icon_name": "Landmark",
        "spacing_scale": "normal",
        "header_style": "gradient",
        "card_style": "elevated",
        "typography_config": {"heading_size": "14px", "body_size": "13px", "numeric_tabular": True},
        "color_tokens": {"surface": "#f0f9ff", "border": "#bae6fd", "badge_bg": "#e0f2fe", "badge_text": "#075985"},
    },
    {
        "theme_code": "CONTRACTOR_JOBWORK",
        "name": "Job Work and Contractor",
        "accent_color": "#4338ca",
        "header_bg": "#312e81",
        "density": "comfortable",
        "border_radius": "rounded-lg",
        "font_style": "Inter, system-ui, sans-serif",
        "icon_name": "FileCheck2",
        "spacing_scale": "normal",
        "header_style": "gradient",
        "card_style": "elevated",
        "typography_config": {"heading_size": "14px", "body_size": "13px", "numeric_tabular": True},
        "color_tokens": {"surface": "#eef2ff", "border": "#c7d2fe", "badge_bg": "#e0e7ff", "badge_text": "#3730a3"},
    },
    {
        "theme_code": "MATERIAL_INVENTORY",
        "name": "Material and Inventory",
        "accent_color": "#059669",
        "header_bg": "#064e3b",
        "density": "compact",
        "border_radius": "rounded-lg",
        "font_style": "Inter, system-ui, sans-serif",
        "icon_name": "Package",
        "spacing_scale": "tight",
        "header_style": "solid",
        "card_style": "bordered",
        "typography_config": {"heading_size": "14px", "body_size": "12px", "numeric_tabular": True},
        "color_tokens": {"surface": "#ecfdf5", "border": "#a7f3d0", "badge_bg": "#d1fae5", "badge_text": "#065f46"},
    },
    {
        "theme_code": "PAYROLL_HR",
        "name": "Payroll and HR",
        "accent_color": "#7c3aed",
        "header_bg": "#4c1d95",
        "density": "comfortable",
        "border_radius": "rounded-xl",
        "font_style": "Inter, system-ui, sans-serif",
        "icon_name": "Users",
        "spacing_scale": "normal",
        "header_style": "gradient",
        "card_style": "elevated",
        "typography_config": {"heading_size": "14px", "body_size": "13px", "numeric_tabular": True},
        "color_tokens": {"surface": "#f5f3ff", "border": "#ddd6fe", "badge_bg": "#ede9fe", "badge_text": "#5b21b6"},
    },
    {
        "theme_code": "FORMAL_PRINT",
        "name": "Formal Print",
        "accent_color": "#334155",
        "header_bg": "#f8fafc",
        "density": "spacious",
        "border_radius": "rounded-none",
        "font_style": "Georgia, Cambria, serif",
        "icon_name": "Printer",
        "spacing_scale": "relaxed",
        "header_style": "ledger-sheet",
        "card_style": "ruled",
        "typography_config": {"heading_size": "15px", "body_size": "13px", "numeric_tabular": True},
        "color_tokens": {"surface": "#ffffff", "border": "#94a3b8", "badge_bg": "#f1f5f9", "badge_text": "#1e293b"},
    },
]


def _default_sections(family: str) -> list[dict]:
    common_tail = [
        {"id": "narration_attachments", "title": "Narration & Supporting Documents", "visible": True, "order": 4},
        {"id": "totals_bar", "title": "Sticky Totals & Actions", "visible": True, "order": 5},
    ]
    if family == "BANKING_SETTLEMENT":
        return [
            {"id": "bank_cash_header", "title": "Paying / Receiving Bank & Payment Instrument", "visible": True, "order": 1},
            {"id": "party_balance_card", "title": "Counterparty Subledger & Live Exposure", "visible": True, "order": 2},
            {"id": "invoice_settlement_grid", "title": "Open Invoices, TDS & Advance Settlement", "visible": True, "order": 3},
            *common_tail,
        ]
    if family == "CONTRA_TRANSFER":
        return [
            {"id": "transfer_route", "title": "Source -> Destination Treasury Route", "visible": True, "order": 1},
            {"id": "instrument_denomination", "title": "Transfer Mode, Cheque / UTR & Remarks", "visible": True, "order": 2},
            *common_tail,
        ]
    if family == "COMMERCIAL_INVOICE":
        return [
            {"id": "counterparty_order_ref", "title": "Vendor / Customer & PO / GRN Reference", "visible": True, "order": 1},
            {"id": "item_tax_grid", "title": "Items, Quantities, Rates & GST/VAT Grid", "visible": True, "order": 2},
            {"id": "charges_taxes_summary", "title": "Freight, Discounts, TDS & Payable Breakdown", "visible": True, "order": 3},
            *common_tail,
        ]
    if family == "STOCK_MOVEMENT":
        return [
            {"id": "warehouse_site_header", "title": "Source / Target Store, Project & Site", "visible": True, "order": 1},
            {"id": "stock_availability_grid", "title": "Item Stock On-Hand, Movement Qty & Variance", "visible": True, "order": 2},
            *common_tail,
        ]
    if family == "CONSTRUCTION_BILLING":
        return [
            {"id": "project_contract_header", "title": "Project, Contract / BOQ & Party Header", "visible": True, "order": 1},
            {"id": "certification_grid", "title": "BOQ Measurement, Certified Value & Deductions", "visible": True, "order": 2},
            {"id": "retention_advance_panel", "title": "Retention, TDS & Mobilization Advance Recovery", "visible": True, "order": 3},
            *common_tail,
        ]
    if family == "PAYROLL_HR":
        return [
            {"id": "payroll_period_header", "title": "Pay Period, Project & Disbursement Bank", "visible": True, "order": 1},
            {"id": "employee_batch_grid", "title": "Employee / Crew Pay Sheet, Allowances & Deductions", "visible": True, "order": 2},
            *common_tail,
        ]
    if family == "LOAN_AND_ASSET":
        return [
            {"id": "facility_asset_header", "title": "Loan Facility / Fixed Asset Selection", "visible": True, "order": 1},
            {"id": "schedule_valuation_grid", "title": "Principal, Interest / Depreciation & Proceeds", "visible": True, "order": 2},
            *common_tail,
        ]
    return [
        {"id": "header_meta", "title": "Voucher Date, Numbering & Cost Allocation", "visible": True, "order": 1},
        {"id": "entry_grid", "title": "Intelligent Double-Entry Accounting Grid", "visible": True, "order": 2},
        *common_tail,
    ]


def _build_catalog() -> list[dict]:
    # Each tuple: (voucher_type, family, title, subtitle, theme, icon, pdf_code, shortcut, extra_fields, columns)
    specs = [
        ("PAYMENT", "BANKING_SETTLEMENT", "Payment Voucher (F5)", "Bank/cash disbursement with bill-wise invoice settlement & TDS", "BANKING_TREASURY", "ArrowUpRight", "PAYMENT_VOUCHER", "F5",
         [
             {"key": "bank_account", "label": "Paying Bank / Cash A/C", "required": True, "visible": True, "section": "bank_cash_header"},
             {"key": "payment_mode", "label": "Payment Mode", "required": True, "visible": True, "default_value": "BANK_TRANSFER", "section": "bank_cash_header"},
             {"key": "instrument_no", "label": "Cheque / UTR / Ref No", "required": False, "visible": True, "condition_field": "payment_mode", "condition_value": "CHEQUE", "section": "bank_cash_header"},
             {"key": "party", "label": "Payee / Supplier / Subcontractor", "required": True, "visible": True, "section": "party_balance_card"},
             {"key": "tds_rate", "label": "TDS %", "required": False, "visible": True, "default_value": "1.5", "section": "invoice_settlement_grid"},
         ],
         ["bill_no", "bill_date", "due_date", "outstanding", "allocate_amt", "tds_amt"]),
        ("RECEIPT", "BANKING_SETTLEMENT", "Receipt Voucher (F6)", "Customer/client inward collection with RA invoice & advance allocation", "BANKING_TREASURY", "ArrowDownLeft", "RECEIPT_VOUCHER", "F6",
         [
             {"key": "bank_account", "label": "Receiving Bank / Cash A/C", "required": True, "visible": True, "section": "bank_cash_header"},
             {"key": "payment_mode", "label": "Receipt Mode", "required": True, "visible": True, "default_value": "BANK_TRANSFER", "section": "bank_cash_header"},
             {"key": "party", "label": "Received From (Client / Debtor)", "required": True, "visible": True, "section": "party_balance_card"},
             {"key": "instrument_no", "label": "Deposit / TT Reference", "required": False, "visible": True, "section": "bank_cash_header"},
         ],
         ["bill_no", "bill_date", "outstanding", "allocate_amt", "discount_amt"]),
        ("CONTRA", "CONTRA_TRANSFER", "Contra Transfer Voucher (F4)", "Internal cash-to-bank, bank-to-cash, and inter-bank treasury transfer", "BANKING_TREASURY", "ArrowLeftRight", "CONTRA_VOUCHER", "F4",
         [
             {"key": "source_account", "label": "Source Account (Credit)", "required": True, "visible": True, "section": "transfer_route"},
             {"key": "destination_account", "label": "Destination Account (Debit)", "required": True, "visible": True, "section": "transfer_route"},
             {"key": "transfer_kind", "label": "Transfer Nature", "required": True, "visible": True, "default_value": "CASH_DEPOSIT", "section": "instrument_denomination"},
             {"key": "amount", "label": "Transfer Amount", "required": True, "visible": True, "section": "transfer_route"},
         ],
         ["source_account", "destination_account", "instrument_no", "amount"]),
        ("JOURNAL", "JOURNAL_INTELLIGENCE", "Journal Voucher (F7)", "Intelligent ledger workbench with subledgers, control accounts & adjustments", "TALLY_CLASSIC", "BookOpen", "JOURNAL_VOUCHER", "F7",
         [
             {"key": "voucher_date", "label": "Journal Date", "required": True, "visible": True, "section": "header_meta"},
             {"key": "project", "label": "Project / Site", "required": False, "visible": True, "section": "header_meta"},
         ],
         ["account", "subledger", "cost_center", "debit", "credit", "narration"]),
        ("PURCHASE", "COMMERCIAL_INVOICE", "Purchase Invoice Voucher (F9)", "Vendor billing linked to PO/GRN, inventory items, ITC VAT & TDS", "ENTERPRISE_MODERN", "ShoppingCart", "PURCHASE_INVOICE", "F9",
         [
             {"key": "party", "label": "Supplier / Vendor", "required": True, "visible": True, "section": "counterparty_order_ref"},
             {"key": "purchase_order_ref", "label": "Linked Purchase Order", "required": False, "visible": True, "section": "counterparty_order_ref"},
             {"key": "grn_ref", "label": "Linked GRN / Receipt Note", "required": False, "visible": True, "section": "counterparty_order_ref"},
             {"key": "supplier_invoice_no", "label": "Vendor Tax Invoice No", "required": True, "visible": True, "section": "counterparty_order_ref"},
         ],
         ["item", "warehouse", "qty", "rate", "discount_pct", "tax_rate", "line_total"]),
        ("SALES", "COMMERCIAL_INVOICE", "Sales / Service Invoice (F8)", "Customer contract billing, delivery ref, Output VAT & retention", "ENTERPRISE_MODERN", "Receipt", "SALES_INVOICE", "F8",
         [
             {"key": "party", "label": "Customer / Client", "required": True, "visible": True, "section": "counterparty_order_ref"},
             {"key": "sales_order_ref", "label": "Contract / Sales Order", "required": False, "visible": True, "section": "counterparty_order_ref"},
             {"key": "retention_pct", "label": "Retention Holdback %", "required": False, "visible": True, "default_value": "0", "section": "charges_taxes_summary"},
         ],
         ["item_or_service", "qty", "rate", "discount_pct", "tax_rate", "line_total"]),
        ("DEBIT_NOTE", "COMMERCIAL_INVOICE", "Debit Note (Alt+F5)", "Purchase return or supplier rate/quantity downward claim", "ENTERPRISE_MODERN", "FileMinus", "DEBIT_NOTE", "Alt+F5",
         [
             {"key": "party", "label": "Supplier", "required": True, "visible": True, "section": "counterparty_order_ref"},
             {"key": "original_invoice_no", "label": "Original Purchase Bill No", "required": True, "visible": True, "section": "counterparty_order_ref"},
         ],
         ["item_or_account", "qty", "rate", "tax_rate", "line_total"]),
        ("CREDIT_NOTE", "COMMERCIAL_INVOICE", "Credit Note (Alt+F6)", "Sales return, rebate or client billing credit adjustment", "ENTERPRISE_MODERN", "FilePlus", "CREDIT_NOTE", "Alt+F6",
         [
             {"key": "party", "label": "Customer / Client", "required": True, "visible": True, "section": "counterparty_order_ref"},
             {"key": "original_invoice_no", "label": "Original Sales Invoice No", "required": True, "visible": True, "section": "counterparty_order_ref"},
         ],
         ["item_or_account", "qty", "rate", "tax_rate", "line_total"]),
        ("PURCHASE_ORDER", "COMMERCIAL_INVOICE", "Purchase Order Voucher", "Non-posting procurement order with committed project budget tracking", "MATERIAL_INVENTORY", "ClipboardList", "PURCHASE_ORDER_DOC", "",
         [
             {"key": "party", "label": "Proposed Vendor", "required": True, "visible": True, "section": "counterparty_order_ref"},
             {"key": "project", "label": "Destination Project", "required": True, "visible": True, "section": "counterparty_order_ref"},
             {"key": "expected_delivery_date", "label": "Delivery Schedule Date", "required": False, "visible": True, "section": "counterparty_order_ref"},
         ],
         ["item", "qty", "unit", "target_rate", "tax_rate", "line_total"]),
        ("SALES_ORDER", "COMMERCIAL_INVOICE", "Sales Order Voucher", "Client contract/sales order commitment before billing", "ENTERPRISE_MODERN", "ClipboardCheck", "SALES_ORDER_DOC", "",
         [
             {"key": "party", "label": "Client / Customer", "required": True, "visible": True, "section": "counterparty_order_ref"},
             {"key": "project", "label": "Project Scope", "required": True, "visible": True, "section": "counterparty_order_ref"},
         ],
         ["item_or_service", "qty", "unit", "contract_rate", "tax_rate", "line_total"]),
        ("RECEIPT_NOTE", "STOCK_MOVEMENT", "Receipt Note / GRN", "Goods inward receipt into site store increasing warehouse stock", "MATERIAL_INVENTORY", "PackageCheck", "GRN_RECEIPT", "",
         [
             {"key": "party", "label": "Vendor", "required": True, "visible": True, "section": "warehouse_site_header"},
             {"key": "warehouse", "label": "Receiving Warehouse", "required": True, "visible": True, "section": "warehouse_site_header"},
             {"key": "challan_no", "label": "Delivery Challan No", "required": True, "visible": True, "section": "warehouse_site_header"},
         ],
         ["item", "available_stock", "qty_in", "rate", "batch_no", "value"]),
        ("DELIVERY_NOTE", "STOCK_MOVEMENT", "Delivery Note", "Dispatch outward from store against customer/site delivery", "MATERIAL_INVENTORY", "Truck", "DELIVERY_NOTE_DOC", "",
         [
             {"key": "party", "label": "Recipient / Customer", "required": True, "visible": True, "section": "warehouse_site_header"},
             {"key": "warehouse", "label": "Dispatch Warehouse", "required": True, "visible": True, "section": "warehouse_site_header"},
         ],
         ["item", "available_stock", "qty_out", "rate", "value"]),
        ("REJECTIONS_IN", "STOCK_MOVEMENT", "Rejections In", "Customer/site goods returned inward due to defect or excess", "MATERIAL_INVENTORY", "Undo2", "REJECTIONS_IN_DOC", "",
         [{"key": "warehouse", "label": "Receiving Store", "required": True, "visible": True, "section": "warehouse_site_header"}],
         ["item", "available_stock", "qty_in", "reason", "value"]),
        ("REJECTIONS_OUT", "STOCK_MOVEMENT", "Rejections Out", "Defective materials returned outward back to supplier", "MATERIAL_INVENTORY", "Redo2", "REJECTIONS_OUT_DOC", "",
         [{"key": "party", "label": "Supplier", "required": True, "visible": True, "section": "warehouse_site_header"}, {"key": "warehouse", "label": "Dispatch Store", "required": True, "visible": True, "section": "warehouse_site_header"}],
         ["item", "available_stock", "qty_out", "reason", "value"]),
        ("STOCK_JOURNAL", "STOCK_MOVEMENT", "Stock Journal (Transfer)", "Inter-warehouse store transfer & valuation adjustment", "MATERIAL_INVENTORY", "ArrowLeftRight", "STOCK_JOURNAL_DOC", "Alt+F7",
         [{"key": "warehouse", "label": "Source Store", "required": True, "visible": True, "section": "warehouse_site_header"}, {"key": "target_warehouse", "label": "Target Store", "required": True, "visible": True, "section": "warehouse_site_header"}],
         ["item", "available_stock", "qty_transfer", "rate", "value"]),
        ("PHYSICAL_STOCK", "STOCK_MOVEMENT", "Physical Stock Verification", "Cycle count reconciliation against live system book stock", "MATERIAL_INVENTORY", "ScanLine", "PHYSICAL_STOCK_DOC", "Ctrl+F7",
         [{"key": "warehouse", "label": "Verified Store / Yard", "required": True, "visible": True, "section": "warehouse_site_header"}],
         ["item", "book_qty", "counted_qty", "variance_qty", "rate", "variance_value"]),
        ("MATERIAL_IN", "STOCK_MOVEMENT", "Material In (Job Work)", "Materials received inward from subcontractor / fabricator", "MATERIAL_INVENTORY", "PackagePlus", "MATERIAL_IN_DOC", "",
         [{"key": "party", "label": "Job Worker / Fabricator", "required": True, "visible": True, "section": "warehouse_site_header"}, {"key": "warehouse", "label": "Receiving Store", "required": True, "visible": True, "section": "warehouse_site_header"}],
         ["item", "available_stock", "qty_in", "rate", "value"]),
        ("MATERIAL_OUT", "STOCK_MOVEMENT", "Material Out (Job Work)", "Raw material issued to external subcontractor / fabricator", "MATERIAL_INVENTORY", "PackageMinus", "MATERIAL_OUT_DOC", "",
         [{"key": "party", "label": "Job Worker / Fabricator", "required": True, "visible": True, "section": "warehouse_site_header"}, {"key": "warehouse", "label": "Dispatch Store", "required": True, "visible": True, "section": "warehouse_site_header"}],
         ["item", "available_stock", "qty_out", "rate", "value"]),
        ("MANUFACTURING_JOURNAL", "STOCK_MOVEMENT", "Manufacturing / RMC Batch Journal", "Raw material consumption vs finished concrete/precast output", "MATERIAL_INVENTORY", "Factory", "MANUFACTURING_DOC", "",
         [{"key": "warehouse", "label": "Batching / Plant Store", "required": True, "visible": True, "section": "warehouse_site_header"}, {"key": "project", "label": "Project", "required": True, "visible": True, "section": "warehouse_site_header"}],
         ["component_item", "available_stock", "consumed_qty", "output_item", "output_qty", "effective_rate"]),
        ("PAYROLL", "PAYROLL_HR", "Payroll Voucher", "Monthly salary batch with allowances, overtime, PF/SSF/TDS & advances", "PAYROLL_HR", "Users", "PAYROLL_VOUCHER", "Ctrl+F4",
         [
             {"key": "pay_month", "label": "Pay Month / Cycle", "required": True, "visible": True, "section": "payroll_period_header"},
             {"key": "bank_account", "label": "Disbursement / Payable A/C", "required": True, "visible": True, "section": "payroll_period_header"},
             {"key": "project", "label": "Cost Project", "required": False, "visible": True, "section": "payroll_period_header"},
         ],
         ["employee", "basic_salary", "allowances", "overtime", "deductions", "advance_recovery", "net_salary"]),
        ("SITE_EXPENSE", "CONSTRUCTION_BILLING", "Site Expense Voucher", "Field petty cash / imprest expenditure by project, site & cost code", "CONSTRUCTION_SITE", "HardHat", "SITE_EXPENSE_VOUCHER", "",
         [
             {"key": "project", "label": "Construction Project", "required": True, "visible": True, "section": "project_contract_header"},
             {"key": "site", "label": "Work Site", "required": True, "visible": True, "section": "project_contract_header"},
             {"key": "cash_advance_account", "label": "Site Cash / Imprest A/C", "required": True, "visible": True, "section": "project_contract_header"},
         ],
         ["expense_account", "cost_code", "boq_item", "receipt_ref", "amount", "remarks"]),
        ("MATERIAL_PURCHASE", "COMMERCIAL_INVOICE", "Material Purchase Voucher", "Project store material acquisition with PO, GRN & perpetual inventory", "MATERIAL_INVENTORY", "Truck", "MATERIAL_PURCHASE_DOC", "",
         [
             {"key": "party", "label": "Material Supplier", "required": True, "visible": True, "section": "counterparty_order_ref"},
             {"key": "project", "label": "Project", "required": True, "visible": True, "section": "counterparty_order_ref"},
             {"key": "warehouse", "label": "Destination Store", "required": True, "visible": True, "section": "counterparty_order_ref"},
             {"key": "grn_ref", "label": "GRN Ref", "required": False, "visible": True, "section": "counterparty_order_ref"},
         ],
         ["item", "warehouse", "qty", "rate", "tax_rate", "line_total"]),
        ("MATERIAL_ISSUE", "STOCK_MOVEMENT", "Material Issue to Site", "Issue construction materials from warehouse into Project WIP & Cost Code", "CONSTRUCTION_SITE", "PackageOpen", "MATERIAL_ISSUE_DOC", "",
         [
             {"key": "warehouse", "label": "Issuing Warehouse", "required": True, "visible": True, "section": "warehouse_site_header"},
             {"key": "project", "label": "Destination Project", "required": True, "visible": True, "section": "warehouse_site_header"},
             {"key": "site", "label": "Site", "required": True, "visible": True, "section": "warehouse_site_header"},
         ],
         ["item", "available_stock", "issue_qty", "cost_code", "boq_item", "rate", "value"]),
        ("MATERIAL_RETURN", "STOCK_MOVEMENT", "Material Return to Store", "Unused site material returned back into inventory from Project WIP", "CONSTRUCTION_SITE", "RotateCcw", "MATERIAL_RETURN_DOC", "",
         [
             {"key": "warehouse", "label": "Receiving Warehouse", "required": True, "visible": True, "section": "warehouse_site_header"},
             {"key": "project", "label": "Origin Project", "required": True, "visible": True, "section": "warehouse_site_header"},
         ],
         ["item", "available_stock", "return_qty", "rate", "value"]),
        ("LABOR_PAYMENT", "PAYROLL_HR", "Labor / Muster Roll Payment", "Site gang & daily wage muster roll batch with overtime & advances", "CONSTRUCTION_SITE", "Hammer", "LABOR_PAYMENT_VOUCHER", "",
         [
             {"key": "project", "label": "Project", "required": True, "visible": True, "section": "payroll_period_header"},
             {"key": "site", "label": "Work Site", "required": True, "visible": True, "section": "payroll_period_header"},
             {"key": "bank_account", "label": "Cash / Bank A/C", "required": True, "visible": True, "section": "payroll_period_header"},
         ],
         ["worker_or_gang", "days_worked", "daily_rate", "overtime", "advance_recovery", "net_paid"]),
        ("SUBCONTRACTOR_BILL", "CONSTRUCTION_BILLING", "Subcontractor RA Bill", "BOQ measurement, certified work value, retention, TDS & mobilization advance recovery", "CONTRACTOR_JOBWORK", "FileCheck2", "SUBCONTRACTOR_RA_BILL", "",
         [
             {"key": "party", "label": "Subcontractor", "required": True, "visible": True, "section": "project_contract_header"},
             {"key": "project", "label": "Project", "required": True, "visible": True, "section": "project_contract_header"},
             {"key": "work_package", "label": "Work Order / Package", "required": True, "visible": True, "section": "project_contract_header"},
             {"key": "retention_pct", "label": "Retention %", "required": True, "visible": True, "default_value": "5.0", "section": "retention_advance_panel"},
             {"key": "tds_rate", "label": "Contractor TDS %", "required": True, "visible": True, "default_value": "1.5", "section": "retention_advance_panel"},
         ],
         ["boq_item", "prev_qty", "current_qty", "unit_rate", "certified_amt"]),
        ("CLIENT_RA_BILL", "CONSTRUCTION_BILLING", "Client RA Bill / IPC", "Certified IPC billing, customer retention receivable, VAT 13% & mobilization advance recovery", "CONTRACTOR_JOBWORK", "Building2", "CLIENT_RA_BILL_DOC", "",
         [
             {"key": "party", "label": "Employer / Client", "required": True, "visible": True, "section": "project_contract_header"},
             {"key": "project", "label": "Contract Project", "required": True, "visible": True, "section": "project_contract_header"},
             {"key": "ipc_no", "label": "IPC / Certificate Ref", "required": True, "visible": True, "section": "project_contract_header"},
             {"key": "retention_pct", "label": "Customer Retention %", "required": True, "visible": True, "default_value": "5.0", "section": "retention_advance_panel"},
         ],
         ["boq_item", "certified_qty", "rate", "certified_amt", "collection_status"]),
        ("MACHINE_INCOME", "CONSTRUCTION_BILLING", "Machine & Equipment Income", "Machinery hire & equipment income via Single Entry (Cash/Bank) or Double Entry (Customer / Dr-Cr)", "CONSTRUCTION_SITE", "Wrench", "RECEIPT_VOUCHER", "",
         [
             {"key": "bank_account", "label": "Receiving Cash / Bank A/C", "required": False, "visible": True, "section": "project_contract_header"},
             {"key": "equipment", "label": "Machinery / Equipment", "required": False, "visible": True, "section": "project_contract_header"},
             {"key": "party", "label": "Customer (Credit Billing)", "required": False, "visible": True, "section": "project_contract_header"},
         ],
         ["equipment", "project", "hours_or_trips", "rate", "amount"]),
        ("STAFF_ADVANCE", "PAYROLL_HR", "Staff Advance Voucher", "Imprest or salary advance issued to employee/engineer", "PAYROLL_HR", "Wallet", "STAFF_ADVANCE_DOC", "",
         [
             {"key": "employee", "label": "Employee / Staff", "required": True, "visible": True, "section": "payroll_period_header"},
             {"key": "bank_account", "label": "Paying Bank / Cash", "required": True, "visible": True, "section": "payroll_period_header"},
             {"key": "project", "label": "Assigned Project", "required": False, "visible": True, "section": "payroll_period_header"},
         ],
         ["employee", "purpose", "expected_settlement_date", "amount"]),
        ("STAFF_SETTLEMENT", "PAYROLL_HR", "Staff Advance Settlement", "Liquidate employee cash/imprest advance against site bills or cash refund", "PAYROLL_HR", "BadgeCheck", "STAFF_SETTLEMENT_DOC", "",
         [
             {"key": "employee", "label": "Employee / Staff", "required": True, "visible": True, "section": "payroll_period_header"},
             {"key": "advance_record", "label": "Open Advance Reference", "required": True, "visible": True, "section": "payroll_period_header"},
         ],
         ["expense_account", "bill_ref", "cost_code", "settled_amount"]),
        ("SUPPLIER_ADVANCE", "BANKING_SETTLEMENT", "Supplier Advance Voucher", "Prepayment / PO mobilization advance to vendor before invoice", "BANKING_TREASURY", "Send", "SUPPLIER_ADVANCE_DOC", "",
         [
             {"key": "party", "label": "Supplier", "required": True, "visible": True, "section": "party_balance_card"},
             {"key": "bank_account", "label": "Paying Bank", "required": True, "visible": True, "section": "bank_cash_header"},
             {"key": "purchase_order_ref", "label": "PO Reference", "required": False, "visible": True, "section": "party_balance_card"},
         ],
         ["reference_no", "po_ref", "tds_amt", "advance_amount"]),
        ("CUSTOMER_ADVANCE", "BANKING_SETTLEMENT", "Customer Advance Receipt", "Contract mobilization advance liability received from client", "BANKING_TREASURY", "HandCoins", "CUSTOMER_ADVANCE_DOC", "",
         [
             {"key": "party", "label": "Client / Customer", "required": True, "visible": True, "section": "party_balance_card"},
             {"key": "bank_account", "label": "Receiving Bank", "required": True, "visible": True, "section": "bank_cash_header"},
             {"key": "project", "label": "Contract Project", "required": True, "visible": True, "section": "party_balance_card"},
         ],
         ["contract_ref", "bg_ref", "advance_amount"]),
        ("RETENTION", "CONSTRUCTION_BILLING", "Retention Release / Adjustment", "Release or holdback adjustment of Supplier Retention Payable / Client Retention Receivable", "CONTRACTOR_JOBWORK", "LockOpen", "RETENTION_VOUCHER", "",
         [
             {"key": "party", "label": "Contractor / Client", "required": True, "visible": True, "section": "project_contract_header"},
             {"key": "retention_direction", "label": "Direction", "required": True, "visible": True, "default_value": "PAYABLE_RELEASE", "section": "retention_advance_panel"},
             {"key": "bank_account", "label": "Settlement Bank / Receivable Control", "required": True, "visible": True, "section": "retention_advance_panel"},
         ],
         ["bill_ref", "held_balance", "release_amount"]),
        ("LOAN_DISBURSEMENT", "LOAN_AND_ASSET", "Loan Disbursement Voucher", "Bank loan tranche drawdown crediting loan liability & bank inflow", "BANKING_TREASURY", "Banknote", "LOAN_DISBURSEMENT_DOC", "",
         [
             {"key": "loan_facility", "label": "Loan Facility", "required": True, "visible": True, "section": "facility_asset_header"},
             {"key": "bank_account", "label": "Receiving Bank", "required": True, "visible": True, "section": "facility_asset_header"},
         ],
         ["facility_code", "sanctioned_limit", "drawdown_amount"]),
        ("LOAN_REPAYMENT", "LOAN_AND_ASSET", "Loan Repayment Voucher", "Split EMI / Principal Recovery vs Interest Expense & Bank outflow", "BANKING_TREASURY", "Calculator", "LOAN_REPAYMENT_DOC", "",
         [
             {"key": "loan_facility", "label": "Loan Facility", "required": True, "visible": True, "section": "facility_asset_header"},
             {"key": "bank_account", "label": "Paying Bank", "required": True, "visible": True, "section": "facility_asset_header"},
             {"key": "principal_amount", "label": "Principal Recovery", "required": True, "visible": True, "section": "schedule_valuation_grid"},
             {"key": "interest_amount", "label": "Interest Expense", "required": True, "visible": True, "section": "schedule_valuation_grid"},
         ],
         ["facility", "outstanding_principal", "principal_paid", "interest_paid", "remaining_principal"]),
        ("DEPRECIATION", "LOAN_AND_ASSET", "Depreciation Voucher", "Fixed asset / plant & equipment depreciation schedule posting", "ENTERPRISE_MODERN", "TrendingDown", "DEPRECIATION_DOC", "",
         [{"key": "equipment_asset", "label": "Plant / Fixed Asset", "required": True, "visible": True, "section": "facility_asset_header"}],
         ["asset_code", "book_value", "depreciation_rate", "depreciation_amount", "closing_wdv"]),
        ("PROVISION", "JOURNAL_INTELLIGENCE", "Provision Voucher", "Period-end cost or doubtful debt provision journal", "TALLY_CLASSIC", "ShieldAlert", "PROVISION_DOC", "",
         [{"key": "project", "label": "Project", "required": False, "visible": True, "section": "header_meta"}],
         ["account", "cost_center", "debit", "credit", "narration"]),
        ("ACCRUAL", "JOURNAL_INTELLIGENCE", "Accrual Voucher", "Unbilled revenue / incurred expense cutoff accrual entry", "TALLY_CLASSIC", "Clock", "ACCRUAL_DOC", "",
         [{"key": "project", "label": "Project", "required": False, "visible": True, "section": "header_meta"}],
         ["account", "party", "debit", "credit", "narration"]),
        ("REVERSING_JOURNAL", "JOURNAL_INTELLIGENCE", "Reversing Journal (F10)", "Period-end temporary accrual with automated next-period reversal", "TALLY_CLASSIC", "Repeat", "REVERSING_JOURNAL_DOC", "F10",
         [{"key": "reverse_on_date", "label": "Auto-Reverse Date", "required": True, "visible": True, "section": "header_meta"}],
         ["account", "cost_center", "debit", "credit", "narration"]),
        ("WIP_ADJUSTMENT", "CONSTRUCTION_BILLING", "WIP Adjustment Voucher", "Capitalize or reclassify Project Work-In-Progress across cost codes", "CONSTRUCTION_SITE", "Layers", "WIP_ADJUSTMENT_DOC", "",
         [{"key": "project", "label": "Project", "required": True, "visible": True, "section": "project_contract_header"}],
         ["from_cost_code", "to_cost_code", "wip_amount", "narration"]),
        ("ASSET_ACQUISITION", "LOAN_AND_ASSET", "Asset Acquisition Voucher", "Capitalize plant, machinery or vehicle with input VAT & vendor/bank", "ENTERPRISE_MODERN", "Wrench", "ASSET_ACQUISITION_DOC", "",
         [
             {"key": "equipment_asset", "label": "Asset / Machinery Record", "required": True, "visible": True, "section": "facility_asset_header"},
             {"key": "party", "label": "Equipment Vendor", "required": False, "visible": True, "section": "facility_asset_header"},
         ],
         ["asset_code", "cost", "vat_amount", "capitalized_value"]),
        ("ASSET_DISPOSAL", "LOAN_AND_ASSET", "Asset Disposal Voucher", "Derecognize asset & accumulated depreciation with gain/loss on sale", "ENTERPRISE_MODERN", "Trash2", "ASSET_DISPOSAL_DOC", "",
         [
             {"key": "equipment_asset", "label": "Disposed Asset", "required": True, "visible": True, "section": "facility_asset_header"},
             {"key": "proceeds_amount", "label": "Sale Proceeds", "required": True, "visible": True, "section": "schedule_valuation_grid"},
         ],
         ["asset_code", "original_cost", "accumulated_depr", "proceeds", "gain_or_loss"]),
    ]

    catalog = []
    for (vtype, family, title, subtitle, theme, icon, pdf_code, shortcut, fields, cols) in specs:
        catalog.append(
            {
                "voucher_type": vtype,
                "layout_family": family,
                "title": title,
                "subtitle": subtitle,
                "default_theme_code": theme,
                "icon_name": icon,
                "pdf_template_code": pdf_code,
                "sections_config": _default_sections(family),
                "fields_config": fields,
                "columns_config": [{"key": c, "label": c.replace("_", " ").title(), "visible": True} for c in cols],
                "responsive_config": {
                    "desktop": {"columns": 3, "sticky_header": True, "sticky_totals": True},
                    "tablet": {"columns": 2, "sticky_header": True, "sticky_totals": True},
                    "mobile": {"columns": 1, "sticky_header": False, "sticky_totals": True},
                },
                "keyboard_profile": {"primary_shortcut": shortcut, "save_draft": "Ctrl+S", "submit": "Ctrl+Enter", "inline_ledger": "Alt+C"},
                "default_values": {"theme_code": theme},
            }
        )
    return catalog


VOUCHER_LAYOUT_CATALOG = _build_catalog()
VOUCHER_LAYOUT_BY_TYPE = {row["voucher_type"]: row for row in VOUCHER_LAYOUT_CATALOG}


class VoucherDesignService:
    @staticmethod
    @transaction.atomic
    def ensure_default_design_studio_catalog(company) -> dict:
        themes_created = 0
        blueprints_created = 0

        for idx, t in enumerate(DEFAULT_THEMES_CATALOG):
            obj, created = VoucherThemeConfig.objects.get_or_create(
                company=company,
                voucher_type="ALL",
                theme_code=t["theme_code"],
                defaults={
                    "name": t["name"],
                    "accent_color": t["accent_color"],
                    "header_bg": t["header_bg"],
                    "density": t["density"],
                    "border_radius": t["border_radius"],
                    "font_style": t["font_style"],
                    "icon_name": t["icon_name"],
                    "spacing_scale": t["spacing_scale"],
                    "header_style": t["header_style"],
                    "card_style": t["card_style"],
                    "typography_config": t["typography_config"],
                    "color_tokens": t["color_tokens"],
                    "is_default": idx == 0,
                },
            )
            if created:
                themes_created += 1

        for spec in VOUCHER_LAYOUT_CATALOG:
            existing = VoucherLayoutBlueprint.objects.filter(
                company=company,
                voucher_type=spec["voucher_type"],
                branch__isnull=True,
                user__isnull=True,
                is_default=True,
            ).first()
            if not existing:
                VoucherLayoutBlueprint.objects.create(
                    company=company,
                    voucher_type=spec["voucher_type"],
                    layout_family=spec["layout_family"],
                    title=spec["title"],
                    subtitle=spec["subtitle"],
                    default_theme_code=spec["default_theme_code"],
                    icon_name=spec["icon_name"],
                    sections_config=spec["sections_config"],
                    fields_config=spec["fields_config"],
                    columns_config=spec["columns_config"],
                    responsive_config=spec["responsive_config"],
                    keyboard_profile=spec["keyboard_profile"],
                    default_values=spec["default_values"],
                    pdf_template_code=spec["pdf_template_code"],
                    is_default=True,
                    is_active=True,
                )
                blueprints_created += 1

        return {
            "themes_created": themes_created,
            "blueprints_created": blueprints_created,
            "total_blueprints": VoucherLayoutBlueprint.objects.filter(company=company, branch__isnull=True, user__isnull=True).count(),
        }

    @staticmethod
    def resolve_blueprint_and_theme(*, company, voucher_type: str, user=None, branch=None) -> dict:
        vtype = (voucher_type or "JOURNAL").upper()
        bp = None
        if user:
            bp = VoucherLayoutBlueprint.objects.filter(company=company, voucher_type=vtype, user=user, is_active=True).first()
        if not bp and branch:
            bp = VoucherLayoutBlueprint.objects.filter(company=company, voucher_type=vtype, branch=branch, user__isnull=True, is_active=True).first()
        if not bp:
            bp = VoucherLayoutBlueprint.objects.filter(company=company, voucher_type=vtype, branch__isnull=True, user__isnull=True, is_active=True).first()

        fallback = VOUCHER_LAYOUT_BY_TYPE.get(vtype) or VOUCHER_LAYOUT_BY_TYPE["JOURNAL"]
        bp_payload = (
            {
                "id": str(bp.id),
                "scope": "USER" if bp.user_id else ("BRANCH" if bp.branch_id else "COMPANY"),
                "voucher_type": bp.voucher_type,
                "layout_family": bp.layout_family,
                "title": bp.title,
                "subtitle": bp.subtitle,
                "default_theme_code": bp.default_theme_code,
                "icon_name": bp.icon_name,
                "sections_config": bp.sections_config,
                "fields_config": bp.fields_config,
                "columns_config": bp.columns_config,
                "responsive_config": bp.responsive_config,
                "keyboard_profile": bp.keyboard_profile,
                "default_values": bp.default_values,
                "pdf_template_code": bp.pdf_template_code,
                "version": bp.version,
            }
            if bp
            else {"id": None, "scope": "SYSTEM", "version": 1, **fallback}
        )

        # Resolve Theme Hierarchy: user/voucher -> branch/voucher -> company/voucher -> company/theme_code
        target_theme_code = bp_payload["default_theme_code"]
        theme = None
        if user:
            theme = VoucherThemeConfig.objects.filter(company=company, voucher_type=vtype, user=user).first()
        if not theme and branch:
            theme = VoucherThemeConfig.objects.filter(company=company, voucher_type=vtype, branch=branch, user__isnull=True).first()
        if not theme:
            theme = VoucherThemeConfig.objects.filter(company=company, voucher_type=vtype, branch__isnull=True, user__isnull=True).first()
        if not theme:
            theme = VoucherThemeConfig.objects.filter(company=company, voucher_type="ALL", theme_code=target_theme_code).first()

        sys_theme = next((t for t in DEFAULT_THEMES_CATALOG if t["theme_code"] == target_theme_code), DEFAULT_THEMES_CATALOG[0])
        theme_payload = (
            {
                "id": str(theme.id),
                "theme_code": theme.theme_code,
                "name": theme.name,
                "accent_color": theme.accent_color,
                "header_bg": theme.header_bg,
                "density": theme.density,
                "border_radius": theme.border_radius,
                "font_style": theme.font_style,
                "icon_name": theme.icon_name,
                "spacing_scale": theme.spacing_scale,
                "header_style": theme.header_style,
                "card_style": theme.card_style,
                "typography_config": theme.typography_config or sys_theme["typography_config"],
                "color_tokens": theme.color_tokens or sys_theme["color_tokens"],
                "keyboard_shortcuts_enabled": theme.keyboard_shortcuts_enabled,
            }
            if theme
            else {**sys_theme, "id": None, "keyboard_shortcuts_enabled": True}
        )
        return {"blueprint": bp_payload, "theme": theme_payload, "all_themes": DEFAULT_THEMES_CATALOG}

    @staticmethod
    @transaction.atomic
    def update_blueprint_with_revision(*, blueprint: VoucherLayoutBlueprint, user, data: dict, summary: str = "") -> VoucherLayoutBlueprint:
        updatable = [
            "layout_family", "title", "subtitle", "default_theme_code", "icon_name",
            "sections_config", "fields_config", "columns_config", "responsive_config",
            "keyboard_profile", "default_values", "pdf_template_code", "is_active",
        ]
        for k in updatable:
            if k in data:
                setattr(blueprint, k, data[k])
        blueprint.version += 1
        blueprint.save()
        VoucherDesignRevision.objects.create(
            company=blueprint.company,
            blueprint=blueprint,
            version=blueprint.version,
            changed_by=user,
            change_summary=summary or f"Updated {blueprint.voucher_type} layout to v{blueprint.version}",
            snapshot={k: getattr(blueprint, k) for k in updatable},
        )
        return blueprint

    @staticmethod
    @transaction.atomic
    def restore_blueprint_revision(*, blueprint: VoucherLayoutBlueprint, revision: VoucherDesignRevision, user) -> VoucherLayoutBlueprint:
        return VoucherDesignService.update_blueprint_with_revision(
            blueprint=blueprint,
            user=user,
            data=revision.snapshot,
            summary=f"Restored v{revision.version}",
        )

    @staticmethod
    def get_functional_context(*, company, voucher_type: str, project_id: str | None = None, party_id: str | None = None) -> dict:
        """
        Loads function-specific master data, balances & operational references needed by each
        specialized voucher screen without calling extra N+1 endpoints on mount.
        """
        vtype = (voucher_type or "JOURNAL").upper()
        ctx: dict = {"voucher_type": vtype}

        # 1. Treasury / Cash & Bank Accounts with live GL balances
        cash_bank_accs = Account.objects.filter(
            company=company,
            is_group=False,
            is_active=True,
            control_role__in=[Account.ControlRole.CASH, Account.ControlRole.BANK],
        ).order_by("code")
        cb_rows = []
        for a in cash_bank_accs:
            agg = LedgerEntry.objects.filter(company=company, account=a).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
            bal = (a.opening_debit - a.opening_credit) + (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
            cb_rows.append({"id": str(a.id), "code": a.code, "name": a.name, "role": a.control_role, "balance": str(bal)})
        ctx["cash_bank_accounts"] = cb_rows

        from apps.banking.bank_txn_services import BankAccountQueryService
        from apps.banking.models import BankAccount, CashAccount
        from apps.treasury.cheques.gl_helpers import get_bank_transfer_in_transit_account

        active_bank_objs = BankAccountQueryService.list_eligible_accounts(company=company)[:50]
        ctx["bank_accounts"] = [BankAccountQueryService.serialize_selector_row(b) for b in active_bank_objs]
        ctx["bank_facilities_accounts"] = [
            {
                "id": str(b.id),
                "code": b.account_name,
                "name": f"{b.bank_branch.bank.name} — {b.account_name}",
                "account_no": b.account_number_masked,
                "gl_account_id": str(b.gl_account_id),
            }
            for b in active_bank_objs
        ]
        cash_rows = []
        for ca in CashAccount.objects.select_related("gl_account").filter(company=company, is_active=True, is_frozen=False)[:50]:
            agg = LedgerEntry.objects.filter(company=company, account=ca.gl_account).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
            bal = (ca.gl_account.opening_debit - ca.gl_account.opening_credit) + (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
            cash_rows.append(
                {
                    "id": str(ca.id),
                    "code": ca.code,
                    "name": ca.name,
                    "cash_type": ca.cash_type,
                    "currency": ca.currency,
                    "gl_account": str(ca.gl_account_id),
                    "balance": str(bal),
                }
            )
        ctx["cash_accounts"] = cash_rows
        if vtype == "CONTRA":
            it_acc = get_bank_transfer_in_transit_account(company)
            ctx["in_transit_account"] = {"id": str(it_acc.id), "code": it_acc.code, "name": it_acc.name}

        # 2. Party Open Invoices & Advances (for Payment, Receipt, Billing, Advances, Retention)
        if vtype in ("PAYMENT", "RECEIPT", "SUBCONTRACTOR_BILL", "CLIENT_RA_BILL", "SUPPLIER_ADVANCE", "CUSTOMER_ADVANCE", "RETENTION", "DEBIT_NOTE", "CREDIT_NOTE"):
            from apps.party_hub.models import OpenItem
            oi_qs = OpenItem.objects.select_related("party", "project").filter(
                company=company, is_unallocated_credit=False
            ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.REVERSED, OpenItem.Status.WRITTEN_OFF])
            if party_id:
                oi_qs = oi_qs.filter(party_id=party_id)
            ctx["open_invoices"] = [
                {
                    "id": str(o.id),
                    "party_id": str(o.party_id),
                    "party_name": o.party.name,
                    "hub_side": o.hub_side,
                    "document_no": o.document_no,
                    "document_date": o.document_date.isoformat(),
                    "due_date": o.due_date.isoformat(),
                    "original_amount": str(o.original_amount),
                    "remaining_amount": str(o.remaining_amount),
                }
                for o in oi_qs[:150]
            ]
            adv_qs = AdvanceRecord.objects.select_related("party").filter(company=company).exclude(
                status__in=[AdvanceRecord.Status.SETTLED, AdvanceRecord.Status.CANCELLED]
            )
            if party_id:
                adv_qs = adv_qs.filter(party_id=party_id)
            ctx["open_advances"] = [
                {
                    "id": str(a.id),
                    "advance_no": a.advance_no,
                    "party_id": str(a.party_id),
                    "party_name": a.party.name,
                    "advance_type": a.advance_type,
                    "remaining_amount": str(a.remaining_amount),
                }
                for a in adv_qs[:100]
                if a.remaining_amount > Decimal("0.00")
            ]

        # 3. Warehouses, Items & Live Stock On-Hand + POs / GRNs
        if vtype in ("PURCHASE", "SALES", "DEBIT_NOTE", "CREDIT_NOTE", "PURCHASE_ORDER", "SALES_ORDER", "RECEIPT_NOTE", "DELIVERY_NOTE", "REJECTIONS_IN", "REJECTIONS_OUT", "STOCK_JOURNAL", "PHYSICAL_STOCK", "MATERIAL_IN", "MATERIAL_OUT", "MANUFACTURING_JOURNAL", "MATERIAL_PURCHASE", "MATERIAL_ISSUE", "MATERIAL_RETURN"):
            from apps.inventory.models import GoodsReceiptNote, ItemMaster, StockMovement, Warehouse
            from apps.procurement.models import PurchaseOrder
            ctx["warehouses"] = [
                {"id": str(w.id), "code": w.code, "name": w.name, "store_kind": w.store_kind}
                for w in Warehouse.objects.filter(company=company, is_active=True)[:50]
            ]
            ctx["items"] = [
                {
                    "id": str(it.id),
                    "item_code": it.item_code,
                    "name": it.name,
                    "unit": it.primary_unit.code if it.primary_unit else "",
                    "standard_rate": str(it.standard_rate),
                    "tax_rate": str(it.tax_rate),
                }
                for it in ItemMaster.objects.select_related("primary_unit").filter(company=company, is_active=True)[:200]
            ]
            stock_rows = StockMovement.objects.filter(company=company).values("warehouse_id", "item_id").annotate(qty=Sum("quantity_delta"))
            ctx["stock_balances"] = [
                {"warehouse_id": str(r["warehouse_id"]), "item_id": str(r["item_id"]), "qty_on_hand": str(r["qty"] or Decimal("0.000"))}
                for r in stock_rows
            ]
            ctx["purchase_orders"] = [
                {"id": str(po.id), "po_number": po.po_number, "vendor_id": str(po.vendor.party_id), "vendor_name": po.vendor.party.name, "total_amount": str(po.total_amount), "status": po.status}
                for po in PurchaseOrder.objects.select_related("vendor__party").filter(company=company).order_by("-po_date")[:60]
            ]
            ctx["grns"] = [
                {"id": str(g.id), "grn_number": g.grn_number, "vendor_id": str(g.vendor_id), "vendor_name": g.vendor.name, "warehouse_id": str(g.warehouse_id), "total_amount": str(g.total_amount)}
                for g in GoodsReceiptNote.objects.select_related("vendor").filter(company=company).order_by("-grn_date")[:60]
            ]

        # 4. HR / Payroll / Employees / Staff Loans & Advances
        if vtype in ("PAYROLL", "LABOR_PAYMENT", "STAFF_ADVANCE", "STAFF_SETTLEMENT", "SITE_EXPENSE"):
            ctx["employees"] = [
                {
                    "id": str(e.id),
                    "employee_code": e.employee_code,
                    "full_name": e.full_name,
                    "designation": e.designation,
                    "monthly_salary": str(e.basic_salary),
                    "daily_wage_rate": str((e.basic_salary / Decimal("30")).quantize(Decimal("0.01"))),
                }
                for e in EmployeeProfile.objects.filter(company=company, is_active=True)[:150]
            ]
            ctx["payroll_liabilities"] = [
                {
                    "id": str(pl.id),
                    "payroll_ref": pl.payroll_ref,
                    "employee_id": str(pl.employee_id),
                    "employee_name": pl.employee.full_name,
                    "outstanding_amount": str(pl.outstanding_amount),
                }
                for pl in PayrollLiability.objects.select_related("employee").filter(company=company).exclude(status=PayrollLiability.Status.SETTLED)[:100]
                if pl.outstanding_amount > Decimal("0.00")
            ]
            ctx["staff_loans"] = [
                {
                    "id": str(sl.id),
                    "loan_no": sl.loan_no,
                    "employee_id": str(sl.employee_id),
                    "employee_name": sl.employee.full_name,
                    "remaining_principal": str(sl.remaining_principal),
                }
                for sl in StaffLoan.objects.select_related("employee").filter(company=company).exclude(status=StaffLoan.Status.SETTLED)[:100]
                if sl.remaining_principal > Decimal("0.00")
            ]

        # 5. Loans & Fixed Assets / Equipment
        if vtype in ("LOAN_DISBURSEMENT", "LOAN_REPAYMENT", "DEPRECIATION", "ASSET_ACQUISITION", "ASSET_DISPOSAL"):
            from apps.loans.models import BankFacility
            facs = []
            for f in BankFacility.objects.select_related("linked_liability_account", "linked_interest_account", "bank_account").filter(company=company):
                agg = LedgerEntry.objects.filter(company=company, account=f.linked_liability_account).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
                out_prin = (agg["c"] or Decimal("0.00")) - (agg["d"] or Decimal("0.00"))
                facs.append(
                    {
                        "id": str(f.id),
                        "facility_code": f.facility_code,
                        "facility_name": f.facility_name,
                        "facility_type": f.facility_type,
                        "sanctioned_limit": str(f.sanctioned_limit),
                        "interest_rate": str(f.effective_interest_rate),
                        "outstanding_principal": str(max(Decimal("0.00"), out_prin)),
                        "liability_account_id": str(f.linked_liability_account_id),
                        "interest_account_id": str(f.linked_interest_account_id),
                    }
                )
            ctx["loan_facilities"] = facs
            ctx["equipment_assets"] = [
                {
                    "id": str(eq.id),
                    "code": eq.code,
                    "name": eq.name,
                    "category": eq.asset_category,
                    "hourly_rate": str(eq.hourly_rate),
                    "project_id": None,
                }
                for eq in EquipmentAsset.objects.filter(company=company, is_active=True)[:100]
            ]

        return ctx

