import csv
from decimal import Decimal
import io
import openpyxl

from apps.accounting.models import LedgerEntry
from apps.banking.models import (
    BankAccount,
    BankStatementLine,
    CashAccount,
    CashCountReconciliation,
    CashTransfer,
    ChequeBook,
    ChequeLeaf,
    ImprestAdvance,
    ImprestSettlement,
)
from apps.banking.services import BankingService
from apps.currency.models import ExchangeRate, FxRevaluationRun
from apps.loans.models import (
    BankFacility,
    BankGuarantee,
    FacilityCollateralLink,
    GuaranteeAmendment,
    InterestCalculationRun,
    LoanCollateral,
    LoanDisbursement,
    LoanInterestAccrual,
    LoanRepayment,
    LoanScheduleInstallment,
)
from apps.loans.services import LoanService


REPORT_CATALOG = [
    # Bank Reports (1-11)
    {"code": "BANK_REGISTER", "group": "BANKING", "label": "Bank Account Register"},
    {"code": "BANK_LEDGER", "group": "BANKING", "label": "Bank Ledger"},
    {"code": "BANK_WISE_SUMMARY", "group": "BANKING", "label": "Bank Transaction Register & Summary"},
    {"code": "DAILY_BANK_BALANCE", "group": "BANKING", "label": "Daily Bank Balance"},
    {"code": "DAILY_BANK_MOVEMENT", "group": "BANKING", "label": "Cash Position & Daily Movement"},
    {"code": "BRS_SUMMARY", "group": "RECONCILIATION", "label": "Bank Reconciliation Statement"},
    {"code": "OUTSTANDING_CHEQUES", "group": "CHEQUE", "label": "Outstanding Unpresented Cheques"},
    {"code": "CHEQUES_IN_HAND", "group": "CHEQUE", "label": "Cheques-in-Hand"},
    {"code": "CHEQUES_IN_CLEARING", "group": "CHEQUE", "label": "Cheques-in-Clearing"},
    {"code": "BANK_CHARGES", "group": "BANKING", "label": "Bank Charges Register"},
    {"code": "INTEREST_INCOME", "group": "BANKING", "label": "Bank Interest Income"},
    {"code": "UNRECONCILED_ITEMS", "group": "RECONCILIATION", "label": "Unreconciled Bank Statement Items"},
    {"code": "TRANSFER_REGISTER", "group": "BANKING", "label": "Inter-Bank & Cash Transfer Register"},
    # Cash Reports (12-19)
    {"code": "CASH_REGISTER", "group": "CASH", "label": "Cash Register"},
    {"code": "CASH_CUSTODY", "group": "CASH", "label": "Cash Custody Register"},
    {"code": "IMPREST_REGISTER", "group": "CASH", "label": "Imprest Advance Register"},
    {"code": "ADVANCE_SETTLEMENT", "group": "CASH", "label": "Imprest Settlement Register"},
    {"code": "CASH_COUNT_REGISTER", "group": "CASH", "label": "Physical Cash Count"},
    {"code": "CASH_SHORTAGE_EXCESS", "group": "CASH", "label": "Cash Shortage / Excess Report"},
    {"code": "BRANCH_CASH_SUMMARY", "group": "CASH", "label": "Branch-wise Cash Summary"},
    {"code": "SITE_CASH_SUMMARY", "group": "CASH", "label": "Site-wise Cash Summary"},
    # Cheques & FX
    {"code": "ISSUED_CHEQUES", "group": "CHEQUE", "label": "Issued Cheque Register"},
    {"code": "RECEIVED_CHEQUES", "group": "CHEQUE", "label": "Received Cheque Register"},
    {"code": "BOUNCED_CHEQUES", "group": "CHEQUE", "label": "Bounced & Cancelled Cheques"},
    {"code": "CHEQUE_BOOK_STOCK", "group": "CHEQUE", "label": "Cheque Book Stock & Consumption"},
    {"code": "FX_BANK_BALANCES", "group": "FX", "label": "Foreign Currency Bank Balances"},
    {"code": "NRB_RATE_HISTORY", "group": "FX", "label": "NRB vs Actual Bank FX Rate Variance"},
    {"code": "FX_REVALUATIONS", "group": "FX", "label": "FX Unrealized Revaluation Register"},
    # Loan Reports (20-32)
    {"code": "LOAN_REGISTER", "group": "LOANS", "label": "Loan Facility Register"},
    {"code": "FACILITY_OUTSTANDING", "group": "LOANS", "label": "Loan Outstanding & Available Limit"},
    {"code": "DISBURSEMENT_REGISTER", "group": "LOANS", "label": "Loan Disbursement Register"},
    {"code": "TERM_LOAN_SCHEDULE", "group": "LOANS", "label": "Loan Repayment Schedule"},
    {"code": "REPAYMENT_HISTORY", "group": "LOANS", "label": "Principal & Interest Repayment History"},
    {"code": "INTEREST_CALCULATION_RUNS", "group": "LOANS", "label": "Interest Calculation Runs"},
    {"code": "LOAN_INTEREST_ACCRUALS", "group": "LOANS", "label": "Interest Accrual & Bank Variance"},
    {"code": "INTEREST_PAID_REGISTER", "group": "LOANS", "label": "Interest Paid Register"},
    {"code": "PENAL_INTEREST_REPORT", "group": "LOANS", "label": "Penal & Excess Utilization Interest"},
    {"code": "LOAN_MATURITY", "group": "LOANS", "label": "Loan Maturity Schedule"},
    {"code": "OD_UTILIZATION", "group": "LOANS", "label": "OD/CC Daily Utilization"},
    {"code": "CC_DRAWING_POWER", "group": "LOANS", "label": "Cash Credit (CC) Drawing Power"},
    {"code": "FACILITY_RENEWAL", "group": "LOANS", "label": "Facility Renewal & Review Register"},
    # Guarantee & Collateral Reports (33-48)
    {"code": "BG_EXPOSURE", "group": "GUARANTEES", "label": "Bank Guarantee Register"},
    {"code": "ACTIVE_BG_EXPOSURE", "group": "GUARANTEES", "label": "Active Guarantee Exposure"},
    {"code": "BG_BY_BANK", "group": "GUARANTEES", "label": "Guarantee by Issuing Bank"},
    {"code": "BG_BY_PROJECT", "group": "GUARANTEES", "label": "Guarantee by Project"},
    {"code": "BG_BY_BENEFICIARY", "group": "GUARANTEES", "label": "Guarantee by Beneficiary"},
    {"code": "BG_EXPIRY_CALENDAR", "group": "GUARANTEES", "label": "Guarantee Expiry Calendar"},
    {"code": "BG_EXPIRED_AWAITING_RELEASE", "group": "GUARANTEES", "label": "Expired BGs Awaiting Release"},
    {"code": "BG_INVOKED", "group": "GUARANTEES", "label": "Invoked Guarantee Register"},
    {"code": "BG_RELEASED", "group": "GUARANTEES", "label": "Released Guarantee Register"},
    {"code": "BG_AMENDMENT_HISTORY", "group": "GUARANTEES", "label": "Guarantee Amendment History"},
    {"code": "BG_COMMISSION", "group": "GUARANTEES", "label": "Guarantee Commission & Margin Charges"},
    {"code": "COLLATERAL_SUMMARY", "group": "COLLATERAL", "label": "Collateral Register"},
    {"code": "COLLATERAL_VALUATION", "group": "COLLATERAL", "label": "Collateral Valuation & Haircuts"},
    {"code": "ENCUMBERED_COLLATERAL", "group": "COLLATERAL", "label": "Encumbered Collateral Allocations"},
    {"code": "COLLATERAL_RELEASE_PENDING", "group": "COLLATERAL", "label": "Collateral Release Status"},
    {"code": "CASH_MARGIN_BLOCKED", "group": "GUARANTEES", "label": "Cash Margin Blocked Deposit Register"},
    # Treasury Management Reports (49-55)
    {"code": "TREASURY_CASH_FLOW", "group": "TREASURY", "label": "Treasury Cash Flow Statement"},
    {"code": "BANK_WISE_EXPOSURE", "group": "TREASURY", "label": "Bank-wise Total Financial Exposure"},
    {"code": "LOAN_INTEREST_FORECAST", "group": "TREASURY", "label": "Loan Principal & Interest Forecast"},
    {"code": "CURRENCY_EXPOSURE_REPORT", "group": "TREASURY", "label": "Multi-Currency Net Exposure"},
    {"code": "FACILITY_UTILIZATION", "group": "TREASURY", "label": "Facility Utilization Summary"},
    {"code": "TREASURY_RISK_SUMMARY", "group": "TREASURY", "label": "Treasury Executive Risk & Alerts Summary"},
    {"code": "PROJECT_FINANCING_COST", "group": "TREASURY", "label": "Project-wise Financing Cost & Exposure"},
]


class TreasuryReportsService:
    @staticmethod
    def run_report(*, company, report_code: str, bank_account_id: str | None = None, project_id: str | None = None) -> list[dict]:
        code = report_code.upper()
        if code in ("BANK_REGISTER", "BANK_WISE_SUMMARY", "FX_BANK_BALANCES", "DAILY_BANK_BALANCE"):
            qs = BankAccount.objects.select_related("bank_branch__bank", "gl_account", "project").filter(company=company)
            if code == "FX_BANK_BALANCES":
                qs = qs.exclude(currency=company.base_currency)
            if bank_account_id:
                qs = qs.filter(id=bank_account_id)
            if project_id:
                qs = qs.filter(project_id=project_id)
            return [
                {
                    "account_code": ba.account_code,
                    "account_name": ba.account_name,
                    "bank": ba.bank_branch.bank.name,
                    "masked_no": ba.account_number_masked,
                    "type": ba.account_type,
                    "currency": ba.currency,
                    "gl_code": ba.gl_account.code,
                    "book_balance": str(BankingService.get_gl_balance(ba.gl_account)),
                    "status": ba.status,
                }
                for ba in qs
            ]

        if code == "TRANSFER_REGISTER":
            qs = CashTransfer.objects.select_related("from_gl_account", "to_gl_account", "voucher").filter(company=company).order_by("-transfer_date")
            return [
                {
                    "date": t.transfer_date.isoformat(),
                    "type": t.transfer_type,
                    "from": t.from_gl_account.code,
                    "to": t.to_gl_account.code,
                    "amount": str(t.amount),
                    "fee": str(t.fee_amount),
                    "currency": t.currency,
                    "ref": t.transfer_ref,
                    "voucher_no": t.voucher.voucher_no if t.voucher else "",
                }
                for t in qs[:300]
            ]

        if code in ("BANK_CHARGES", "INTEREST_INCOME", "DAILY_BANK_MOVEMENT", "BANK_LEDGER", "CASH_REGISTER"):
            qs = LedgerEntry.objects.select_related("account", "voucher").filter(company=company).order_by("-posting_date")
            if code == "BANK_CHARGES":
                qs = qs.filter(account__code="5230")
            elif code == "INTEREST_INCOME":
                qs = qs.filter(account__code="4230")
            elif code == "BANK_LEDGER":
                qs = qs.filter(account__control_role="BANK")
            elif code == "CASH_REGISTER":
                qs = qs.filter(account__control_role="CASH")
            else:
                qs = qs.filter(account__control_role__in=["BANK", "CASH"])
            return [
                {
                    "date": e.posting_date.isoformat(),
                    "voucher_no": e.voucher.voucher_no if e.voucher else "",
                    "account": f"{e.account.code} - {e.account.name}",
                    "debit": str(e.base_debit),
                    "credit": str(e.base_credit),
                    "narration": e.voucher.narration if e.voucher else "",
                }
                for e in qs[:300]
            ]

        if code == "BRS_SUMMARY":
            from apps.banking.models import BankReconciliationSession
            return [
                {
                    "bank_account": s.bank_account.account_name,
                    "period": f"{s.period_start}..{s.period_end}",
                    "statement_balance": str(s.statement_closing_balance),
                    "book_balance": str(s.book_closing_balance),
                    "difference": str(s.unreconciled_difference),
                    "status": s.status,
                }
                for s in BankReconciliationSession.objects.select_related("bank_account").filter(company=company)
            ]

        if code == "UNRECONCILED_ITEMS":
            qs = BankStatementLine.objects.select_related("bank_account").filter(
                company=company, match_status__in=["UNMATCHED", "UNDER_REVIEW", "PARTIAL"]
            )
            if bank_account_id:
                qs = qs.filter(bank_account_id=bank_account_id)
            return [
                {
                    "bank_account": ln.bank_account.account_name,
                    "txn_date": ln.txn_date.isoformat(),
                    "ref": ln.reference_no,
                    "cheque_no": ln.cheque_no,
                    "description": ln.description,
                    "debit": str(ln.debit),
                    "credit": str(ln.credit),
                    "status": ln.match_status,
                }
                for ln in qs[:300]
            ]

        if code in ("CASH_CUSTODY", "SITE_CASH_SUMMARY"):
            qs = CashAccount.objects.select_related("custodian", "project", "site", "gl_account").filter(company=company)
            if code == "SITE_CASH_SUMMARY":
                qs = qs.filter(project__isnull=False)
            if project_id:
                qs = qs.filter(project_id=project_id)
            return [
                {
                    "code": c.code,
                    "name": c.name,
                    "type": c.cash_type,
                    "custodian": c.custodian.username if c.custodian else "Unassigned",
                    "project": c.project.code if c.project else "",
                    "site": c.site.code if c.site else "",
                    "imprest_limit": str(c.imprest_limit),
                    "balance": str(BankingService.get_gl_balance(c.gl_account)),
                }
                for c in qs
            ]

        if code == "IMPREST_REGISTER":
            qs = ImprestAdvance.objects.select_related("cash_account", "custodian", "project").filter(company=company)
            return [
                {
                    "imprest_no": i.imprest_no,
                    "custodian": i.custodian.username,
                    "cash_account": i.cash_account.name,
                    "project": i.project.code if i.project else "",
                    "issued": str(i.issued_amount),
                    "settled": str(i.settled_expense_amount),
                    "returned": str(i.returned_cash_amount),
                    "outstanding": str(i.outstanding_balance),
                    "status": i.status,
                }
                for i in qs
            ]

        if code == "ADVANCE_SETTLEMENT":
            qs = ImprestSettlement.objects.select_related("imprest", "settlement_voucher").filter(company=company)
            return [
                {
                    "imprest_no": s.imprest.imprest_no,
                    "date": s.settlement_date.isoformat(),
                    "verified_expenses": str(s.verified_expense_total),
                    "returned_cash": str(s.unused_cash_returned),
                    "replenished": str(s.replenished_amount),
                    "voucher_no": s.settlement_voucher.voucher_no if s.settlement_voucher else "",
                    "status": s.status,
                }
                for s in qs
            ]

        if code == "CASH_COUNT_REGISTER":
            qs = CashCountReconciliation.objects.select_related("cash_account", "counted_by", "voucher").filter(company=company)
            return [
                {
                    "date": c.count_date.isoformat(),
                    "cash_account": c.cash_account.name,
                    "book_balance": str(c.book_balance),
                    "physical_balance": str(c.physical_balance),
                    "variance": str(c.variance),
                    "surprise": "Yes" if c.is_surprise_check else "No",
                    "status": c.status,
                    "voucher_no": c.voucher.voucher_no if c.voucher else "",
                }
                for c in qs
            ]

        if code in ("ISSUED_CHEQUES", "RECEIVED_CHEQUES", "OUTSTANDING_CHEQUES", "BOUNCED_CHEQUES"):
            qs = ChequeLeaf.objects.select_related("bank_account", "voucher", "project").filter(company=company).exclude(status="AVAILABLE")
            if code == "ISSUED_CHEQUES":
                qs = qs.filter(direction="ISSUED")
            elif code == "RECEIVED_CHEQUES":
                qs = qs.filter(direction="RECEIVED")
            elif code == "OUTSTANDING_CHEQUES":
                qs = qs.filter(status__in=["ISSUED", "PRESENTED", "IN_HAND", "DEPOSITED", "UNDER_CLEARING"])
            elif code == "BOUNCED_CHEQUES":
                qs = qs.filter(status__in=["BOUNCED", "CANCELLED"])
            return [
                {
                    "cheque_no": c.cheque_number,
                    "direction": c.direction,
                    "bank_account": c.bank_account.account_name,
                    "party": c.party_name or c.drawer_name,
                    "cheque_date": c.cheque_date.isoformat() if c.cheque_date else "",
                    "amount": str(c.amount),
                    "status": c.status,
                    "voucher_no": c.voucher.voucher_no if c.voucher else "",
                    "reason": c.bounce_reason,
                }
                for c in qs[:400]
            ]

        if code == "CHEQUE_BOOK_STOCK":
            return [
                {
                    "book_code": b.book_code,
                    "bank_account": b.bank_account.account_name,
                    "range": f"{b.prefix}{b.start_number}..{b.end_number}",
                    "total": b.end_number - b.start_number + 1,
                    "available": b.leaves.filter(status="AVAILABLE").count(),
                    "issued": b.leaves.exclude(status="AVAILABLE").count(),
                    "status": b.status,
                }
                for b in ChequeBook.objects.select_related("bank_account").filter(company=company)
            ]

        if code == "NRB_RATE_HISTORY":
            return [
                {
                    "date": r.effective_date.isoformat(),
                    "currency": r.from_currency,
                    "unit": r.unit,
                    "source": r.rate_source,
                    "bank": r.bank_name,
                    "buy": str(r.buy_rate),
                    "sell": str(r.sell_rate),
                    "mid": str(r.mid_rate),
                }
                for r in ExchangeRate.objects.filter(company=company)[:300]
            ]

        if code == "FX_REVALUATIONS":
            return [
                {
                    "date": r.revaluation_date.isoformat(),
                    "currency": r.currency_code,
                    "scope": r.scope,
                    "closing_rate": str(r.closing_rate),
                    "gain_loss": str(r.unrealized_gain_loss),
                    "voucher_no": r.voucher.voucher_no if r.voucher else "",
                }
                for r in FxRevaluationRun.objects.select_related("voucher").filter(company=company)
            ]

        if code in ("LOAN_REGISTER", "FACILITY_OUTSTANDING", "OD_UTILIZATION", "CC_DRAWING_POWER", "LOAN_MATURITY"):
            qs = BankFacility.objects.select_related("bank_account__bank_branch__bank", "project").filter(company=company)
            if code == "OD_UTILIZATION":
                qs = qs.filter(facility_type="OVERDRAFT")
            elif code == "CC_DRAWING_POWER":
                qs = qs.filter(facility_type="CASH_CREDIT")
            return [
                {
                    "code": f.facility_code,
                    "name": f.facility_name,
                    "type": f.facility_type,
                    "bank": f.bank_account.bank_branch.bank.short_code,
                    "sanctioned": str(f.sanctioned_limit),
                    "outstanding": str(LoanService.get_outstanding_principal(f)),
                    "rate": f"{f.effective_interest_rate}%",
                    "basis": f.day_count_basis,
                    "maturity": f.maturity_date.isoformat(),
                    "status": f.status,
                }
                for f in qs
            ]

        if code == "TERM_LOAN_SCHEDULE":
            return [
                {
                    "facility": i.facility.facility_code,
                    "installment": i.installment_no,
                    "due_date": i.due_date.isoformat(),
                    "principal_due": str(i.principal_due),
                    "interest_due": str(i.interest_due),
                    "principal_paid": str(i.principal_paid),
                    "status": i.status,
                }
                for i in LoanScheduleInstallment.objects.select_related("facility").filter(facility__company=company)[:400]
            ]

        if code == "LOAN_INTEREST_ACCRUALS":
            return [
                {
                    "facility": a.facility.facility_code,
                    "period": f"{a.period_start}..{a.period_end}",
                    "days": a.days,
                    "basis": a.day_count_basis,
                    "principal": str(a.average_principal),
                    "rate": f"{a.effective_rate}%",
                    "system_interest": str(a.system_calculated_interest),
                    "bank_interest": str(a.bank_debited_interest or ""),
                    "variance": str(a.variance_amount),
                    "status": a.status,
                }
                for a in LoanInterestAccrual.objects.select_related("facility").filter(company=company)
            ]

        if code == "REPAYMENT_HISTORY":
            return [
                {
                    "facility": r.facility.facility_code,
                    "date": r.payment_date.isoformat(),
                    "principal": str(r.principal_amount),
                    "interest": str(r.interest_amount),
                    "penal": str(r.penal_amount),
                    "prepayment": "Yes" if r.is_prepayment else "No",
                    "voucher_no": r.voucher.voucher_no if r.voucher else "",
                }
                for r in LoanRepayment.objects.select_related("facility", "voucher").filter(facility__company=company)[:300]
            ]

        if code in ("COLLATERAL_SUMMARY", "COLLATERAL_VALUATION", "COLLATERAL_RELEASE_PENDING"):
            qs = LoanCollateral.objects.select_related("facility", "project").prefetch_related("allocations").filter(company=company)
            if code == "COLLATERAL_RELEASE_PENDING":
                qs = qs.filter(lifecycle_status__in=["RELEASE_REQUESTED", "BANK_DISCHARGED"])
            return [
                {
                    "collateral_code": c.collateral_code or str(c.id)[:8],
                    "type": c.security_type,
                    "description": c.description,
                    "owner": c.owner_name,
                    "market_value": str(c.market_value),
                    "haircut_pct": str(c.haircut_pct),
                    "eligible_value": str(c.assessed_value),
                    "allocated": str(sum((a.allocated_value for a in c.allocations.filter(is_released=False)), Decimal("0.00"))),
                    "lifecycle_status": c.lifecycle_status,
                }
                for c in qs
            ]

        if code == "ENCUMBERED_COLLATERAL":
            return [
                {
                    "collateral": lnk.collateral.description,
                    "facility": lnk.facility.facility_code if lnk.facility else "",
                    "guarantee": lnk.guarantee.bg_number if lnk.guarantee else "",
                    "allocated_value": str(lnk.allocated_value),
                    "charge_rank": lnk.charge_rank,
                    "released": "Yes" if lnk.is_released else "No",
                }
                for lnk in FacilityCollateralLink.objects.select_related("collateral", "facility", "guarantee").filter(company=company)
            ]

        if code in ("BG_EXPOSURE", "ACTIVE_BG_EXPOSURE", "BG_BY_BANK", "BG_BY_PROJECT", "BG_BY_BENEFICIARY", "BG_EXPIRY_CALENDAR", "BG_EXPIRED_AWAITING_RELEASE", "BG_INVOKED", "BG_RELEASED", "BG_COMMISSION", "CASH_MARGIN_BLOCKED"):
            from django.utils import timezone
            qs = BankGuarantee.objects.select_related("bank_account__bank_branch__bank", "project").filter(company=company)
            if code == "ACTIVE_BG_EXPOSURE":
                qs = qs.filter(status__in=["ACTIVE", "EXTENDED", "AMENDED", "ISSUED"])
            elif code == "BG_EXPIRED_AWAITING_RELEASE":
                qs = qs.filter(expiry_date__lt=timezone.localdate()).exclude(status__in=["RELEASED", "INVOKED", "REVOKED"])
            elif code == "BG_INVOKED":
                qs = qs.filter(status__in=["INVOKED", "PARTIALLY_INVOKED", "CLAIMED"])
            elif code == "BG_RELEASED":
                qs = qs.filter(status="RELEASED")
            elif code == "CASH_MARGIN_BLOCKED":
                qs = qs.filter(margin_amount__gt=0).exclude(status="RELEASED")
            return [
                {
                    "bg_number": b.bg_number,
                    "type": b.bg_type,
                    "bank": b.bank_account.bank_branch.bank.short_code,
                    "project": b.project.code if b.project else "",
                    "beneficiary": b.beneficiary,
                    "amount": str(b.amount),
                    "margin": str(b.margin_amount),
                    "commission": str(b.commission_amount),
                    "expiry_date": b.expiry_date.isoformat(),
                    "status": b.status,
                }
                for b in qs
            ]

        if code == "BG_AMENDMENT_HISTORY":
            return [
                {
                    "bg_number": a.guarantee.bg_number,
                    "version": f"V{a.version_no}",
                    "date": a.amendment_date.isoformat(),
                    "type": a.amendment_type,
                    "prev_amount": str(a.previous_amount),
                    "new_amount": str(a.new_amount),
                    "charges": str(a.amendment_charges),
                    "reason": a.reason,
                }
                for a in GuaranteeAmendment.objects.select_related("guarantee").filter(company=company)
            ]

        if code in ("CHEQUES_IN_HAND", "CHEQUES_IN_CLEARING"):
            st = ["IN_HAND"] if code == "CHEQUES_IN_HAND" else ["DEPOSITED", "UNDER_CLEARING"]
            return [
                {
                    "cheque_no": c.cheque_number,
                    "party": c.party_name or c.drawer_name,
                    "bank_account": c.bank_account.account_name,
                    "amount": str(c.amount),
                    "cheque_date": c.cheque_date.isoformat() if c.cheque_date else "",
                    "status": c.status,
                }
                for c in ChequeLeaf.objects.select_related("bank_account").filter(company=company, status__in=st)
            ]

        if code in ("CASH_SHORTAGE_EXCESS", "BRANCH_CASH_SUMMARY"):
            if code == "CASH_SHORTAGE_EXCESS":
                return [
                    {
                        "date": c.count_date.isoformat(),
                        "cash_account": c.cash_account.name,
                        "variance": str(c.variance),
                        "status": c.status,
                    }
                    for c in CashCountReconciliation.objects.select_related("cash_account").filter(company=company).exclude(variance=0)
                ]
            return [
                {
                    "branch": c.branch.name if c.branch else "Head Office",
                    "cash_account": c.name,
                    "type": c.cash_type,
                    "balance": str(BankingService.get_gl_balance(c.gl_account)),
                }
                for c in CashAccount.objects.select_related("branch", "gl_account").filter(company=company)
            ]

        if code == "DISBURSEMENT_REGISTER":
            return [
                {
                    "facility": d.facility.facility_code,
                    "date": d.disbursement_date.isoformat(),
                    "amount": str(d.amount),
                    "ref": d.reference_no,
                    "voucher_no": d.voucher.voucher_no if d.voucher else "",
                }
                for d in LoanDisbursement.objects.select_related("facility", "voucher").filter(facility__company=company)
            ]

        if code in ("INTEREST_CALCULATION_RUNS", "INTEREST_PAID_REGISTER", "PENAL_INTEREST_REPORT", "FACILITY_RENEWAL"):
            if code == "INTEREST_CALCULATION_RUNS":
                return [
                    {
                        "facility": r.facility.facility_code,
                        "period": f"{r.period_start}..{r.period_end}",
                        "basis": r.day_count_basis,
                        "normal_interest": str(r.normal_interest),
                        "penal_interest": str(r.penal_interest),
                        "total": str(r.total_calculated),
                        "bank_charged": str(r.bank_charged_interest or ""),
                        "status": r.status,
                    }
                    for r in InterestCalculationRun.objects.select_related("facility").filter(company=company)
                ]
            if code == "INTEREST_PAID_REGISTER":
                return [
                    {
                        "facility": r.facility.facility_code,
                        "date": r.payment_date.isoformat(),
                        "interest_paid": str(r.interest_amount),
                        "penal_paid": str(r.penal_amount),
                        "voucher_no": r.voucher.voucher_no if r.voucher else "",
                    }
                    for r in LoanRepayment.objects.select_related("facility", "voucher").filter(facility__company=company, interest_amount__gt=0)
                ]
            if code == "PENAL_INTEREST_REPORT":
                return [
                    {
                        "facility": r.facility.facility_code,
                        "period": f"{r.period_start}..{r.period_end}",
                        "penal_interest": str(r.penal_interest),
                        "status": r.status,
                    }
                    for r in InterestCalculationRun.objects.select_related("facility").filter(company=company, penal_interest__gt=0)
                ]
            return [
                {
                    "facility": f.facility_code,
                    "name": f.facility_name,
                    "bank": f.bank_account.bank_branch.bank.short_code,
                    "renewal_date": f.renewal_date.isoformat() if f.renewal_date else "",
                    "maturity_date": f.maturity_date.isoformat(),
                    "sanctioned": str(f.sanctioned_limit),
                    "status": f.status,
                }
                for f in BankFacility.objects.select_related("bank_account__bank_branch__bank").filter(company=company)
            ]

        if code in ("TREASURY_CASH_FLOW", "BANK_WISE_EXPOSURE", "LOAN_INTEREST_FORECAST", "CURRENCY_EXPOSURE_REPORT", "FACILITY_UTILIZATION", "TREASURY_RISK_SUMMARY", "PROJECT_FINANCING_COST"):
            from .analytics_service import TreasuryAnalyticsService
            dash = TreasuryAnalyticsService.get_executive_dashboard(company=company)
            if code == "TREASURY_CASH_FLOW":
                return dash.get("monthly_cashflow", [])
            if code == "BANK_WISE_EXPOSURE":
                return dash.get("bank_wise_exposure", [])
            if code == "CURRENCY_EXPOSURE_REPORT":
                return dash.get("fx_exposure", [])
            if code in ("FACILITY_UTILIZATION", "LOAN_INTEREST_FORECAST"):
                return dash.get("loan_exposure", [])
            if code == "PROJECT_FINANCING_COST":
                return dash.get("project_wise_exposure", [])
            return dash.get("alerts", [])

        return []

    @staticmethod
    def export_rows_csv(rows: list[dict]) -> bytes:
        buf = io.StringIO()
        if rows:
            writer = csv.DictWriter(buf, fieldnames=list(rows[0].keys()))
            writer.writeheader()
            writer.writerows(rows)
        return buf.getvalue().encode("utf-8")

    @staticmethod
    def export_rows_xlsx(title: str, rows: list[dict]) -> bytes:
        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = "Treasury Report"
        ws.append([title])
        if rows:
            cols = list(rows[0].keys())
            ws.append(cols)
            for r in rows:
                ws.append([r.get(c, "") for c in cols])
        out = io.BytesIO()
        wb.save(out)
        return out.getvalue()

    @staticmethod
    def build_report_html(*, company, report_code: str, rows: list[dict], paper: str = "A4_PORTRAIT", generated_by: str = "") -> str:
        from django.utils import timezone
        from apps.document_engine.renderers.html_renderer import render_document_html
        from apps.document_engine.services.template_resolver import DEFAULT_LAYOUT_SCHEMA

        label = next((r["label"] for r in REPORT_CATALOG if r["code"] == report_code.upper()), report_code)
        paper_size = "A3" if paper == "A3" else ("LETTER" if paper == "LETTER" else "A4")
        orientation = "LANDSCAPE" if paper == "A4_LANDSCAPE" else "PORTRAIT"
        cols_keys = list(rows[0].keys()) if rows else ["status"]
        norm_rows = rows if rows else [{"status": "No records match the selected criteria."}]
        columns = [
            {
                "key": k,
                "label": k.replace("_", " ").title(),
                "type": "number" if any(t in k for t in ("amount", "balance", "principal", "interest", "debit", "credit", "margin", "limit", "value")) else "text",
                "align": "right" if any(t in k for t in ("amount", "balance", "principal", "interest", "debit", "credit", "margin", "limit", "value")) else "left",
            }
            for k in cols_keys
        ]
        payload = {
            "document_type": "TREASURY_REPORT",
            "title": label,
            "title_ne": "कोष तथा बैंकिङ्ग प्रतिवेदन",
            "source_model": "treasury.TreasuryReport",
            "source_id": report_code,
            "document_number": report_code,
            "issue_date": timezone.localdate(),
            "status": "VERIFIED",
            "currency": company.base_currency,
            "party": {"name": company.name, "pan_vat": company.pan_vat_no or "", "address": "", "contact": ""},
            "project": {"code": "TREASURY", "name": f"{len(rows)} Record(s)", "site": f"Generated by {generated_by or 'System'}"},
            "metadata": [
                {"label": "Report Code", "value": report_code},
                {"label": "Paper Profile", "value": paper},
                {"label": "Generated By", "value": generated_by or "Treasury User"},
                {"label": "Generated On", "value": timezone.now().strftime("%Y-%m-%d %H:%M")},
            ],
            "columns": columns,
            "rows": norm_rows,
            "totals": {"subtotal": Decimal("0.00"), "tax_label": "Rows", "tax_amount": Decimal(len(rows)), "grand_total": Decimal("0.00")},
            "narration": f"Maya OS Enterprise Treasury Print Studio — {label}",
            "terms": [],
        }
        resolved = {
            "layout_schema": DEFAULT_LAYOUT_SCHEMA,
            "settings": {
                "legal_name": company.name,
                "pan_vat_no": company.pan_vat_no or "",
                "registration_no": "",
                "company_address": "",
                "currency_symbol": company.base_currency,
            },
            "print_profile": {
                "paper_size": paper_size,
                "orientation": orientation,
                "margin_top_mm": 10,
                "margin_right_mm": 10,
                "margin_bottom_mm": 14,
                "margin_left_mm": 10,
                "show_header": True,
                "show_footer": True,
                "show_logo": True,
                "show_page_number": True,
                "show_page_count": True,
                "show_border": True,
                "show_qr_code": False,
                "show_barcode": False,
                "copy_type": "ORIGINAL",
                "language": "ENGLISH",
                "date_format": "AD",
                "accent_color": "#1d4ed8",
                "table_style": "STANDARD",
                "row_height_px": 20,
            },
            "signatures": [
                {"role": "Prepared By", "label": "Prepared By"},
                {"role": "Checked By", "label": "Checked By"},
                {"role": "Approved By", "label": "Approved By"},
            ],
            "stamp_data_uri": "",
        }
        return render_document_html(payload=payload, resolved=resolved)

    @staticmethod
    def build_report_pdf(*, company, report_code: str, rows: list[dict], paper: str = "A4_PORTRAIT", generated_by: str = "") -> bytes:
        from apps.document_engine.renderers.pdf_renderer import html_to_pdf_bytes
        html_str = TreasuryReportsService.build_report_html(
            company=company,
            report_code=report_code,
            rows=rows,
            paper=paper,
            generated_by=generated_by,
        )
        return html_to_pdf_bytes(html_str)

