import json
from datetime import date, timedelta
from decimal import Decimal
from django.db.models import DecimalField, Q, Sum, Value
from django.db.models.functions import Coalesce
from django.utils import timezone

from apps.accounts_rbac.constants import Permissions
from apps.accounts_rbac.models import ApprovalAuthority
from apps.audit.models import AuditEvent
from apps.accounting.models import (
    Account,
    LedgerEntry,
    PartyLedgerEntry,
    Voucher,
    VoucherRegisterViewConfig,
)
from apps.document_engine.models import DocumentAuditLog, DocumentDeliveryLog, DocumentRecord, DocumentVersion
from apps.tenancy.models import FiscalYear, TaxConfig
from .posting_engine import PostingRuleEngine


REGISTER_SCOPE_TYPES: dict[str, list[str]] = {
    "PAYMENT": [
        Voucher.VoucherType.PAYMENT,
        Voucher.VoucherType.LABOR_PAYMENT,
        Voucher.VoucherType.SITE_PETTY_CASH,
        Voucher.VoucherType.SITE_EXPENSE,
        Voucher.VoucherType.SITE_CASH,
        Voucher.VoucherType.DIRECT_EXPENSE,
        Voucher.VoucherType.INDIRECT_EXPENSE,
        Voucher.VoucherType.EQUIPMENT_HIRE,
        Voucher.VoucherType.FUEL_EXPENSE,
        Voucher.VoucherType.FUEL,
        Voucher.VoucherType.STAFF_ADVANCE,
        Voucher.VoucherType.LOAN_REPAYMENT,
    ],
    "RECEIPT": [
        Voucher.VoucherType.RECEIPT,
        Voucher.VoucherType.MOBILIZATION_ADVANCE,
        Voucher.VoucherType.MACHINE_INCOME,
        Voucher.VoucherType.LOAN_DISBURSEMENT,
        Voucher.VoucherType.BANK_INTEREST,
    ],
    "JOURNAL": [
        Voucher.VoucherType.JOURNAL,
        Voucher.VoucherType.PROVISION,
        Voucher.VoucherType.ACCRUAL,
        Voucher.VoucherType.DEPRECIATION,
        Voucher.VoucherType.RECTIFICATION,
        Voucher.VoucherType.FX_ADJUSTMENT,
        Voucher.VoucherType.REVERSAL,
        Voucher.VoucherType.REVERSING_JOURNAL,
        Voucher.VoucherType.YEAR_END_CLOSING,
        Voucher.VoucherType.OPENING_BALANCE,
        Voucher.VoucherType.ADVANCE_RECOVERY,
        Voucher.VoucherType.STAFF_SETTLEMENT,
        Voucher.VoucherType.WAGE_ACCRUAL,
        Voucher.VoucherType.PAYROLL,
        Voucher.VoucherType.WAGES,
        Voucher.VoucherType.WIP_ADJUSTMENT,
        Voucher.VoucherType.PROJECT_COST_TRANSFER,
    ],
    "CONTRA": [Voucher.VoucherType.CONTRA],
    "PURCHASE": [
        Voucher.VoucherType.PURCHASE,
        Voucher.VoucherType.MATERIAL_PURCHASE,
        Voucher.VoucherType.SITE_PURCHASE,
        Voucher.VoucherType.SUBCONTRACTOR_BILL,
        Voucher.VoucherType.PURCHASE_ORDER,
    ],
    "SALES": [
        Voucher.VoucherType.SALES,
        Voucher.VoucherType.CLIENT_RA_BILL,
        Voucher.VoucherType.VARIATION_ORDER,
        Voucher.VoucherType.SALES_ORDER,
    ],
    "DEBIT_NOTE": [Voucher.VoucherType.DEBIT_NOTE],
    "CREDIT_NOTE": [Voucher.VoucherType.CREDIT_NOTE],
    "INVENTORY": [
        Voucher.VoucherType.RECEIPT_NOTE,
        Voucher.VoucherType.DELIVERY_NOTE,
        Voucher.VoucherType.REJECTIONS_IN,
        Voucher.VoucherType.REJECTIONS_OUT,
        Voucher.VoucherType.STOCK_JOURNAL,
        Voucher.VoucherType.PHYSICAL_STOCK,
        Voucher.VoucherType.MATERIAL_IN,
        Voucher.VoucherType.MATERIAL_OUT,
        Voucher.VoucherType.MANUFACTURING_JOURNAL,
        Voucher.VoucherType.MATERIAL_ISSUE,
        Voucher.VoucherType.MATERIAL_CONSUMPTION,
        Voucher.VoucherType.MATERIAL_RETURN,
        Voucher.VoucherType.MATERIAL_PURCHASE,
    ],
    "CONSTRUCTION": [
        Voucher.VoucherType.MATERIAL_PURCHASE,
        Voucher.VoucherType.SITE_PURCHASE,
        Voucher.VoucherType.DIRECT_EXPENSE,
        Voucher.VoucherType.LABOR_PAYMENT,
        Voucher.VoucherType.WAGES,
        Voucher.VoucherType.SUBCONTRACTOR_BILL,
        Voucher.VoucherType.CLIENT_RA_BILL,
        Voucher.VoucherType.MOBILIZATION_ADVANCE,
        Voucher.VoucherType.ADVANCE_RECOVERY,
        Voucher.VoucherType.RETENTION,
        Voucher.VoucherType.RETENTION_RECEIVABLE,
        Voucher.VoucherType.RETENTION_PAYABLE,
        Voucher.VoucherType.VARIATION_ORDER,
        Voucher.VoucherType.EQUIPMENT_HIRE,
        Voucher.VoucherType.MACHINE_INCOME,
        Voucher.VoucherType.FUEL_EXPENSE,
        Voucher.VoucherType.FUEL,
        Voucher.VoucherType.SITE_PETTY_CASH,
        Voucher.VoucherType.SITE_EXPENSE,
        Voucher.VoucherType.SITE_CASH,
        Voucher.VoucherType.MATERIAL_ISSUE,
        Voucher.VoucherType.MATERIAL_CONSUMPTION,
        Voucher.VoucherType.MATERIAL_RETURN,
        Voucher.VoucherType.PROJECT_COST_TRANSFER,
        Voucher.VoucherType.WIP_ADJUSTMENT,
        Voucher.VoucherType.WAGE_ACCRUAL,
    ],
}

VOUCHER_TO_DOCTYPE: dict[str, str] = {
    Voucher.VoucherType.PAYMENT: "PAYMENT_VOUCHER",
    Voucher.VoucherType.LABOR_PAYMENT: "PAYMENT_VOUCHER",
    Voucher.VoucherType.DIRECT_EXPENSE: "PAYMENT_VOUCHER",
    Voucher.VoucherType.INDIRECT_EXPENSE: "PAYMENT_VOUCHER",
    Voucher.VoucherType.EQUIPMENT_HIRE: "PAYMENT_VOUCHER",
    Voucher.VoucherType.FUEL_EXPENSE: "PAYMENT_VOUCHER",
    Voucher.VoucherType.FUEL: "PAYMENT_VOUCHER",
    Voucher.VoucherType.SITE_PETTY_CASH: "PAYMENT_VOUCHER",
    Voucher.VoucherType.SITE_CASH: "PAYMENT_VOUCHER",
    Voucher.VoucherType.STAFF_ADVANCE: "PAYMENT_VOUCHER",
    Voucher.VoucherType.LOAN_REPAYMENT: "PAYMENT_VOUCHER",
    Voucher.VoucherType.SITE_EXPENSE: "SITE_EXPENSE_STATEMENT",
    Voucher.VoucherType.RECEIPT: "RECEIPT_VOUCHER",
    Voucher.VoucherType.MACHINE_INCOME: "RECEIPT_VOUCHER",
    Voucher.VoucherType.MOBILIZATION_ADVANCE: "RECEIPT_VOUCHER",
    Voucher.VoucherType.LOAN_DISBURSEMENT: "RECEIPT_VOUCHER",
    Voucher.VoucherType.CONTRA: "CONTRA_VOUCHER",
    Voucher.VoucherType.PURCHASE: "PURCHASE_INVOICE",
    Voucher.VoucherType.MATERIAL_PURCHASE: "PURCHASE_INVOICE",
    Voucher.VoucherType.SITE_PURCHASE: "PURCHASE_INVOICE",
    Voucher.VoucherType.PURCHASE_ORDER: "PURCHASE_ORDER",
    Voucher.VoucherType.SUBCONTRACTOR_BILL: "CONTRACTOR_PAYMENT_CERT",
    Voucher.VoucherType.SALES: "SALES_INVOICE",
    Voucher.VoucherType.SALES_ORDER: "SALES_ORDER",
    Voucher.VoucherType.CLIENT_RA_BILL: "RA_BILL",
    Voucher.VoucherType.VARIATION_ORDER: "RA_BILL",
    Voucher.VoucherType.DEBIT_NOTE: "DEBIT_NOTE",
    Voucher.VoucherType.CREDIT_NOTE: "CREDIT_NOTE",
    Voucher.VoucherType.RECEIPT_NOTE: "GOODS_RECEIPT_NOTE",
    Voucher.VoucherType.DELIVERY_NOTE: "DELIVERY_CHALLAN",
    Voucher.VoucherType.MATERIAL_ISSUE: "MATERIAL_ISSUE_NOTE",
    Voucher.VoucherType.MATERIAL_RETURN: "MATERIAL_RETURN_NOTE",
}

DEFAULT_REGISTER_COLUMNS = [
    {"key": "checkbox", "label": "", "visible": True, "width": 40, "order": 0, "pinned": "left"},
    {"key": "voucher_no", "label": "Voucher No.", "visible": True, "width": 148, "order": 1, "pinned": "left"},
    {"key": "date", "label": "Date (AD / BS)", "visible": True, "width": 152, "order": 2, "pinned": None},
    {"key": "voucher_type", "label": "Voucher Type", "visible": True, "width": 150, "order": 3, "pinned": None},
    {"key": "party", "label": "Party / Account", "visible": True, "width": 195, "order": 4, "pinned": None},
    {"key": "narration", "label": "Narration", "visible": True, "width": 220, "order": 5, "pinned": None},
    {"key": "project_site", "label": "Project / Site", "visible": True, "width": 150, "order": 6, "pinned": None},
    {"key": "debit", "label": "Debit", "visible": True, "width": 124, "order": 7, "pinned": None},
    {"key": "credit", "label": "Credit", "visible": True, "width": 124, "order": 8, "pinned": None},
    {"key": "reference", "label": "Reference", "visible": True, "width": 136, "order": 9, "pinned": None},
    {"key": "prepared_by", "label": "Prepared By", "visible": True, "width": 120, "order": 10, "pinned": None},
    {"key": "approved_by", "label": "Approved By", "visible": True, "width": 120, "order": 11, "pinned": None},
    {"key": "status", "label": "Status", "visible": True, "width": 124, "order": 12, "pinned": None},
    {"key": "actions", "label": "Actions", "visible": True, "width": 148, "order": 13, "pinned": "right"},
]

ALLOWED_CONDITION_FIELDS = {
    "voucher_no": "voucher_no",
    "voucher_type": "voucher_type",
    "status": "status",
    "party_name": "party_name",
    "narration": "narration",
    "reference_no": "reference_no",
    "supplier_invoice_no": "supplier_invoice_no",
    "voucher_date": "voucher_date",
    "bs_date": "bs_date",
    "entry_mode": "entry_mode",
    "tax_amount": "tax_amount",
    "tds_amount": "tds_amount",
    "retention_amount": "retention_amount",
    "debit": "computed_debit",
    "credit": "computed_credit",
}


def _resolve_date_preset(preset: str, company) -> tuple[date | None, date | None]:
    today = timezone.localdate()
    p = (preset or "").upper()
    if p == "TODAY":
        return today, today
    if p == "YESTERDAY":
        y = today - timedelta(days=1)
        return y, y
    if p == "THIS_WEEK":
        start = today - timedelta(days=today.weekday())
        return start, today
    if p == "THIS_MONTH":
        start = today.replace(day=1)
        return start, today
    if p == "PREVIOUS_MONTH":
        first_this = today.replace(day=1)
        last_prev = first_this - timedelta(days=1)
        first_prev = last_prev.replace(day=1)
        return first_prev, last_prev
    if p == "FINANCIAL_YEAR":
        fy = (
            FiscalYear.objects.filter(company=company, is_current=True).first()
            or FiscalYear.objects.filter(company=company).order_by("-start_date").first()
        )
        if fy:
            return fy.start_date, fy.end_date
    return None, None


def _build_condition_q(cond: dict) -> Q | None:
    field_key = str(cond.get("field") or "")
    op = str(cond.get("operator") or "contains").lower()
    val = cond.get("value")
    if field_key not in ALLOWED_CONDITION_FIELDS or val in (None, ""):
        return None
    orm_field = ALLOWED_CONDITION_FIELDS[field_key]
    if field_key in ("tax_amount", "tds_amount", "retention_amount", "debit", "credit"):
        try:
            val = Decimal(str(val))
        except Exception:
            return None
    if op == "eq":
        return Q(**{f"{orm_field}__iexact": val}) if isinstance(val, str) else Q(**{orm_field: val})
    if op == "neq":
        return ~(Q(**{f"{orm_field}__iexact": val}) if isinstance(val, str) else Q(**{orm_field: val}))
    if op == "contains":
        return Q(**{f"{orm_field}__icontains": str(val)})
    if op == "gt":
        return Q(**{f"{orm_field}__gt": val})
    if op == "gte":
        return Q(**{f"{orm_field}__gte": val})
    if op == "lt":
        return Q(**{f"{orm_field}__lt": val})
    if op == "lte":
        return Q(**{f"{orm_field}__lte": val})
    return None


class VoucherRegisterService:
    """Server-authoritative service for Enterprise Voucher Register queries & 6-tab inspection."""

    @staticmethod
    def filter_register_queryset(qs, params, company):
        qs = qs.annotate(
            computed_debit=Coalesce(Sum("lines__debit"), Value(Decimal("0.00")), output_field=DecimalField(max_digits=18, decimal_places=2)),
            computed_credit=Coalesce(Sum("lines__credit"), Value(Decimal("0.00")), output_field=DecimalField(max_digits=18, decimal_places=2)),
        )

        # Date presets & explicit ranges
        date_preset = params.get("date_preset")
        date_from = params.get("date_from")
        date_to = params.get("date_to")
        if date_preset and date_preset.upper() != "CUSTOM":
            p_from, p_to = _resolve_date_preset(date_preset, company)
            if p_from and not date_from:
                date_from = p_from.isoformat()
            if p_to and not date_to:
                date_to = p_to.isoformat()

        if date_from:
            qs = qs.filter(voucher_date__gte=date.fromisoformat(date_from))
        if date_to:
            qs = qs.filter(voucher_date__lte=date.fromisoformat(date_to))
        if params.get("fiscal_year"):
            qs = qs.filter(fiscal_year_id=params["fiscal_year"])

        # Register scope & voucher filters
        scope = (params.get("register_scope") or "").upper()
        if scope and scope != "ALL" and scope in REGISTER_SCOPE_TYPES:
            qs = qs.filter(voucher_type__in=REGISTER_SCOPE_TYPES[scope])

        if params.get("voucher_type"):
            vtypes = [x.strip() for x in str(params["voucher_type"]).split(",") if x.strip()]
            if len(vtypes) == 1:
                qs = qs.filter(voucher_type=vtypes[0])
            elif vtypes:
                qs = qs.filter(voucher_type__in=vtypes)

        if params.get("status"):
            statuses = [x.strip() for x in str(params["status"]).split(",") if x.strip()]
            if len(statuses) == 1:
                qs = qs.filter(status=statuses[0])
            elif statuses:
                qs = qs.filter(status__in=statuses)

        if params.get("entry_mode"):
            qs = qs.filter(entry_mode=params["entry_mode"])
        if params.get("provisional_kind"):
            qs = qs.filter(provisional_kind=params["provisional_kind"])
        if str(params.get("is_optional", "")).lower() in ("true", "1"):
            qs = qs.filter(Q(provisional_kind=Voucher.ProvisionalKind.OPTIONAL) | Q(status=Voucher.Status.OPTIONAL))
        if str(params.get("is_post_dated", "")).lower() in ("true", "1"):
            qs = qs.filter(Q(provisional_kind=Voucher.ProvisionalKind.POST_DATED) | Q(status=Voucher.Status.POST_DATED))
        if str(params.get("is_reversed", "")).lower() in ("true", "1"):
            qs = qs.filter(Q(status=Voucher.Status.REVERSED) | Q(reversed_from__isnull=False))

        if params.get("amount_min"):
            qs = qs.filter(computed_debit__gte=Decimal(str(params["amount_min"])))
        if params.get("amount_max"):
            qs = qs.filter(computed_debit__lte=Decimal(str(params["amount_max"])))

        # Accounting filters
        if params.get("ledger"):
            qs = qs.filter(lines__account_id=params["ledger"])
        if params.get("parent_account"):
            qs = qs.filter(lines__account__parent_id=params["parent_account"])
        if params.get("party"):
            qs = qs.filter(Q(party_id=params["party"]) | Q(lines__party_id=params["party"]))
        if params.get("customer"):
            qs = qs.filter(party_id=params["customer"], party__party_type="CUSTOMER")
        if params.get("supplier"):
            qs = qs.filter(party_id=params["supplier"], party__party_type="SUPPLIER")
        if params.get("dr_cr"):
            side = params["dr_cr"].upper()
            if side == "DEBIT":
                qs = qs.filter(lines__debit__gt=0)
            elif side == "CREDIT":
                qs = qs.filter(lines__credit__gt=0)
        if params.get("tax_status"):
            ts = params["tax_status"].upper()
            if ts == "VAT_APPLICABLE":
                qs = qs.filter(tax_amount__gt=0)
            elif ts == "TDS_APPLICABLE":
                qs = qs.filter(tds_amount__gt=0)
            elif ts == "TAX_FREE":
                qs = qs.filter(tax_amount=0, tds_amount=0)

        # Construction & Org filters
        if params.get("branch"):
            qs = qs.filter(branch_id=params["branch"])
        if params.get("project"):
            qs = qs.filter(Q(project_id=params["project"]) | Q(lines__project_id=params["project"]))
        if params.get("site"):
            qs = qs.filter(Q(site_id=params["site"]) | Q(lines__site_id=params["site"]))
        if params.get("cost_code"):
            qs = qs.filter(lines__cost_code_id=params["cost_code"])
        if params.get("boq_item"):
            qs = qs.filter(lines__boq_item_id=params["boq_item"])
        if params.get("contractor"):
            qs = qs.filter(Q(lines__contractor_id=params["contractor"]) | Q(party_id=params["contractor"]))
        if params.get("department"):
            qs = qs.filter(Q(department_id=params["department"]) | Q(lines__department_id=params["department"]))

        # User filters
        if params.get("prepared_by"):
            qs = qs.filter(created_by_id=params["prepared_by"])
        if params.get("approved_by"):
            qs = qs.filter(approved_by_id=params["approved_by"])
        if params.get("posted_by"):
            qs = qs.filter(posted_by_id=params["posted_by"])
        if params.get("assigned_reviewer"):
            qs = qs.filter(assigned_reviewer_id=params["assigned_reviewer"])

        # Search options
        if params.get("exact_voucher_no"):
            qs = qs.filter(voucher_no__iexact=params["exact_voucher_no"].strip())
        if params.get("voucher_no"):
            qs = qs.filter(voucher_no__icontains=params["voucher_no"].strip())
        if params.get("search_party"):
            sp = params["search_party"].strip()
            qs = qs.filter(Q(party_name__icontains=sp) | Q(party__name__icontains=sp))
        if params.get("search_narration"):
            qs = qs.filter(narration__icontains=params["search_narration"].strip())
        if params.get("search_reference"):
            sr = params["search_reference"].strip()
            qs = qs.filter(Q(reference_no__icontains=sr) | Q(supplier_invoice_no__icontains=sr))
        if params.get("search"):
            s = params["search"].strip()
            qs = qs.filter(
                Q(voucher_no__icontains=s)
                | Q(party_name__icontains=s)
                | Q(party__name__icontains=s)
                | Q(narration__icontains=s)
                | Q(reference_no__icontains=s)
                | Q(supplier_invoice_no__icontains=s)
            )

        # Advanced AND/OR conditions
        raw_conds = params.get("conditions")
        if raw_conds:
            try:
                cond_list = json.loads(raw_conds) if isinstance(raw_conds, str) else raw_conds
            except Exception:
                cond_list = []
            if isinstance(cond_list, list) and cond_list:
                logic_op = str(params.get("logic_operator") or "AND").upper()
                combined_q = Q()
                first = True
                for item in cond_list[:12]:
                    if not isinstance(item, dict):
                        continue
                    q_part = _build_condition_q(item)
                    if q_part is None:
                        continue
                    if first:
                        combined_q = q_part
                        first = False
                    elif logic_op == "OR":
                        combined_q |= q_part
                    else:
                        combined_q &= q_part
                if not first:
                    qs = qs.filter(combined_q)

        qs = qs.distinct()

        # Sorting
        sort_map = {
            "voucher_date": "voucher_date",
            "voucher_no": "voucher_no",
            "voucher_type": "voucher_type",
            "party": "party_name",
            "status": "status",
            "debit": "computed_debit",
            "credit": "computed_credit",
            "created_at": "created_at",
        }
        sort_by = sort_map.get(params.get("sort_by", ""), "voucher_date")
        sort_dir = "-" if str(params.get("sort_dir") or "desc").lower() == "desc" else ""
        if sort_by == "voucher_date":
            qs = qs.order_by(f"{sort_dir}voucher_date", f"{sort_dir}created_at")
        else:
            qs = qs.order_by(f"{sort_dir}{sort_by}", "-voucher_date")

        return qs

    @staticmethod
    def compute_register_summary(qs) -> dict:
        agg = qs.aggregate(
            total_debit=Coalesce(Sum("computed_debit"), Value(Decimal("0.00")), output_field=DecimalField(max_digits=18, decimal_places=2)),
            total_credit=Coalesce(Sum("computed_credit"), Value(Decimal("0.00")), output_field=DecimalField(max_digits=18, decimal_places=2)),
        )
        total_count = qs.count()
        pending_count = qs.filter(
            status__in=[Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW, Voucher.Status.RETURNED, Voucher.Status.ON_HOLD]
        ).count()
        approved_count = qs.filter(status=Voucher.Status.APPROVED).count()
        posted_count = qs.filter(status=Voucher.Status.POSTED).count()
        draft_count = qs.filter(status=Voucher.Status.DRAFT).count()
        return {
            "filtered_count": total_count,
            "total_debit": str(agg["total_debit"]),
            "total_credit": str(agg["total_credit"]),
            "status_counts": {
                "all": total_count,
                "draft": draft_count,
                "pending_review": pending_count,
                "approved": approved_count,
                "posted": posted_count,
            },
        }

    @staticmethod
    def build_logic_payload(voucher: Voucher) -> dict:
        lines = list(
            voucher.lines.select_related(
                "account__parent",
                "party",
                "project",
                "site",
                "department",
                "cost_center",
                "cost_code",
                "boq_item",
                "advance_record",
                "payroll_liability",
                "staff_loan",
            ).prefetch_related("cost_allocations__cost_center", "cost_allocations__project")
        )
        plan = PostingRuleEngine.build_voucher_accounting_plan(
            company=voucher.company,
            voucher_type=voucher.voucher_type,
            voucher_date=voucher.voucher_date,
            lines_data=[
                {
                    "account": l.account,
                    "debit": l.debit,
                    "credit": l.credit,
                    "party": l.party,
                    "project": l.project or voucher.project,
                    "cost_center": l.cost_center or voucher.cost_center,
                    "advance_record": l.advance_record,
                    "payroll_liability": l.payroll_liability,
                    "staff_loan": l.staff_loan,
                    "cost_allocations": [
                        {
                            "allocation_mode": ca.allocation_mode,
                            "percentage": ca.percentage,
                            "amount": ca.amount,
                        }
                        for ca in l.cost_allocations.all()
                    ],
                }
                for l in lines
            ],
            party=voucher.party,
            supplier_invoice_no=voucher.supplier_invoice_no,
            is_control_override=voucher.is_control_override,
            voucher_id=voucher.id,
            voucher_type_config=voucher.voucher_type_config,
            inventory_items=[
                {
                    "item": inv.item,
                    "warehouse": inv.warehouse,
                    "target_warehouse": inv.target_warehouse,
                    "quantity": inv.quantity,
                    "rate": inv.rate,
                    "amount": inv.amount,
                }
                for inv in voucher.inventory_items.select_related("item", "warehouse", "target_warehouse").all()
            ],
            bill_wise_allocations=voucher.bill_wise_allocations_payload,
            operational_payload=voucher.operational_payload,
        )

        # Determine strict posting state label (never mislabel unposted as posted!)
        if voucher.status == Voucher.Status.POSTED:
            posting_state = "ACTUAL_POSTED"
            posting_state_label = "Actual Posted General Ledger Transaction"
        elif voucher.status == Voucher.Status.REVERSED:
            posting_state = "REVERSED"
            posting_state_label = "Posted & Reversed Transaction"
        elif voucher.provisional_kind != Voucher.ProvisionalKind.REGULAR or voucher.status in (
            Voucher.Status.OPTIONAL,
            Voucher.Status.MEMORANDUM,
            Voucher.Status.POST_DATED,
        ):
            posting_state = "PROVISIONAL"
            posting_state_label = f"Provisional Entry ({voucher.provisional_kind}) — Non-Posting"
        elif voucher.status in (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW, Voucher.Status.APPROVED):
            posting_state = "PENDING_APPROVAL"
            posting_state_label = f"Pending Posting ({voucher.get_status_display()}) — Not Yet in GL"
        else:
            posting_state = "UNPOSTED_DRAFT"
            posting_state_label = f"Unposted {voucher.get_status_display()} Preview — Not Posted to GL"

        gl_entries = list(
            LedgerEntry.objects.select_related(
                "account__parent",
                "party",
                "project",
                "site",
                "cost_center",
                "cost_code",
                "boq_item",
            )
            .filter(voucher=voucher)
            .order_by("posting_date", "posted_at", "id")
        )
        gl_by_line = {e.voucher_line_id: e for e in gl_entries}

        # Reconcile posted journal lines directly from LedgerEntry when posted
        journal_lines = []
        preview_by_idx = {row["line_no"]: row for row in plan.get("journal_preview", [])}
        for idx, l in enumerate(lines, start=1):
            p_row = preview_by_idx.get(idx, {})
            gl = gl_by_line.get(l.id)
            debit_val = gl.debit if gl else l.debit
            credit_val = gl.credit if gl else l.credit
            journal_lines.append(
                {
                    "line_no": l.line_no,
                    "ledger_entry_id": str(gl.id) if gl else None,
                    "is_actual_gl": bool(gl),
                    "account_id": str(l.account_id),
                    "account_code": l.account.code,
                    "account_name": l.account.name,
                    "account_group": l.account.parent.name if l.account.parent else l.account.account_type,
                    "account_type": l.account.account_type,
                    "control_role": l.account.control_role,
                    "normal_balance": l.account.normal_balance,
                    "party_name": (gl.party.name if gl and gl.party else (l.party.name if l.party else "")),
                    "debit": str(debit_val),
                    "credit": str(credit_val),
                    "before_balance": p_row.get("current_balance", "0.00"),
                    "after_balance": p_row.get("projected_balance", "0.00"),
                    "project_code": l.project.code if l.project else (voucher.project.code if voucher.project else "HO"),
                    "site_name": l.site.name if l.site else (voucher.site.name if voucher.site else ""),
                    "cost_center": l.cost_center.name if l.cost_center else (voucher.cost_center.name if voucher.cost_center else ""),
                    "cost_code": l.cost_code.code if l.cost_code else "",
                    "boq_code": l.boq_item.code if l.boq_item else "",
                    "description": l.description or voucher.narration,
                    "cost_allocations": [
                        {
                            "cost_center": ca.cost_center.name,
                            "project": ca.project.code if ca.project else "",
                            "mode": ca.allocation_mode,
                            "percentage": str(ca.percentage),
                            "amount": str(ca.amount),
                        }
                        for ca in l.cost_allocations.all()
                    ],
                }
            )

        total_debit = sum((Decimal(r["debit"]) for r in journal_lines), Decimal("0.00"))
        total_credit = sum((Decimal(r["credit"]) for r in journal_lines), Decimal("0.00"))
        party_subledger_entries = [
            {
                "id": str(pe.id),
                "party_name": pe.party.name,
                "entry_kind": pe.entry_kind,
                "debit": str(pe.debit),
                "credit": str(pe.credit),
                "posting_date": pe.entry_date.isoformat(),
                "bill_ref": pe.reference_no,
            }
            for pe in PartyLedgerEntry.objects.select_related("party").filter(voucher=voucher)
        ]

        return {
            "voucher_id": str(voucher.id),
            "voucher_no": voucher.voucher_no or "DRAFT",
            "posting_state": posting_state,
            "posting_state_label": posting_state_label,
            "is_posted": voucher.status == Voucher.Status.POSTED,
            "classification": {
                "voucher_type": voucher.voucher_type,
                "voucher_type_display": voucher.get_voucher_type_display(),
                "voucher_type_config": voucher.voucher_type_config.name if voucher.voucher_type_config else None,
                "voucher_class": voucher.voucher_class.name if voucher.voucher_class else None,
                "entry_mode": voucher.entry_mode,
                "provisional_kind": voucher.provisional_kind,
            },
            "is_balanced": total_debit == total_credit and total_debit > 0,
            "is_valid": plan.get("is_valid", False),
            "total_debit": str(total_debit),
            "total_credit": str(total_credit),
            "difference": str(abs(total_debit - total_credit)),
            "validation_errors": plan.get("validation_errors", []),
            "warnings": plan.get("warnings", []),
            "lines": journal_lines,
            "party_subledger": {
                "party_id": str(voucher.party_id) if voucher.party_id else None,
                "party_name": voucher.party.name if voucher.party else voucher.party_name,
                "party_type": voucher.party.party_type if voucher.party else None,
                "party_pan": voucher.party_pan,
                "entries": party_subledger_entries,
                "bill_allocations": voucher.bill_wise_allocations_payload or [],
            },
            "project_allocation": {
                "project": voucher.project.name if voucher.project else "Head Office",
                "project_code": voucher.project.code if voucher.project else "HO",
                "site": voucher.site.name if voucher.site else None,
                "department": voucher.department.name if voucher.department else None,
                "cost_center": voucher.cost_center.name if voucher.cost_center else None,
                "project_cost_impact": plan.get("project_cost_impact", []),
                "project_wip_impact": plan.get("project_wip_impact", "0.00"),
            },
            "inventory_impact": {
                "total_value": plan.get("inventory_impact", "0.00"),
                "movements": plan.get("inventory_movements", []),
            },
            "cash_bank_impact": plan.get("cash_bank_impact", []),
            "advance_adjustments": {
                "header_recovery": str(voucher.advance_recovery_amount),
                "impacts": plan.get("advance_impacts", []),
            },
            "retention_adjustments": {
                "header_retention": str(voucher.retention_amount),
                "impact": plan.get("retention_impact", {}),
            },
            "tax_tds_impact": plan.get("tax_tds_impact", {}),
            "statement_impact": plan.get("statement_impact", {}),
            "gl_posting_reference": {
                "posted_at": voucher.posted_at.isoformat() if voucher.posted_at else None,
                "posted_by": voucher.posted_by.username if voucher.posted_by else None,
                "fiscal_year": voucher.fiscal_year.name if voucher.fiscal_year else None,
                "fiscal_period": voucher.fiscal_period.name if voucher.fiscal_period else None,
                "ledger_entry_count": len(gl_entries),
                "ledger_entry_ids": [str(e.id) for e in gl_entries],
                "reversed_from": str(voucher.reversed_from_id) if voucher.reversed_from_id else None,
            },
        }

    @staticmethod
    def build_tax_payload(voucher: Voucher) -> dict:
        vdate = voucher.voucher_date
        tax_rules = list(
            TaxConfig.objects.select_related("tax_ledger")
            .filter(company=voucher.company, is_active=True)
            .filter(Q(effective_from__isnull=True) | Q(effective_from__lte=vdate))
            .filter(Q(effective_to__isnull=True) | Q(effective_to__gte=vdate))
        )
        vat_rule = next((r for r in tax_rules if r.tax_type == TaxConfig.TaxType.VAT), None)
        tds_rules = [r for r in tax_rules if r.tax_type == TaxConfig.TaxType.TDS]

        lines = list(voucher.lines.select_related("account"))
        gl_entries = list(LedgerEntry.objects.select_related("account").filter(voucher=voucher))
        source_rows = gl_entries if gl_entries else lines

        input_vat = Decimal("0.00")
        output_vat = Decimal("0.00")
        tds_payable = Decimal("0.00")
        tds_receivable = Decimal("0.00")
        tax_rows = []

        tax_period = voucher.fiscal_period.name if voucher.fiscal_period else ""
        tax_doc = voucher.supplier_invoice_no or voucher.reference_no or voucher.voucher_no or "DRAFT"

        total_gross = sum((l.debit for l in lines), Decimal("0.00"))
        tax_ledger_amt = Decimal("0.00")

        for row in source_rows:
            acc = row.account
            role = acc.control_role
            dr = row.debit
            cr = row.credit
            amt = dr if dr > 0 else cr
            if role in (Account.ControlRole.INPUT_VAT, Account.ControlRole.OUTPUT_VAT):
                tax_ledger_amt += amt
                if role == Account.ControlRole.INPUT_VAT:
                    input_vat += dr - cr
                else:
                    output_vat += cr - dr
                rate = vat_rule.rate if vat_rule else voucher.company.default_vat_rate
                taxable_base = voucher.gross_amount if voucher.gross_amount > 0 else max(total_gross - amt, Decimal("0.00"))
                tax_rows.append(
                    {
                        "taxable_amount": str(taxable_base),
                        "tax_type": "INPUT_VAT" if role == Account.ControlRole.INPUT_VAT else "OUTPUT_VAT",
                        "tax_rate": str(rate),
                        "tax_amount": str(amt),
                        "tax_ledger": f"{acc.code} — {acc.name}",
                        "tax_category": vat_rule.category if vat_rule else "STANDARD_VAT",
                        "exemption": vat_rule.exemption_rule if vat_rule and vat_rule.exemption_rule else "None",
                        "tax_period": tax_period,
                        "tax_document": tax_doc,
                        "calculation_rule": (
                            vat_rule.calculation_rule
                            if vat_rule and vat_rule.calculation_rule
                            else f"{vat_rule.name if vat_rule else 'Default Company VAT'} (Eff: {vat_rule.effective_from.isoformat() if vat_rule and vat_rule.effective_from else 'FY Start'})"
                        ),
                    }
                )
            elif role in (Account.ControlRole.TDS_PAYABLE, Account.ControlRole.TDS_RECEIVABLE):
                tax_ledger_amt += amt
                if role == Account.ControlRole.TDS_PAYABLE:
                    tds_payable += cr - dr
                else:
                    tds_receivable += dr - cr
                matched_tds = tds_rules[0] if tds_rules else None
                taxable_base = voucher.gross_amount if voucher.gross_amount > 0 else total_gross
                eff_rate = (amt * Decimal("100") / taxable_base).quantize(Decimal("0.01")) if taxable_base > 0 else (matched_tds.rate if matched_tds else Decimal("0.00"))
                tax_rows.append(
                    {
                        "taxable_amount": str(taxable_base),
                        "tax_type": "TDS_DEDUCTION" if role == Account.ControlRole.TDS_PAYABLE else "TDS_RECEIVABLE",
                        "tax_rate": str(eff_rate),
                        "tax_amount": str(amt),
                        "tax_ledger": f"{acc.code} — {acc.name}",
                        "tax_category": matched_tds.category if matched_tds else "STATUTORY_TDS",
                        "exemption": matched_tds.exemption_rule if matched_tds and matched_tds.exemption_rule else "None",
                        "tax_period": tax_period,
                        "tax_document": tax_doc,
                        "calculation_rule": (
                            matched_tds.calculation_rule
                            if matched_tds and matched_tds.calculation_rule
                            else f"{matched_tds.name if matched_tds else 'Nepal Sec 88/89 TDS'} (Eff: {matched_tds.effective_from.isoformat() if matched_tds and matched_tds.effective_from else 'FY Start'})"
                        ),
                    }
                )

        # If header carries tax_amount / tds_amount without explicit control-role GL lines, surface rule summary
        if not tax_rows and (voucher.tax_amount > 0 or voucher.tds_amount > 0):
            if voucher.tax_amount > 0:
                tax_rows.append(
                    {
                        "taxable_amount": str(voucher.gross_amount),
                        "tax_type": "VAT",
                        "tax_rate": str(vat_rule.rate if vat_rule else voucher.company.default_vat_rate),
                        "tax_amount": str(voucher.tax_amount),
                        "tax_ledger": f"{vat_rule.tax_ledger.code} — {vat_rule.tax_ledger.name}" if vat_rule and vat_rule.tax_ledger else "Configured VAT Ledger",
                        "tax_category": vat_rule.category if vat_rule else "STANDARD_VAT",
                        "exemption": vat_rule.exemption_rule if vat_rule and vat_rule.exemption_rule else "None",
                        "tax_period": tax_period,
                        "tax_document": tax_doc,
                        "calculation_rule": vat_rule.name if vat_rule else "Company Default VAT",
                    }
                )
            if voucher.tds_amount > 0:
                matched_tds = tds_rules[0] if tds_rules else None
                tax_rows.append(
                    {
                        "taxable_amount": str(voucher.gross_amount),
                        "tax_type": "TDS",
                        "tax_rate": str(matched_tds.rate if matched_tds else "0.00"),
                        "tax_amount": str(voucher.tds_amount),
                        "tax_ledger": f"{matched_tds.tax_ledger.code} — {matched_tds.tax_ledger.name}" if matched_tds and matched_tds.tax_ledger else "Configured TDS Ledger",
                        "tax_category": matched_tds.category if matched_tds else "STATUTORY_TDS",
                        "exemption": matched_tds.exemption_rule if matched_tds and matched_tds.exemption_rule else "None",
                        "tax_period": tax_period,
                        "tax_document": tax_doc,
                        "calculation_rule": matched_tds.name if matched_tds else "Nepal TDS Rule",
                    }
                )

        vat_total = input_vat + output_vat
        taxable_amount = voucher.gross_amount if voucher.gross_amount > 0 else max(total_gross - vat_total, Decimal("0.00"))
        non_taxable_amount = max(total_gross - taxable_amount - vat_total, Decimal("0.00")) if vat_total > 0 else Decimal("0.00")
        validations = []
        if (voucher.tax_amount > 0 or vat_total > 0) and voucher.party and not voucher.party_pan:
            validations.append({"level": "warning", "message": "Party PAN/VAT number is missing for VAT-bearing transaction."})
        if voucher.status == Voucher.Status.POSTED and voucher.tax_amount > 0 and vat_total == 0:
            validations.append({"level": "warning", "message": "Voucher header records VAT but no Input/Output VAT control ledger line was found."})
        if not validations:
            validations.append({"level": "ok", "message": "Tax amounts reconcile with effective-dated company tax configuration."})

        return {
            "voucher_id": str(voucher.id),
            "voucher_date": voucher.voucher_date.isoformat(),
            "bs_date": voucher.bs_date,
            "tax_period": tax_period,
            "tax_document": tax_doc,
            "party_pan": voucher.party_pan,
            "is_posted": voucher.status == Voucher.Status.POSTED,
            "summary": {
                "taxable_amount": str(taxable_amount),
                "non_taxable_amount": str(non_taxable_amount),
                "input_vat": str(input_vat),
                "output_vat": str(output_vat),
                "tds_deduction": str(tds_payable),
                "tds_receivable": str(tds_receivable),
                "tax_adjustment": str(voucher.discount_amount),
                "header_tax_amount": str(voucher.tax_amount),
                "header_tds_amount": str(voucher.tds_amount),
            },
            "tax_lines": tax_rows,
            "effective_rules": [
                {
                    "code": r.code,
                    "name": r.name,
                    "tax_type": r.tax_type,
                    "rate": str(r.rate),
                    "category": r.category,
                    "effective_from": r.effective_from.isoformat() if r.effective_from else None,
                    "effective_to": r.effective_to.isoformat() if r.effective_to else None,
                    "exemption_rule": r.exemption_rule,
                    "calculation_rule": r.calculation_rule,
                    "tax_ledger": f"{r.tax_ledger.code} — {r.tax_ledger.name}" if r.tax_ledger else None,
                }
                for r in tax_rules
            ],
            "validations": validations,
            "drill_down": {
                "route": "reports:wip",
                "label": "Open VAT & TDS Control Summary",
            },
        }

    @staticmethod
    def build_approvals_payload(voucher: Voucher, user, membership) -> dict:
        steps = list(voucher.approval_steps.select_related("actor").order_by("created_at"))
        total_amt = sum((l.debit for l in voucher.lines.all()), Decimal("0.00"))
        role_ids = [r.id for r in membership.effective_roles()] if membership else []
        authorities = list(
            ApprovalAuthority.objects.select_related("role")
            .filter(company=voucher.company, is_active=True)
            .filter(Q(voucher_type="ALL") | Q(voucher_type=voucher.voucher_type))
            .order_by("approval_level", "min_amount")
        )
        matched_auth = next(
            (a for a in authorities if a.role_id in role_ids and a.covers_amount(total_amt)),
            None,
        )

        submitted_step = next((s for s in steps if s.action == "SUBMITTED"), None)
        review_step = next((s for s in steps if s.action == "UNDER_REVIEW"), None)
        approved_step = next((s for s in reversed(steps) if s.action == "APPROVED"), None)
        rejected_step = next((s for s in reversed(steps) if s.action == "REJECTED"), None)
        returned_steps = [s for s in steps if s.action == "RETURNED"]

        stages = [
            {
                "key": "PREPARED",
                "title": "Voucher Prepared",
                "status": "completed" if voucher.created_by_id else "pending",
                "actor": voucher.created_by.username if voucher.created_by else "system",
                "timestamp": voucher.created_at.isoformat() if voucher.created_at else None,
                "reference": f"Created · Draft v{voucher.version}",
                "comment": submitted_step.comment if submitted_step else "",
            },
            {
                "key": "REVIEW",
                "title": "Finance Review",
                "status": (
                    "completed"
                    if review_step or voucher.status in (Voucher.Status.APPROVED, Voucher.Status.POSTED)
                    else ("active" if voucher.status in (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW) else "pending")
                ),
                "actor": (
                    review_step.actor.username
                    if review_step
                    else (voucher.assigned_reviewer.username if voucher.assigned_reviewer else "Pending reviewer")
                ),
                "timestamp": review_step.created_at.isoformat() if review_step else None,
                "reference": "Finance Manager / Reviewer",
                "comment": review_step.comment if review_step else "",
            },
            {
                "key": "AUTHORIZATION",
                "title": "Final Authorization",
                "status": (
                    "rejected"
                    if voucher.status == Voucher.Status.REJECTED
                    else ("returned" if voucher.status == Voucher.Status.RETURNED else ("completed" if voucher.approved_by_id else "pending"))
                ),
                "actor": (
                    voucher.approved_by.username
                    if voucher.approved_by
                    else (rejected_step.actor.username if rejected_step else "Pending authorization")
                ),
                "timestamp": (
                    approved_step.created_at.isoformat()
                    if approved_step
                    else (rejected_step.created_at.isoformat() if rejected_step else None)
                ),
                "reference": f"Level {matched_auth.approval_level}" if matched_auth else "Maker-Checker Control",
                "comment": (
                    approved_step.comment
                    if approved_step
                    else (rejected_step.comment if rejected_step else "")
                ),
            },
            {
                "key": "POSTING",
                "title": "Accounting Posting",
                "status": "completed" if voucher.status == Voucher.Status.POSTED else ("reversed" if voucher.status == Voucher.Status.REVERSED else "pending"),
                "actor": voucher.posted_by.username if voucher.posted_by else "Posting Engine",
                "timestamp": voucher.posted_at.isoformat() if voucher.posted_at else None,
                "reference": voucher.voucher_no if voucher.status in (Voucher.Status.POSTED, Voucher.Status.REVERSED) else "Awaiting GL Posting",
                "comment": "",
            },
        ]

        perms = {Permissions.VOUCHER_SUBMIT, Permissions.VOUCHER_APPROVE, Permissions.VOUCHER_REJECT, Permissions.VOUCHER_RETURN, Permissions.VOUCHER_HOLD, Permissions.VOUCHER_POST, Permissions.VOUCHER_REVERSE, Permissions.VOUCHER_EDIT, Permissions.VOUCHER_DELETE}
        if not user.is_superuser and membership:
            perms = set(membership.effective_permissions())

        is_maker = voucher.created_by_id == user.id
        can_approve_auth = user.is_superuser or (
            Permissions.VOUCHER_APPROVE in perms
            and not is_maker
            and (not authorities or matched_auth is not None)
        )

        available_actions = []
        if voucher.status in (Voucher.Status.DRAFT, Voucher.Status.RETURNED, Voucher.Status.ON_HOLD, Voucher.Status.REJECTED) and Permissions.VOUCHER_SUBMIT in perms:
            available_actions.append("submit")
        if voucher.status == Voucher.Status.SUBMITTED and Permissions.VOUCHER_APPROVE in perms:
            available_actions.append("under_review")
        if voucher.status in (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW) and can_approve_auth:
            available_actions.append("approve")
        if voucher.status in (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW) and Permissions.VOUCHER_RETURN in perms:
            available_actions.append("return")
        if voucher.status in (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW, Voucher.Status.APPROVED) and Permissions.VOUCHER_HOLD in perms:
            available_actions.append("hold")
        if voucher.status in (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW, Voucher.Status.APPROVED) and Permissions.VOUCHER_REJECT in perms:
            available_actions.append("reject")
        if voucher.status == Voucher.Status.APPROVED and Permissions.VOUCHER_POST in perms:
            available_actions.append("post")
        if voucher.status == Voucher.Status.POSTED and Permissions.VOUCHER_REVERSE in perms:
            available_actions.append("reverse")
        if voucher.status in (Voucher.Status.DRAFT, Voucher.Status.RETURNED, Voucher.Status.ON_HOLD, Voucher.Status.REJECTED) and Permissions.VOUCHER_DELETE in perms:
            available_actions.append("cancel")

        return {
            "voucher_id": str(voucher.id),
            "status": voucher.status,
            "prepared_by": voucher.created_by.username if voucher.created_by else None,
            "submitted_by": submitted_step.actor.username if submitted_step else None,
            "reviewer": (
                review_step.actor.username
                if review_step
                else (voucher.assigned_reviewer.username if voucher.assigned_reviewer else None)
            ),
            "approver": voucher.approved_by.username if voucher.approved_by else None,
            "posted_by": voucher.posted_by.username if voucher.posted_by else None,
            "posted_at": voucher.posted_at.isoformat() if voucher.posted_at else None,
            "posting_reference": voucher.voucher_no if voucher.status in (Voucher.Status.POSTED, Voucher.Status.REVERSED) else None,
            "approval_level": matched_auth.approval_level if matched_auth else 1,
            "amount_authority": (
                f"{matched_auth.currency} {matched_auth.min_amount} – {matched_auth.max_amount or 'Unlimited'}"
                if matched_auth
                else ("Unlimited (Superuser)" if user.is_superuser else "Role Permission Default")
            ),
            "rejection_reason": rejected_step.comment if rejected_step else "",
            "returned_history": [
                {
                    "actor": rs.actor.username,
                    "comment": rs.comment,
                    "timestamp": rs.created_at.isoformat(),
                }
                for rs in returned_steps
            ],
            "stages": stages,
            "steps": [
                {
                    "id": str(s.id),
                    "action": s.action,
                    "actor": s.actor.username,
                    "comment": s.comment,
                    "timestamp": s.created_at.isoformat(),
                }
                for s in steps
            ],
            "available_actions": available_actions,
        }

    @staticmethod
    def build_audit_payload(voucher: Voucher) -> dict:
        events = []

        # 1. Immutable AuditEvent records
        for ev in AuditEvent.objects.select_related("actor").filter(
            company=voucher.company, entity_type="Voucher", entity_id=str(voucher.id)
        ):
            prev = ev.previous_state or {}
            curr = ev.new_state or {}
            diffs = []
            for key in sorted(set(prev.keys()) | set(curr.keys())):
                if prev.get(key) != curr.get(key):
                    diffs.append({"field": key, "old": prev.get(key), "new": curr.get(key)})
            events.append(
                {
                    "id": str(ev.id),
                    "source": "AUDIT_EVENT",
                    "category": "WORKFLOW" if "APPROVED" in ev.action or "POSTED" in ev.action or "SUBMITTED" in ev.action else "MODIFICATION",
                    "action": ev.action,
                    "actor": ev.actor.username if ev.actor else "system",
                    "device_id": ev.device_id or "",
                    "ip_address": ev.ip_address or "",
                    "timestamp": ev.created_at.isoformat(),
                    "reason": (curr.get("reason") or curr.get("comment") or "") if isinstance(curr, dict) else "",
                    "diffs": diffs,
                    "immutable": True,
                }
            )

        # 2. Draft modification revisions (before/after payload diffs)
        for rev in voucher.revisions.select_related("changed_by").all():
            prev = rev.previous_payload or {}
            curr = rev.new_payload or {}
            diffs = []
            for key in sorted(set(prev.keys()) | set(curr.keys())):
                if prev.get(key) != curr.get(key):
                    diffs.append({"field": key, "old": prev.get(key), "new": curr.get(key)})
            events.append(
                {
                    "id": str(rev.id),
                    "source": "VOUCHER_REVISION",
                    "category": "MODIFICATION",
                    "action": f"REVISION_V{rev.version}",
                    "actor": rev.changed_by.username,
                    "device_id": "",
                    "ip_address": "",
                    "timestamp": rev.changed_at.isoformat(),
                    "reason": rev.change_summary,
                    "diffs": diffs,
                    "immutable": True,
                }
            )

        # 3. Document print, export, and delivery logs
        for dlog in DocumentAuditLog.objects.select_related("actor").filter(
            company=voucher.company, source_id=str(voucher.id)
        ):
            events.append(
                {
                    "id": str(dlog.id),
                    "source": "DOCUMENT_AUDIT",
                    "category": "DOCUMENT",
                    "action": f"DOC_{dlog.action}",
                    "actor": dlog.actor.username if dlog.actor else "system",
                    "device_id": "",
                    "ip_address": dlog.ip_address or "",
                    "timestamp": dlog.created_at.isoformat(),
                    "reason": f"{dlog.doc_type_code} ({dlog.output_format or 'VIEW'})",
                    "diffs": [{"field": "document_number", "old": None, "new": dlog.document_number}] if dlog.document_number else [],
                    "immutable": True,
                }
            )

        events.sort(key=lambda x: x["timestamp"], reverse=True)
        return {
            "voucher_id": str(voucher.id),
            "voucher_no": voucher.voucher_no or "DRAFT",
            "version": voucher.version,
            "is_immutable": True,
            "events": events,
        }

    @staticmethod
    def build_print_preview_payload(voucher: Voucher, user, params: dict, ip_address: str = "") -> dict:
        from apps.document_engine.services.pdf_service import render_preview_html

        doc_type_code = VOUCHER_TO_DOCTYPE.get(voucher.voucher_type, "JOURNAL_VOUCHER")
        overrides = {}
        for k in ("paper_size", "orientation", "copy_type", "language", "watermark_mode", "watermark_text"):
            if params.get(k):
                overrides[k] = params[k]

        html_str, payload, resolved = render_preview_html(
            company=voucher.company,
            doc_type_code=doc_type_code,
            source_id=str(voucher.id),
            user=user,
            template_id=params.get("template_id"),
            overrides=overrides,
            filters={},
            ip_address=ip_address,
        )

        rec = DocumentRecord.objects.filter(
            company=voucher.company,
            source_model="accounting.Voucher",
            source_id=str(voucher.id),
        ).first()
        versions = []
        deliveries = []
        if rec:
            versions = [
                {
                    "id": str(ver.id),
                    "version_number": ver.version_number,
                    "copy_type": ver.copy_type,
                    "output_format": ver.output_format,
                    "file_name": ver.file_name,
                    "verification_code": ver.verification_code,
                    "sha256_hash": ver.sha256_hash,
                    "is_superseded": ver.is_superseded,
                    "generated_by": ver.generated_by.username if ver.generated_by else "system",
                    "generated_at": ver.generated_at.isoformat(),
                }
                for ver in DocumentVersion.objects.select_related("generated_by").filter(document_record=rec).order_by("version_number")
            ]
            deliveries = [
                {
                    "id": str(dl.id),
                    "channel_type": dl.channel_type,
                    "recipient": dl.recipient,
                    "status": dl.status,
                    "created_at": dl.created_at.isoformat(),
                }
                for dl in DocumentDeliveryLog.objects.filter(document_version__document_record=rec).order_by("-created_at")[:15]
            ]

        is_posted = voucher.status in (Voucher.Status.POSTED, Voucher.Status.REVERSED)
        has_original_issued = bool(versions)
        return {
            "voucher_id": str(voucher.id),
            "doc_type_code": doc_type_code,
            "document_number": payload.get("document_number") or voucher.voucher_no or "DRAFT",
            "title": payload.get("title") or f"{voucher.voucher_type} {voucher.voucher_no or 'Draft'}",
            "html": html_str,
            "print_profile": resolved.get("print_profile", {}),
            "is_posted": is_posted,
            "has_original_issued_version": has_original_issued,
            "copy_classification": (
                "ORIGINAL_ISSUED_RECORD"
                if (is_posted and has_original_issued and not overrides)
                else ("REPRINT_OR_CUSTOM_COPY" if is_posted else "PROVISIONAL_DRAFT_PREVIEW")
            ),
            "issued_versions": versions,
            "delivery_history": deliveries,
            "document_record_id": str(rec.id) if rec else None,
        }

    @staticmethod
    def ensure_default_register_views(company) -> list[VoucherRegisterViewConfig]:
        existing = list(VoucherRegisterViewConfig.objects.filter(company=company, is_system=True))
        if existing:
            return existing

        specs = [
            ("ALL", "All Vouchers · Enterprise Modern", "ENTERPRISE_MODERN", True),
            ("PAYMENT", "Payment Register", "BANKING", False),
            ("RECEIPT", "Receipt Register", "BANKING", False),
            ("JOURNAL", "Journal Register (Tally Classic)", "TALLY_CLASSIC", False),
            ("CONTRA", "Contra Transfer Register", "BANKING", False),
            ("PURCHASE", "Purchase & Subcontractor Register", "ENTERPRISE_MODERN", False),
            ("SALES", "Sales & Client RA Register", "ENTERPRISE_MODERN", False),
            ("DEBIT_NOTE", "Debit Note Register", "TALLY_CLASSIC", False),
            ("CREDIT_NOTE", "Credit Note Register", "TALLY_CLASSIC", False),
            ("INVENTORY", "Inventory & Store Register", "INVENTORY", False),
            ("CONSTRUCTION", "Construction Project Register", "CONSTRUCTION_PROJECT", False),
        ]
        created = []
        for scope, name, style, is_def in specs:
            obj, _ = VoucherRegisterViewConfig.objects.get_or_create(
                company=company,
                name=name,
                register_scope=scope,
                is_system=True,
                defaults={
                    "description": f"System preset view for {name}",
                    "style_code": style,
                    "density": "compact",
                    "columns_config": DEFAULT_REGISTER_COLUMNS,
                    "filters_config": {"register_scope": scope},
                    "sort_config": {"sort_by": "voucher_date", "sort_dir": "desc"},
                    "page_size": 50,
                    "action_placement": "both",
                    "is_shared": True,
                    "is_default": is_def,
                },
            )
            created.append(obj)
        return created
