from datetime import date
from decimal import Decimal, ROUND_HALF_UP
from django.db.models import Count, Q, Sum
from django.utils import timezone

from apps.accounting.models import Account, AdvanceRecord, LedgerEntry, Party, Voucher, VoucherLine
from apps.audit.models import AuditEvent
from apps.banking.models import BankAccount, BankReconciliationSession, CashAccount, ChequeLeaf
from apps.budgeting.models import BudgetCommitment, BudgetLine
from apps.construction_ops.models import InventoryStockBalance
from apps.localization.bs_calendar import ad_to_bs
from apps.party_hub.models import OpenItem, PartyDispute, RetentionSchedule
from apps.party_hub.services.ar_intelligence_service import ARIntelligenceService
from apps.tenancy.models import FiscalPeriod, TaxConfig
from .filter_engine import ReportFilterContext, ReportFilterEngine
from .ledger_reports import BalanceSheetReportService, ProfitLossReportService, TrialBalanceReportService


Q2 = Decimal("0.01")


class FinancialReportService:
    """Cash Flow, Fund Flow, Cash/Bank Summary, Budget vs Actual, Expense/Revenue Analysis & Financial Ratios."""

    @staticmethod
    def build_cash_flow(*, company, user, membership, ctx: ReportFilterContext) -> dict:
        d_from = ctx.date_from
        d_to = ctx.date_to or timezone.localdate()
        cb_roles = [Account.ControlRole.CASH, Account.ControlRole.BANK]

        # Opening & Closing Cash + Bank from GL
        op_bal = Decimal("0.00")
        for acc in Account.objects.filter(company=company, control_role__in=cb_roles, is_group=False, is_active=True):
            op_bal += (acc.opening_debit - acc.opening_credit)
        if d_from:
            prior = LedgerEntry.objects.filter(company=company, account__control_role__in=cb_roles, posting_date__lt=d_from).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
            op_bal += (prior["d"] or Decimal("0.00")) - (prior["c"] or Decimal("0.00"))

        cb_entries = LedgerEntry.objects.select_related("voucher", "account").filter(company=company, account__control_role__in=cb_roles, posting_date__lte=d_to)
        if d_from:
            cb_entries = cb_entries.filter(posting_date__gte=d_from)
        cb_entries = ReportFilterEngine.scope_qs(cb_entries, user=user, membership=membership)

        operating_in = operating_out = investing_in = investing_out = financing_in = financing_out = Decimal("0.00")
        for e in cb_entries:
            vt = e.voucher.voucher_type
            d = e.base_debit or Decimal("0.00")
            c = e.base_credit or Decimal("0.00")
            if vt in (Voucher.VoucherType.CONTRA,):
                continue  # Internal Cash/Bank transfer nets to 0
            elif vt in (Voucher.VoucherType.ASSET_ACQUISITION, Voucher.VoucherType.ASSET_DISPOSAL):
                investing_in += d
                investing_out += c
            elif vt in (Voucher.VoucherType.LOAN_DISBURSEMENT, Voucher.VoucherType.LOAN_REPAYMENT):
                financing_in += d
                financing_out += c
            else:
                operating_in += d
                operating_out += c

        net_op = operating_in - operating_out
        net_inv = investing_in - investing_out
        net_fin = financing_in - financing_out
        net_change = net_op + net_inv + net_fin
        closing_cb = op_bal + net_change

        rows = [
            {"section": "OPERATING", "label": "Cash Inflows from Operations & Receipts", "amount": str(operating_in)},
            {"section": "OPERATING", "label": "Cash Outflows for Suppliers, Site & Payroll", "amount": str(-operating_out)},
            {"section": "OPERATING", "label": "Net Cash Flow from Operating Activities", "amount": str(net_op), "is_subtotal": True},
            {"section": "INVESTING", "label": "Asset Disposals & Capital Inflows", "amount": str(investing_in)},
            {"section": "INVESTING", "label": "Capital Expenditure & Equipment Purchases", "amount": str(-investing_out)},
            {"section": "INVESTING", "label": "Net Cash Flow from Investing Activities", "amount": str(net_inv), "is_subtotal": True},
            {"section": "FINANCING", "label": "Loan Disbursements & Capital Proceeds", "amount": str(financing_in)},
            {"section": "FINANCING", "label": "Loan Repayments & Debt Service", "amount": str(-financing_out)},
            {"section": "FINANCING", "label": "Net Cash Flow from Financing Activities", "amount": str(net_fin), "is_subtotal": True},
        ]
        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="cash_flow", title="Cash Flow Statement (Direct Method)", row_count=len(rows)),
            "rows": rows,
            "summary": {
                "opening_cash_bank": str(op_bal),
                "net_operating": str(net_op),
                "net_investing": str(net_inv),
                "net_financing": str(net_fin),
                "net_cash_movement": str(net_change),
                "closing_cash_bank": str(closing_cb),
            },
        }

    @staticmethod
    def build_budget_vs_actual(*, company, user, membership, ctx: ReportFilterContext) -> dict:
        lines = BudgetLine.objects.select_related("budget_version__budget", "budget_version__budget__project", "account", "cost_code").filter(
            budget_version__budget__company=company, budget_version__is_active=True
        )
        if ctx.project_id:
            lines = lines.filter(budget_version__budget__project_id=ctx.project_id)

        rows = []
        tot_bgt = tot_act = tot_comm = Decimal("0.00")
        for bl in lines:
            bgt = bl.budget_version.budget
            if membership and not user.is_superuser and membership.data_scope == "PROJECT":
                if bgt.project_id not in list(membership.projects.values_list("id", flat=True)):
                    continue
            rev_bgt = bl.approved_amount
            le_qs = LedgerEntry.objects.filter(company=company)
            if bgt.project_id:
                le_qs = le_qs.filter(project_id=bgt.project_id)
            if bl.account_id:
                le_qs = le_qs.filter(account_id=bl.account_id)
            if bl.cost_code_id:
                le_qs = le_qs.filter(cost_code_id=bl.cost_code_id)
            agg = le_qs.aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
            actual = (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))

            # Open commitments only (relieved amount subtracted so PO -> Bill never double-counts)
            open_comm = sum(
                (max(c.committed_amount - c.relieved_amount, Decimal("0.00")) for c in BudgetCommitment.objects.filter(
                    budget_line=bl, status__in=[BudgetCommitment.Status.OPEN, BudgetCommitment.Status.PARTIALLY_RELIEVED]
                )),
                Decimal("0.00"),
            )
            avail = rev_bgt - actual - open_comm
            util = str((actual * Decimal("100") / rev_bgt).quantize(Q2)) if rev_bgt > 0 else "0.00"
            tot_bgt += rev_bgt
            tot_act += actual
            tot_comm += open_comm
            rows.append({
                "budget_name": bgt.title or bgt.budget_code,
                "project_code": bgt.project.code if bgt.project else "HO",
                "category": bl.cost_category,
                "description": bl.description or (bl.account.name if bl.account else "-"),
                "revised_budget": str(rev_bgt),
                "open_commitments": str(open_comm),
                "actual_cost": str(actual),
                "available_budget": str(avail),
                "utilization_pct": util,
            })

        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="budget_vs_actual", title="Budget vs Actual & Commitment Utilization", row_count=len(rows)),
            "formula_note": "Available Budget = Revised Approved Budget - Eligible Actual Cost - Open Un-Relieved Commitments",
            "rows": rows,
            "summary": {
                "revised_budget": str(tot_bgt),
                "actual_cost": str(tot_act),
                "open_commitments": str(tot_comm),
                "available_budget": str(tot_bgt - tot_act - tot_comm),
            },
        }

    @staticmethod
    def build_financial_subreport(*, company, user, membership, ctx: ReportFilterContext, code: str) -> dict:
        if code == "cash_flow":
            return FinancialReportService.build_cash_flow(company=company, user=user, membership=membership, ctx=ctx)
        if code == "budget_vs_actual":
            return FinancialReportService.build_budget_vs_actual(company=company, user=user, membership=membership, ctx=ctx)
        if code == "fund_flow":
            bs = BalanceSheetReportService.build(company=company, user=user, membership=membership, ctx=ctx)
            cf = FinancialReportService.build_cash_flow(company=company, user=user, membership=membership, ctx=ctx)
            rows = [
                {"category": "SOURCE", "item": "Net Cash Inflow from Operations", "amount": cf["summary"]["net_operating"]},
                {"category": "SOURCE", "item": "Financing Proceeds Net", "amount": cf["summary"]["net_financing"]},
                {"category": "APPLICATION", "item": "Investing Outflow Net", "amount": cf["summary"]["net_investing"]},
                {"category": "WORKING_CAPITAL", "item": "Net Working Capital (Current Assets - Current Liabilities)", "amount": bs["summary"]["working_capital"]},
            ]
            return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=code, title="Fund Flow & Working Capital Statement", row_count=len(rows)), "rows": rows}
        if code in ("cash_bank_summary", "bank_reconciliation"):
            rows = []
            for ba in BankAccount.objects.select_related("gl_account").filter(company=company, is_active=True):
                agg = LedgerEntry.objects.filter(company=company, account=ba.gl_account).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
                bal = (ba.gl_account.opening_debit - ba.gl_account.opening_credit) + (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
                unpresented = ChequeLeaf.objects.filter(bank_account=ba, status="ISSUED").count()
                last_rec = BankReconciliationSession.objects.filter(bank_account=ba).order_by("-statement_date").first()
                rows.append({
                    "kind": "BANK", "name": ba.account_name, "account_code": ba.gl_account.code,
                    "book_balance": str(bal), "unpresented_cheques": unpresented,
                    "last_recon_status": last_rec.status if last_rec else "NOT_RECONCILED",
                })
            for ca in CashAccount.objects.select_related("gl_account").filter(company=company, is_active=True):
                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"))
                rows.append({"kind": "CASH", "name": ca.name, "account_code": ca.gl_account.code, "book_balance": str(bal), "unpresented_cheques": 0, "last_recon_status": "NA"})
            return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=code, title="Cash & Bank Reconciliation Summary", row_count=len(rows)), "rows": rows}
        if code in ("receivable_summary", "payable_summary"):
            side = OpenItem.HubSide.RECEIVABLE if code == "receivable_summary" else OpenItem.HubSide.PAYABLE
            return UnifiedAgingReportService.build(company=company, user=user, membership=membership, ctx=ctx, side=side)
        if code in ("expense_analysis", "revenue_analysis"):
            pl = ProfitLossReportService.build(company=company, user=user, membership=membership, ctx=ctx)
            rows = pl["sections"]["income"]["rows"] if code == "revenue_analysis" else (pl["sections"]["direct_costs"]["rows"] + pl["sections"]["operating_expenses"]["rows"])
            return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=code, title="Revenue Analysis" if code == "revenue_analysis" else "Expense Analysis", row_count=len(rows)), "rows": rows}
        # financial_ratios
        pl = ProfitLossReportService.build(company=company, user=user, membership=membership, ctx=ctx)
        bs = BalanceSheetReportService.build(company=company, user=user, membership=membership, ctx=ctx)
        dso = ARIntelligenceService.compute_dso_suite(company=company, as_of_date=ctx.as_of_date)
        rows = [
            {"ratio": "Current Ratio", "formula": "Current Assets / Current Liabilities", "value": bs["summary"]["current_ratio"]},
            {"ratio": "Debt to Equity", "formula": "Total Liabilities / Total Equity", "value": bs["summary"]["debt_to_equity"]},
            {"ratio": "Working Capital", "formula": "Current Assets - Current Liabilities", "value": bs["summary"]["working_capital"]},
            {"ratio": "Gross Profit Margin %", "formula": "Gross Profit / Total Revenue * 100", "value": pl["summary"]["gross_margin_pct"]},
            {"ratio": "Operating Margin %", "formula": "Operating Profit / Total Revenue * 100", "value": pl["summary"]["operating_margin_pct"]},
            {"ratio": "Net Profit Margin %", "formula": "Net Profit / Total Revenue * 100", "value": pl["summary"]["net_margin_pct"]},
            {"ratio": f"DSO ({dso['methodology']})", "formula": dso["current_period"]["formula"], "value": f"{dso['current_period']['dso_days']} Days"},
        ]
        return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="financial_ratios", title="Key Financial Ratios", row_count=len(rows)), "rows": rows}


class UnifiedAgingReportService:
    """AP / AR Open-Item Aging strictly separating Trade vs Retention vs Advances vs Disputed."""

    @staticmethod
    def build(*, company, user, membership, ctx: ReportFilterContext, side: str = OpenItem.HubSide.RECEIVABLE) -> dict:
        as_of = ctx.as_of_date or timezone.localdate()
        buckets = ctx.extra.get("buckets") or [0, 30, 60, 90, 120]
        qs = OpenItem.objects.select_related("party", "project", "voucher").filter(
            company=company, hub_side=side, is_unallocated_credit=False
        ).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.REVERSED, OpenItem.Status.WRITTEN_OFF])
        qs = ReportFilterEngine.scope_qs(qs, user=user, membership=membership, site_field=None, branch_field=None)
        if ctx.project_id:
            qs = qs.filter(project_id=ctx.project_id)
        if ctx.party_id:
            qs = qs.filter(party_id=ctx.party_id)

        totals = {"not_due": Decimal("0.00"), "b1_30": Decimal("0.00"), "b31_60": Decimal("0.00"), "b61_90": Decimal("0.00"), "b91_120": Decimal("0.00"), "b120_plus": Decimal("0.00"), "total": Decimal("0.00"), "disputed": Decimal("0.00")}
        rows = []
        for oi in qs:
            rem = oi.remaining_amount
            od_days = max((as_of - oi.due_date).days, 0)
            if od_days == 0:
                bkey = "not_due"
            elif od_days <= buckets[1]:
                bkey = "b1_30"
            elif od_days <= buckets[2]:
                bkey = "b31_60"
            elif od_days <= buckets[3]:
                bkey = "b61_90"
            elif od_days <= buckets[4]:
                bkey = "b91_120"
            else:
                bkey = "b120_plus"
            totals[bkey] += rem
            totals["total"] += rem
            if oi.status == OpenItem.Status.DISPUTED:
                totals["disputed"] += rem
            rows.append({
                "id": str(oi.id),
                "voucher_id": str(oi.voucher_id),
                "party_id": str(oi.party_id),
                "party_name": oi.party.name,
                "doc_kind": oi.doc_kind,
                "document_no": oi.document_no,
                "project_code": oi.project.code if oi.project else "HO",
                "document_date": oi.document_date.isoformat(),
                "bs_date": oi.bs_date,
                "due_date": oi.due_date.isoformat(),
                "original_amount": str(oi.original_amount),
                "allocated_amount": str(oi.allocated_amount),
                "outstanding": str(rem),
                "overdue_days": od_days,
                "bucket": bkey,
                "status": oi.status,
            })

        # Separate non-trade balances explicitly
        ret_dir = RetentionSchedule.Direction.RECEIVABLE if side == OpenItem.HubSide.RECEIVABLE else RetentionSchedule.Direction.PAYABLE
        adv_type = AdvanceRecord.AdvanceType.CUSTOMER_ADVANCE if side == OpenItem.HubSide.RECEIVABLE else AdvanceRecord.AdvanceType.SUPPLIER_ADVANCE
        retention_held = sum((r.remaining_retention for r in RetentionSchedule.objects.filter(company=company, direction=ret_dir).exclude(status=RetentionSchedule.Status.RELEASED)), Decimal("0.00"))
        advance_bal = sum((a.remaining_amount for a in AdvanceRecord.objects.filter(company=company, advance_type=adv_type).exclude(status__in=[AdvanceRecord.Status.SETTLED, AdvanceRecord.Status.CANCELLED])), Decimal("0.00"))

        title = "Accounts Receivable Aging" if side == OpenItem.HubSide.RECEIVABLE else "Accounts Payable Aging"
        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="ar_aging" if side == OpenItem.HubSide.RECEIVABLE else "ap_aging", title=title, row_count=len(rows)),
            "rows": rows,
            "summary": {k: str(v) for k, v in totals.items()},
            "separate_balances": {
                "retention_held": str(retention_held),
                "advance_balance": str(advance_bal),
                "disputed_balance": str(totals["disputed"]),
            },
        }


class TaxComplianceReportService:
    """Nepal VAT & TDS Statutory Compliance Reports driven strictly from effective-dated TaxConfig & GL Tax Accounts."""

    @staticmethod
    def build(*, company, user, membership, ctx: ReportFilterContext, code: str) -> dict:
        as_of = ctx.date_to or timezone.localdate()
        tax_rules = list(
            TaxConfig.objects.filter(company=company, is_active=True)
            .filter(Q(effective_from__isnull=True) | Q(effective_from__lte=as_of))
            .filter(Q(effective_to__isnull=True) | Q(effective_to__gte=as_of))
        )
        rules_meta = [{"code": r.code, "name": r.name, "tax_type": r.tax_type, "rate": str(r.rate), "category": r.category} for r in tax_rules]

        tax_roles = [Account.ControlRole.INPUT_VAT, Account.ControlRole.OUTPUT_VAT, Account.ControlRole.TDS_PAYABLE, Account.ControlRole.TDS_RECEIVABLE]
        le_qs = LedgerEntry.objects.select_related("voucher", "account", "party", "project").filter(
            company=company, account__control_role__in=tax_roles
        )
        le_qs = ReportFilterEngine.scope_qs(le_qs, user=user, membership=membership)
        if ctx.date_from:
            le_qs = le_qs.filter(posting_date__gte=ctx.date_from)
        if ctx.date_to:
            le_qs = le_qs.filter(posting_date__lte=ctx.date_to)

        if code == "vat_purchase_register":
            le_qs = le_qs.filter(account__control_role=Account.ControlRole.INPUT_VAT)
        elif code == "vat_sales_register":
            le_qs = le_qs.filter(account__control_role=Account.ControlRole.OUTPUT_VAT)
        elif code in ("tds_report", "tax_certificates"):
            le_qs = le_qs.filter(account__control_role__in=[Account.ControlRole.TDS_PAYABLE, Account.ControlRole.TDS_RECEIVABLE])

        rows = []
        tot_dr = tot_cr = Decimal("0.00")
        for e in le_qs[:500]:
            tot_dr += e.base_debit
            tot_cr += e.base_credit
            rows.append({
                "posting_date": e.posting_date.isoformat(),
                "bs_date": e.bs_date or ad_to_bs(e.posting_date).isoformat(),
                "voucher_no": e.voucher.voucher_no,
                "tax_role": e.account.control_role,
                "account": f"{e.account.code} {e.account.name}",
                "party_name": e.party.name if e.party else (e.voucher.party_name or "-"),
                "pan_vat_no": e.party.pan_vat_no if e.party else "",
                "debit": str(e.base_debit),
                "credit": str(e.base_credit),
                "narration": e.narration,
            })

        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=code, title=f"Tax Compliance — {code.replace('_', ' ').title()}", row_count=len(rows)),
            "effective_tax_rules": rules_meta,
            "rows": rows,
            "summary": {"total_debit": str(tot_dr), "total_credit": str(tot_cr), "net_tax_payable": str(tot_cr - tot_dr)},
        }


class AuditControlReportService:
    """Control Reconciliations, Suspense Analysis, Unposted/Reversed Registers & Period Closing Checklist."""

    @staticmethod
    def build(*, company, user, membership, ctx: ReportFilterContext, code: str) -> dict:
        if code in ("account_reconciliation", "debtors_control_recon", "creditors_control_recon", "inventory_control_recon", "wip_control_recon"):
            ar_rec = ARIntelligenceService.compute_control_reconciliation(company=company, as_of_date=ctx.as_of_date)
            controls = list(ar_rec["controls"])

            # Add Creditors Control vs OpenItem Payable
            ap_acc = Account.objects.filter(company=company, control_role=Account.ControlRole.SUNDRY_CREDITORS, is_group=False, is_active=True).first()
            ap_gl = Decimal("0.00")
            if ap_acc:
                agg = LedgerEntry.objects.filter(company=company, account=ap_acc, posting_date__lte=(ctx.as_of_date or timezone.localdate())).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
                ap_gl = (ap_acc.opening_credit - ap_acc.opening_debit) + (agg["c"] or Decimal("0.00")) - (agg["d"] or Decimal("0.00"))
            ap_sub = (
                sum((o.remaining_amount for o in OpenItem.objects.filter(company=company, hub_side=OpenItem.HubSide.PAYABLE, is_unallocated_credit=False).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.REVERSED, OpenItem.Status.WRITTEN_OFF])), Decimal("0.00"))
                - sum((o.remaining_amount for o in OpenItem.objects.filter(company=company, hub_side=OpenItem.HubSide.PAYABLE, is_unallocated_credit=True).exclude(status__in=[OpenItem.Status.SETTLED, OpenItem.Status.REVERSED])), Decimal("0.00"))
            )
            controls.append({
                "control_role": "SUNDRY_CREDITORS",
                "label": "Trade Creditors Control vs Open Payable Subledger",
                "account_code": ap_acc.code if ap_acc else "-",
                "account_name": ap_acc.name if ap_acc else "Not Configured",
                "gl_balance": str(ap_gl),
                "subledger_balance": str(ap_sub),
                "variance": str(ap_gl - ap_sub),
                "is_reconciled": ap_gl == ap_sub,
            })
            return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=code, title="Control Account vs Subledger Reconciliation", row_count=len(controls)), "rows": controls}

        if code == "suspense_analysis":
            tb = TrialBalanceReportService.build(company=company, user=user, membership=membership, ctx=ctx)
            rows = [r for r in tb["rows"] if "suspense" in r["name"].lower() or "ABNORMAL" in "".join(r["flags"]) or "UNMAPPED" in "".join(r["flags"])]
            return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=code, title="Suspense & Unusual Account Balance Analysis", row_count=len(rows)), "rows": rows}

        if code in ("unposted_vouchers", "reversed_vouchers"):
            sub_ctx = ReportFilterContext(**{**ctx.__dict__, "posted_status": "UNPOSTED" if code == "unposted_vouchers" else "REVERSED"})
            from .ledger_reports import VoucherRegisterReportService
            res = VoucherRegisterReportService.build(company=company, user=user, membership=membership, ctx=sub_ctx)
            res["meta"]["report_code"] = code
            res["meta"]["title"] = "Unposted Vouchers Register" if code == "unposted_vouchers" else "Reversed Vouchers Register"
            return res

        if code in ("audit_trail", "user_activity"):
            qs = AuditEvent.objects.select_related("actor").filter(company=company).order_by("-created_at")[:300]
            rows = [{"timestamp": e.created_at.isoformat(), "actor": e.actor.username if e.actor else "System", "action": e.action, "entity_type": e.entity_type, "entity_id": e.entity_id, "changes": str(e.new_state)[:160]} for e in qs]
            return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=code, title="Audit Trail & User Activity Report", row_count=len(rows)), "rows": rows}

        # period_closing_checklist
        tb = TrialBalanceReportService.build(company=company, user=user, membership=membership, ctx=ctx)
        drafts = Voucher.objects.filter(company=company).exclude(status__in=[Voucher.Status.POSTED, Voucher.Status.REVERSED, Voucher.Status.CANCELLED]).count()
        rows = [
            {"check": "Trial Balance Balanced (Dr == Cr)", "status": "PASS" if tb["validation"]["is_balanced"] else "FAIL", "detail": f"Difference: {tb['validation']['trial_balance_difference']}"},
            {"check": "Zero Suspense Non-Zero Accounts", "status": "PASS" if not tb["validation"]["suspense_accounts"] else "WARN", "detail": f"{len(tb['validation']['suspense_accounts'])} suspense account(s)"},
            {"check": "Pending Unposted Vouchers Cleared", "status": "PASS" if drafts == 0 else "ACTION_REQUIRED", "detail": f"{drafts} unposted voucher(s)"},
        ]
        return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code=code, title="Period Closing Readiness Checklist", row_count=len(rows)), "rows": rows}

