from datetime import date, timedelta
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, BillAllocation, LedgerEntry, Voucher, VoucherLine
from apps.budgeting.models import BudgetLine
from apps.localization.bs_calendar import ad_to_bs
from .filter_engine import ReportFilterContext, ReportFilterEngine


Q2 = Decimal("0.01")


def _q2(v) -> Decimal:
    return Decimal(str(v or "0.00")).quantize(Q2, rounding=ROUND_HALF_UP)


def _apply_ledger_filters(qs, ctx: ReportFilterContext, user, membership):
    qs = ReportFilterEngine.scope_qs(qs, user=user, membership=membership)
    if ctx.branch_id:
        qs = qs.filter(branch_id=ctx.branch_id)
    if ctx.department_id:
        qs = qs.filter(department_id=ctx.department_id)
    if ctx.project_id:
        qs = qs.filter(project_id=ctx.project_id)
    if ctx.site_id:
        qs = qs.filter(site_id=ctx.site_id)
    if ctx.cost_center_id:
        qs = qs.filter(cost_center_id=ctx.cost_center_id)
    if ctx.party_id:
        qs = qs.filter(party_id=ctx.party_id)
    if ctx.voucher_type:
        qs = qs.filter(voucher__voucher_type=ctx.voucher_type)
    return qs


def _prev_period(d_from: date | None, d_to: date | None, mode: str) -> tuple[date | None, date | None]:
    if not d_to:
        return None, None
    if mode == "PREVIOUS_FY":
        return (d_from.replace(year=d_from.year - 1) if d_from else None), d_to.replace(year=d_to.year - 1)
    if not d_from:
        return None, d_to - timedelta(days=30)
    span = max((d_to - d_from).days + 1, 1)
    prev_to = d_from - timedelta(days=1)
    prev_from = prev_to - timedelta(days=span - 1)
    return prev_from, prev_to


class TrialBalanceReportService:
    @staticmethod
    def build(*, company, user, membership, ctx: ReportFilterContext) -> dict:
        d_from = ctx.date_from
        d_to = ctx.date_to or timezone.localdate()

        accounts_qs = Account.objects.select_related("parent").filter(company=company, is_group=False, is_active=True).order_by("code")
        if ctx.account_group_id:
            accounts_qs = accounts_qs.filter(Q(parent_id=ctx.account_group_id) | Q(id=ctx.account_group_id))
        if ctx.account_id:
            accounts_qs = accounts_qs.filter(id=ctx.account_id)
        if ctx.search:
            accounts_qs = accounts_qs.filter(Q(code__icontains=ctx.search) | Q(name__icontains=ctx.search))

        base_entries = _apply_ledger_filters(LedgerEntry.objects.filter(company=company), ctx, user, membership)

        # Opening prior posted movements (before d_from)
        prior_sums = {}
        if d_from and ctx.show_opening:
            for r in base_entries.filter(posting_date__lt=d_from).values("account_id").annotate(d=Sum("base_debit"), c=Sum("base_credit")):
                prior_sums[r["account_id"]] = (r["d"] or Decimal("0.00"), r["c"] or Decimal("0.00"))

        period_qs = base_entries.filter(posting_date__lte=d_to)
        if d_from:
            period_qs = period_qs.filter(posting_date__gte=d_from)
        period_sums = {
            r["account_id"]: (r["d"] or Decimal("0.00"), r["c"] or Decimal("0.00"))
            for r in period_qs.values("account_id").annotate(d=Sum("base_debit"), c=Sum("base_credit"))
        }

        # Optional comparative period
        comp_closing = {}
        if ctx.compare_with:
            _, comp_to = _prev_period(d_from, d_to, ctx.compare_with)
            if comp_to:
                for r in base_entries.filter(posting_date__lte=comp_to).values("account_id").annotate(d=Sum("base_debit"), c=Sum("base_credit")):
                    comp_closing[r["account_id"]] = (r["d"] or Decimal("0.00")) - (r["c"] or Decimal("0.00"))

        rows = []
        group_totals: dict[str, dict] = {}
        tot_op_d = tot_op_c = tot_mv_d = tot_mv_c = tot_cl_d = tot_cl_c = Decimal("0.00")
        unusual_accounts = []
        suspense_accounts = []
        unmapped_accounts = []

        # Include master opening_debit/credit when unscoped by project/site/cost_center
        use_master_opening = not (ctx.project_id or ctx.site_id or ctx.cost_center_id or ctx.branch_id or ctx.party_id)

        for acc in accounts_qs:
            m_op_d = acc.opening_debit if (use_master_opening and ctx.show_opening) else Decimal("0.00")
            m_op_c = acc.opening_credit if (use_master_opening and ctx.show_opening) else Decimal("0.00")
            p_d, p_c = prior_sums.get(acc.id, (Decimal("0.00"), Decimal("0.00")))
            op_net = (m_op_d - m_op_c) + (p_d - p_c)
            op_d = op_net if op_net > 0 else Decimal("0.00")
            op_c = -op_net if op_net < 0 else Decimal("0.00")

            mv_d, mv_c = period_sums.get(acc.id, (Decimal("0.00"), Decimal("0.00")))
            cl_net = op_net + (mv_d - mv_c)
            cl_d = cl_net if cl_net > 0 else Decimal("0.00")
            cl_c = -cl_net if cl_net < 0 else Decimal("0.00")

            if not ctx.include_zero and op_d == 0 and op_c == 0 and mv_d == 0 and mv_c == 0 and cl_d == 0 and cl_c == 0:
                continue

            tot_op_d += op_d
            tot_op_c += op_c
            tot_mv_d += mv_d
            tot_mv_c += mv_c
            tot_cl_d += cl_d
            tot_cl_c += cl_c

            flags = []
            if acc.normal_balance == "DEBIT" and cl_c > 0:
                flags.append("ABNORMAL_CREDIT")
            elif acc.normal_balance == "CREDIT" and cl_d > 0:
                flags.append("ABNORMAL_DEBIT")
            if "suspense" in acc.name.lower() and cl_net != 0:
                flags.append("SUSPENSE_NONZERO")
                suspense_accounts.append({"code": acc.code, "name": acc.name, "balance": str(cl_net)})
            if not acc.account_type:
                flags.append("UNMAPPED")
                unmapped_accounts.append({"code": acc.code, "name": acc.name})
            if flags:
                unusual_accounts.append({"code": acc.code, "name": acc.name, "flags": flags, "closing_net": str(cl_net)})

            grp_name = acc.parent.name if acc.parent else acc.account_type
            grp = group_totals.setdefault(grp_name, {"group_name": grp_name, "account_type": acc.account_type, "closing_debit": Decimal("0.00"), "closing_credit": Decimal("0.00")})
            grp["closing_debit"] += cl_d
            grp["closing_credit"] += cl_c

            comp_net = None
            if ctx.compare_with:
                c_prior = comp_closing.get(acc.id, Decimal("0.00"))
                c_master = (acc.opening_debit - acc.opening_credit) if use_master_opening else Decimal("0.00")
                comp_net = str(c_master + c_prior)

            rows.append({
                "account_id": str(acc.id),
                "code": acc.code,
                "name": acc.name,
                "group_name": grp_name,
                "account_type": acc.account_type,
                "account_class": acc.effective_class,
                "normal_balance": acc.normal_balance,
                "opening_debit": str(op_d),
                "opening_credit": str(op_c),
                "period_debit": str(mv_d),
                "period_credit": str(mv_c),
                "closing_debit": str(cl_d),
                "closing_credit": str(cl_c),
                "comparative_net": comp_net,
                "flags": flags,
            })

        # Unposted summary separated cleanly from official posted totals
        unposted_qs = Voucher.objects.filter(company=company).exclude(status__in=[Voucher.Status.POSTED, Voucher.Status.REVERSED, Voucher.Status.CANCELLED])
        unposted_qs = ReportFilterEngine.scope_qs(unposted_qs, user=user, membership=membership)
        unposted_summary = {
            "count": unposted_qs.count(),
            "gross_total": str(unposted_qs.aggregate(s=Sum("net_amount"))["s"] or Decimal("0.00")),
            "note": "Excluded from official Trial Balance & GL totals.",
        }

        diff = tot_cl_d - tot_cl_c
        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="trial_balance", title="Trial Balance", row_count=len(rows)),
            "rows": rows,
            "groups": [{**g, "closing_debit": str(g["closing_debit"]), "closing_credit": str(g["closing_credit"])} for g in group_totals.values()],
            "validation": {
                "total_opening_debit": str(tot_op_d),
                "total_opening_credit": str(tot_op_c),
                "total_period_debit": str(tot_mv_d),
                "total_period_credit": str(tot_mv_c),
                "total_closing_debit": str(tot_cl_d),
                "total_closing_credit": str(tot_cl_c),
                "trial_balance_difference": str(diff),
                "is_balanced": diff == Decimal("0.00"),
                "unmapped_accounts": unmapped_accounts,
                "suspense_accounts": suspense_accounts,
                "unusual_accounts": unusual_accounts,
            },
            "unposted_summary": unposted_summary,
        }


class GeneralLedgerReportService:
    @staticmethod
    def build(*, company, user, membership, ctx: ReportFilterContext) -> dict:
        acc = Account.objects.filter(company=company, id=ctx.account_id).first() if ctx.account_id else None
        if not acc:
            acc = Account.objects.filter(company=company, is_group=False, is_active=True).order_by("code").first()
        if not acc:
            return {"meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="general_ledger", title="General Ledger"), "account": None, "rows": [], "opening_balance": "0.00", "closing_balance": "0.00"}

        qs = _apply_ledger_filters(
            LedgerEntry.objects.select_related("voucher", "voucher_line", "project", "site", "cost_center", "cost_code", "party").filter(company=company, account=acc),
            ctx,
            user,
            membership,
        ).order_by("posting_date", "posted_at")

        use_master = not (ctx.project_id or ctx.site_id or ctx.cost_center_id or ctx.branch_id or ctx.party_id)
        opening_net = (acc.opening_debit - acc.opening_credit) if (use_master and ctx.show_opening) else Decimal("0.00")
        if ctx.date_from and ctx.show_opening:
            prior = qs.filter(posting_date__lt=ctx.date_from).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
            opening_net += (prior["d"] or Decimal("0.00")) - (prior["c"] or Decimal("0.00"))
        if ctx.date_from:
            qs = qs.filter(posting_date__gte=ctx.date_from)
        if ctx.date_to:
            qs = qs.filter(posting_date__lte=ctx.date_to)
        if ctx.search:
            qs = qs.filter(Q(voucher__voucher_no__icontains=ctx.search) | Q(narration__icontains=ctx.search) | Q(party__name__icontains=ctx.search))

        from apps.banking.models import ChequeLeaf
        entries = list(qs[:1000])
        v_ids = [e.voucher_id for e in entries]
        # Preload counter-ledger summaries & cheque numbers in single batch queries
        counter_map: dict[str, list[str]] = {}
        for vl in VoucherLine.objects.select_related("account").filter(voucher_id__in=v_ids).exclude(account=acc):
            counter_map.setdefault(str(vl.voucher_id), []).append(f"{vl.account.code} {vl.account.name}")
        cheque_map: dict[str, str] = {}
        for cl in ChequeLeaf.objects.filter(voucher_id__in=v_ids).values("voucher_id", "cheque_number"):
            cheque_map.setdefault(str(cl["voucher_id"]), cl["cheque_number"] or "")

        running = opening_net
        tot_d = tot_c = Decimal("0.00")
        rows = []
        for e in entries:
            running += e.base_debit - e.base_credit
            tot_d += e.base_debit
            tot_c += e.base_credit
            counters = list(dict.fromkeys(counter_map.get(str(e.voucher_id), [])))[:3]
            rows.append({
                "id": str(e.id),
                "posting_date": e.posting_date.isoformat(),
                "bs_date": e.bs_date or ad_to_bs(e.posting_date).isoformat(),
                "voucher_id": str(e.voucher_id),
                "voucher_no": e.voucher.voucher_no,
                "voucher_type": e.voucher.voucher_type,
                "reference_no": e.voucher.reference_no or e.voucher.supplier_invoice_no or "",
                "cheque_no": cheque_map.get(str(e.voucher_id), ""),
                "party_name": e.party.name if e.party else (e.voucher.party_name or ""),
                "project_code": e.project.code if e.project else None,
                "site_name": e.site.name if e.site else None,
                "cost_center_name": e.cost_center.name if e.cost_center else None,
                "cost_code": e.cost_code.code if e.cost_code else None,
                "counter_accounts": ", ".join(counters),
                "narration": e.narration if ctx.show_narration else "",
                "debit": str(e.base_debit),
                "credit": str(e.base_credit),
                "running_balance": str(abs(running)),
                "running_side": "Dr" if running >= 0 else "Cr",
                "running_signed": str(running),
                "is_reversed": e.voucher.status == Voucher.Status.REVERSED or bool(e.voucher.reversed_from_id),
            })

        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="general_ledger", title=f"General Ledger — {acc.code} {acc.name}", row_count=len(rows)),
            "account": {
                "id": str(acc.id),
                "code": acc.code,
                "name": acc.name,
                "group_name": acc.parent.name if acc.parent else acc.account_type,
                "account_type": acc.account_type,
                "normal_balance": acc.normal_balance,
            },
            "opening_balance": str(abs(opening_net)),
            "opening_side": "Dr" if opening_net >= 0 else "Cr",
            "opening_signed": str(opening_net),
            "closing_balance": str(abs(running)),
            "closing_side": "Dr" if running >= 0 else "Cr",
            "closing_signed": str(running),
            "total_debit": str(tot_d),
            "total_credit": str(tot_c),
            "rows": rows,
        }


class ProfitLossReportService:
    DIRECT_ROLES = {Account.ControlRole.DIRECT_EXPENSES, Account.ControlRole.PROJECT_WIP}

    @staticmethod
    def _pl_bucket(company, user, membership, ctx: ReportFilterContext, d_from: date | None, d_to: date | None) -> dict:
        qs = _apply_ledger_filters(
            LedgerEntry.objects.select_related("account", "account__parent").filter(
                company=company, account__account_type__in=[Account.AccountType.INCOME, Account.AccountType.EXPENSE]
            ),
            ctx,
            user,
            membership,
        )
        if d_from:
            qs = qs.filter(posting_date__gte=d_from)
        if d_to:
            qs = qs.filter(posting_date__lte=d_to)
        agg = qs.values(
            "account_id", "account__code", "account__name", "account__account_type",
            "account__account_class", "account__control_role", "account__parent__name",
        ).annotate(d=Sum("base_debit"), c=Sum("base_credit"))
        by_acc = {}
        for r in agg:
            d = r["d"] or Decimal("0.00")
            c = r["c"] or Decimal("0.00")
            net = (c - d) if r["account__account_type"] == Account.AccountType.INCOME else (d - c)
            by_acc[str(r["account_id"])] = {**r, "net": net}
        return by_acc

    @staticmethod
    def build(*, company, user, membership, ctx: ReportFilterContext) -> dict:
        d_from = ctx.date_from
        d_to = ctx.date_to or timezone.localdate()
        curr_map = ProfitLossReportService._pl_bucket(company, user, membership, ctx, d_from, d_to)

        p_from, p_to = _prev_period(d_from, d_to, ctx.compare_with or "PREVIOUS_PERIOD")
        prev_map = ProfitLossReportService._pl_bucket(company, user, membership, ctx, p_from, p_to) if p_to else {}

        ytd_start = date(d_to.year, 1, 1)
        ytd_map = ProfitLossReportService._pl_bucket(company, user, membership, ctx, ytd_start, d_to)

        budget_qs = BudgetLine.objects.filter(
            budget_version__budget__company=company,
            budget_version__is_active=True,
            budget_version__budget__status__in=["APPROVED", "LOCKED"],
        )
        if ctx.project_id:
            budget_qs = budget_qs.filter(budget_version__budget__project_id=ctx.project_id)
        budget_by_acc = {
            str(r["account_id"]): (r["amt"] or Decimal("0.00"))
            for r in budget_qs.exclude(account__isnull=True).values("account_id").annotate(amt=Sum("approved_amount"))
        }

        income_rows, direct_cost_rows, op_exp_rows, non_op_rows = [], [], [], []
        tot_inc = tot_direct = tot_op_exp = tot_non_op = Decimal("0.00")

        all_ids = set(curr_map.keys()) | set(prev_map.keys())
        for aid in sorted(all_ids, key=lambda i: (curr_map.get(i) or prev_map[i])["account__code"]):
            meta_r = curr_map.get(aid) or prev_map[aid]
            curr_val = (curr_map.get(aid) or {}).get("net", Decimal("0.00"))
            prev_val = (prev_map.get(aid) or {}).get("net", Decimal("0.00"))
            ytd_val = (ytd_map.get(aid) or {}).get("net", curr_val)
            bgt_val = budget_by_acc.get(aid, Decimal("0.00"))
            var = curr_val - prev_val
            var_pct = ((var * Decimal("100") / abs(prev_val)).quantize(Q2) if prev_val else Decimal("0.00"))

            row = {
                "account_id": aid,
                "code": meta_r["account__code"],
                "name": meta_r["account__name"],
                "group_name": meta_r["account__parent__name"] or meta_r["account__account_type"],
                "current": str(curr_val),
                "previous": str(prev_val),
                "variance": str(var),
                "variance_pct": str(var_pct),
                "ytd": str(ytd_val),
                "budget": str(bgt_val),
            }
            atype = meta_r["account__account_type"]
            aclass = meta_r["account__account_class"]
            role = meta_r["account__control_role"]
            code_str = meta_r["account__code"]

            if atype == Account.AccountType.INCOME:
                tot_inc += curr_val
                income_rows.append(row)
            elif role in ProfitLossReportService.DIRECT_ROLES or code_str.startswith(("50", "51", "52")):
                tot_direct += curr_val
                direct_cost_rows.append(row)
            elif aclass in (Account.AccountClass.LOSS,) or "interest" in meta_r["account__name"].lower() or "finance" in meta_r["account__name"].lower():
                tot_non_op += curr_val
                non_op_rows.append(row)
            else:
                tot_op_exp += curr_val
                op_exp_rows.append(row)

        gross_profit = tot_inc - tot_direct
        operating_profit = gross_profit - tot_op_exp
        net_profit = operating_profit - tot_non_op

        def _pct(num: Decimal) -> str:
            return str((num * Decimal("100") / tot_inc).quantize(Q2)) if tot_inc > 0 else "0.00"

        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="profit_loss", title="Statement of Profit & Loss", row_count=len(all_ids)),
            "sections": {
                "income": {"rows": income_rows, "total": str(tot_inc)},
                "direct_costs": {"rows": direct_cost_rows, "total": str(tot_direct)},
                "operating_expenses": {"rows": op_exp_rows, "total": str(tot_op_exp)},
                "non_operating": {"rows": non_op_rows, "total": str(tot_non_op)},
            },
            "summary": {
                "total_revenue": str(tot_inc),
                "total_direct_costs": str(tot_direct),
                "gross_profit": str(gross_profit),
                "gross_margin_pct": _pct(gross_profit),
                "total_operating_expenses": str(tot_op_exp),
                "operating_profit": str(operating_profit),
                "operating_margin_pct": _pct(operating_profit),
                "net_non_operating": str(tot_non_op),
                "net_profit": str(net_profit),
                "net_margin_pct": _pct(net_profit),
            },
        }


class BalanceSheetReportService:
    NON_CURRENT_ASSET_PREFIXES = ("15", "16", "17", "18")
    NON_CURRENT_LIAB_PREFIXES = ("25", "26", "27", "28")

    @staticmethod
    def build(*, company, user, membership, ctx: ReportFilterContext) -> dict:
        tb = TrialBalanceReportService.build(company=company, user=user, membership=membership, ctx=ctx)
        curr_assets, non_curr_assets = [], []
        curr_liab, non_curr_liab, equity_rows = [], [], []
        tot_ca = tot_nca = tot_cl = tot_ncl = tot_eq = net_income = Decimal("0.00")

        for r in tb["rows"]:
            d = Decimal(r["closing_debit"])
            c = Decimal(r["closing_credit"])
            atype = r["account_type"]
            code = r["code"]
            if atype == Account.AccountType.ASSET:
                bal = d - c
                row = {**r, "balance": str(bal)}
                if code.startswith(BalanceSheetReportService.NON_CURRENT_ASSET_PREFIXES) or "land" in r["name"].lower() or "machinery" in r["name"].lower() or "accumulated depreciation" in r["name"].lower():
                    tot_nca += bal
                    non_curr_assets.append(row)
                else:
                    tot_ca += bal
                    curr_assets.append(row)
            elif atype == Account.AccountType.LIABILITY:
                bal = c - d
                row = {**r, "balance": str(bal)}
                if code.startswith(BalanceSheetReportService.NON_CURRENT_LIAB_PREFIXES) or "long-term" in r["name"].lower() or "lease" in r["name"].lower():
                    tot_ncl += bal
                    non_curr_liab.append(row)
                else:
                    tot_cl += bal
                    curr_liab.append(row)
            elif atype == Account.AccountType.EQUITY:
                bal = c - d
                tot_eq += bal
                equity_rows.append({**r, "balance": str(bal)})
            elif atype == Account.AccountType.INCOME:
                net_income += c - d
            elif atype == Account.AccountType.EXPENSE:
                net_income -= d - c

        tot_assets = tot_ca + tot_nca
        tot_liab = tot_cl + tot_ncl
        tot_equity_with_pl = tot_eq + net_income
        tot_liab_and_eq = tot_liab + tot_equity_with_pl

        working_cap = tot_ca - tot_cl
        curr_ratio = str((tot_ca / tot_cl).quantize(Q2)) if tot_cl > 0 else "0.00"
        d_to_e = str((tot_liab / tot_equity_with_pl).quantize(Q2)) if tot_equity_with_pl > 0 else "0.00"

        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="balance_sheet", title="Balance Sheet", row_count=len(tb["rows"])),
            "assets": {
                "current": {"rows": curr_assets, "total": str(tot_ca)},
                "non_current": {"rows": non_curr_assets, "total": str(tot_nca)},
                "total": str(tot_assets),
            },
            "liabilities": {
                "current": {"rows": curr_liab, "total": str(tot_cl)},
                "non_current": {"rows": non_curr_liab, "total": str(tot_ncl)},
                "total": str(tot_liab),
            },
            "equity": {
                "rows": equity_rows,
                "current_year_profit_loss": str(net_income),
                "total": str(tot_equity_with_pl),
            },
            "summary": {
                "total_assets": str(tot_assets),
                "total_liabilities": str(tot_liab),
                "total_equity": str(tot_equity_with_pl),
                "total_liabilities_and_equity": str(tot_liab_and_eq),
                "difference": str(tot_assets - tot_liab_and_eq),
                "is_balanced": tot_assets == tot_liab_and_eq,
                "working_capital": str(working_cap),
                "current_ratio": curr_ratio,
                "debt_to_equity": d_to_e,
            },
        }


class VoucherRegisterReportService:
    @staticmethod
    def build(*, company, user, membership, ctx: ReportFilterContext) -> dict:
        qs = Voucher.objects.select_related("project", "site", "party", "created_by", "approved_by", "posted_by").prefetch_related("lines").filter(company=company)
        qs = ReportFilterEngine.scope_qs(qs, user=user, membership=membership)
        if ctx.project_id:
            qs = qs.filter(project_id=ctx.project_id)
        if ctx.party_id:
            qs = qs.filter(party_id=ctx.party_id)
        if ctx.voucher_type:
            qs = qs.filter(voucher_type=ctx.voucher_type)
        if ctx.date_from:
            qs = qs.filter(voucher_date__gte=ctx.date_from)
        if ctx.date_to:
            qs = qs.filter(voucher_date__lte=ctx.date_to)

        ps = ctx.posted_status
        if ps == "POSTED":
            qs = qs.filter(status=Voucher.Status.POSTED)
        elif ps == "DRAFT":
            qs = qs.filter(status=Voucher.Status.DRAFT)
        elif ps == "UNPOSTED":
            qs = qs.exclude(status__in=[Voucher.Status.POSTED, Voucher.Status.REVERSED, Voucher.Status.CANCELLED])
        elif ps == "REVERSED":
            qs = qs.filter(Q(status=Voucher.Status.REVERSED) | Q(reversed_from__isnull=False))

        if ctx.search:
            qs = qs.filter(Q(voucher_no__icontains=ctx.search) | Q(narration__icontains=ctx.search) | Q(reference_no__icontains=ctx.search))

        rows = []
        tot_dr = tot_cr = Decimal("0.00")
        for v in qs.order_by("-voucher_date", "-created_at")[:500]:
            dr = sum((l.debit for l in v.lines.all()), Decimal("0.00"))
            cr = sum((l.credit for l in v.lines.all()), Decimal("0.00"))
            tot_dr += dr
            tot_cr += cr
            rows.append({
                "id": str(v.id),
                "voucher_date": v.voucher_date.isoformat(),
                "bs_date": v.bs_date or ad_to_bs(v.voucher_date).isoformat(),
                "voucher_no": v.voucher_no or f"DRAFT-{str(v.id)[:6]}",
                "voucher_type": v.voucher_type,
                "reference_no": v.reference_no or v.supplier_invoice_no or "",
                "party_name": v.party.name if v.party else v.party_name,
                "project_code": v.project.code if v.project else "HO",
                "narration": v.narration if ctx.show_narration else "",
                "debit": str(dr),
                "credit": str(cr),
                "status": v.status,
                "created_by": v.created_by.username if v.created_by else "",
                "approved_by": v.approved_by.username if v.approved_by else "",
            })

        # Duplicate reference check
        dup_refs = list(
            qs.exclude(reference_no="").values("reference_no").annotate(cnt=Count("id")).filter(cnt__gt=1).values("reference_no", "cnt")[:25]
        )

        return {
            "meta": ReportFilterEngine.build_meta(company=company, ctx=ctx, report_code="voucher_register", title="Voucher Register", row_count=len(rows)),
            "rows": rows,
            "summary": {
                "count": len(rows),
                "total_debit": str(tot_dr),
                "total_credit": str(tot_cr),
                "duplicate_references": dup_refs,
            },
        }
