import io
from datetime import date, timedelta
from decimal import Decimal
import openpyxl
from django.core.exceptions import ValidationError
from django.test import TestCase
from rest_framework.test import APIClient

from apps.accounting.models import Account, AdvanceRecord, BillAllocation, LedgerEntry, Party, Voucher
from apps.accounts_rbac.constants import Permissions, ROLE_PRESETS
from apps.accounts_rbac.models import CompanyMembership, Role, User
from apps.banking.models import Bank, BankAccount, BankBranch
from apps.construction_ops.models import OperationalDocument
from apps.party_hub.models import (
    ARAuditEvent,
    ARControlPolicy,
    CustomerProfile,
    CustomerReceipt,
    OpenItem,
    PartyDispute,
    RABill,
    ReceiptAllocationReversal,
    RetentionSchedule,
    SalesInvoice,
)
from apps.party_hub.services.ar_billing_service import (
    CustomerGovernanceService,
    RABillingService,
    SalesInvoiceService,
)
from apps.party_hub.services.ar_intelligence_service import ARIntelligenceService
from apps.party_hub.services.ar_receipt_allocation_service import ARReceiptAllocationService
from apps.party_hub.services.ar_reports_service import ARReportService
from apps.party_hub.services.ar_statement_recon_service import ARStatementReconciliationService
from apps.projects.models import (
    Project,
    ProjectBoqHeader,
    ProjectBoqLine,
    ProjectContract,
    ProjectVariationOrder,
)
from apps.tenancy.models import Company, FiscalYear


class EnterpriseSundryDebtors30AcceptanceTests(TestCase):
    """Covers all 30 Mandatory Acceptance Tests for the Enterprise Sundry Debtors Hub (AR)."""

    def setUp(self):
        self.maker = User.objects.create_user(username="ar_maker", email="maker@maya.local", password="Password@123")
        self.checker = User.objects.create_user(username="ar_checker", email="checker@maya.local", password="Password@123")
        self.collector = User.objects.create_user(username="ar_collector", email="col@maya.local", password="Password@123")

        self.company = Company.objects.create(code="AR01", name="Everest Builders Ltd", pan_vat_no="601234567")
        self.fy = FiscalYear.objects.create(
            company=self.company, name="FY 2083/84",
            start_date=date(2026, 7, 16), end_date=date(2027, 7, 15), is_current=True,
        )
        self.fy.generate_nepal_periods(2083)

        admin_role = Role.objects.create(code="AR_FM", name="Finance Mgr", permissions=ROLE_PRESETS["FINANCE_MANAGER"]["permissions"])
        maker_role = Role.objects.create(code="AR_ACCT", name="Accountant", permissions=ROLE_PRESETS["ACCOUNTANT"]["permissions"])
        col_role = Role.objects.create(code="AR_COL", name="Collector", permissions=ROLE_PRESETS["COLLECTION_OFFICER"]["permissions"])

        CompanyMembership.objects.create(user=self.checker, company=self.company, role=admin_role, is_default=True)
        CompanyMembership.objects.create(user=self.maker, company=self.company, role=maker_role, is_default=True)
        CompanyMembership.objects.create(user=self.collector, company=self.company, role=col_role, is_default=True)

        def mk_acc(code, name, atype, acls, role_ctrl, req_sub=False, open_dr="0.00"):
            return Account.objects.create(
                company=self.company, code=code, name=name, account_type=atype,
                account_class=acls, control_role=role_ctrl, requires_subledger=req_sub,
                is_control_account=req_sub, opening_debit=Decimal(open_dr),
            )

        self.acc_cash = mk_acc("1010", "Main Cash", "ASSET", "ASSET", Account.ControlRole.CASH)
        self.acc_bank = mk_acc("1020", "Nabil Current", "ASSET", "ASSET", Account.ControlRole.BANK, open_dr="2000000.00")
        self.acc_cih = mk_acc("1035", "Cheques-in-Hand", "ASSET", "ASSET", Account.ControlRole.NONE)
        self.acc_ar = mk_acc("1101", "Sundry Debtors Control", "ASSET", "ASSET", Account.ControlRole.SUNDRY_DEBTORS, True)
        self.acc_tds_rec = mk_acc("1155", "TDS Receivable", "ASSET", "ASSET", Account.ControlRole.TDS_RECEIVABLE)
        self.acc_ret_rec = mk_acc("1160", "Retention Receivable", "ASSET", "ASSET", Account.ControlRole.RETENTION_RECEIVABLE, True)
        self.acc_vat_out = mk_acc("2040", "Output VAT", "LIABILITY", "LIABILITY", Account.ControlRole.OUTPUT_VAT)
        self.acc_cust_adv = mk_acc("2070", "Customer Advance Liability", "LIABILITY", "LIABILITY", Account.ControlRole.CUSTOMER_ADVANCE, True)
        self.acc_rev = mk_acc("4010", "Contract Revenue", "INCOME", "INCOME", Account.ControlRole.NONE)
        self.acc_exp = mk_acc("5010", "Direct Site Deduction", "EXPENSE", "EXPENSE", Account.ControlRole.DIRECT_EXPENSES)

        bank = Bank.objects.create(company=self.company, name="Nabil Bank", short_code="NABIL")
        br = BankBranch.objects.create(bank=bank, branch_code="KTM", name="Main")
        self.bank_account = BankAccount.objects.create(
            company=self.company, bank_branch=br, account_name="Nabil Hub Current",
            account_number_masked="****7788", account_number_encrypted="enc", account_number_hash="hash7788",
            gl_account=self.acc_bank, opening_balance=Decimal("2000000.00"),
        )

        # Customer profile
        self.cust_prof = CustomerGovernanceService.register_or_update_customer(
            company=self.company,
            user=self.checker,
            data={
                "code": "CLI-DOR",
                "name": "Department of Roads Nepal",
                "customer_category": "GOVERNMENT",
                "tax_classification": "VAT_REGISTERED",
                "pan_vat_no": "301998877",
                "credit_limit": "10000000.00",
                "credit_days": 30,
                "govt_contract_exempt_credit": True,
            },
        )
        self.customer = self.cust_prof.party

        # Projects & Contracts under same customer
        self.prj1 = Project.objects.create(company=self.company, code="PRJ-ROAD-01", name="Mugling Highway Pkg 1", client_party=self.customer)
        self.prj2 = Project.objects.create(company=self.company, code="PRJ-BRG-02", name="Trishuli Bridge Pkg 2", client_party=self.customer)

        self.con1 = ProjectContract.objects.create(
            company=self.company, project=self.prj1, contract_no="DOR-HWY-01",
            original_contract_value=Decimal("5000000.00"),
            approved_contract_value=Decimal("5000000.00"), retention_rate=Decimal("5.00"),
            advance_recovery_rate=Decimal("10.00"),
        )
        self.con2 = ProjectContract.objects.create(
            company=self.company, project=self.prj2, contract_no="DOR-BRG-02",
            original_contract_value=Decimal("3000000.00"),
            approved_contract_value=Decimal("3000000.00"), retention_rate=Decimal("5.00"),
        )

        self.boq_hdr = ProjectBoqHeader.objects.create(company=self.company, project=self.prj1, boq_no="BOQ-01", title="Road BOQ")
        self.boq_line = ProjectBoqLine.objects.create(
            boq_header=self.boq_hdr, project=self.prj1, item_code="EW-101",
            description="Earthwork Excavation", unit="Cum",
            contract_qty=Decimal("100.000"), contract_rate=Decimal("1000.00"),
        )

    def _certify_and_post_ra(self, curr_qty="40.000", bill_date=date(2026, 11, 10), adv_rec="0.00", ret_pct="5.00", cert_no="CERT-01"):
        ra = RABillingService.create_or_update_ra_bill(
            company=self.company,
            user=self.maker,
            data={
                "party": self.customer,
                "contract": self.con1,
                "bill_date": bill_date,
                "retention_pct": ret_pct,
                "advance_recovery_amount": adv_rec,
            },
            lines_data=[{"boq_line": self.boq_line, "current_qty": curr_qty}],
        )
        RABillingService.transition_workflow(ra_bill=ra, action="verify_measurement", user=self.maker)
        RABillingService.transition_workflow(ra_bill=ra, action="approve_engineer", user=self.maker)
        RABillingService.transition_workflow(ra_bill=ra, action="review_pm", user=self.maker)
        RABillingService.transition_workflow(ra_bill=ra, action="review_accounts", user=self.checker)
        RABillingService.transition_workflow(ra_bill=ra, action="authorize", user=self.checker)
        RABillingService.transition_workflow(ra_bill=ra, action="submit_client", user=self.maker)
        RABillingService.transition_workflow(
            ra_bill=ra,
            action="certify",
            user=self.checker,
            payload={"certificate_no": cert_no, "certified_date": bill_date, "certified_gross_amount": ra.current_gross_amount},
        )
        return RABillingService.post_to_ar(ra_bill=ra, user=self.checker)

    def test_01_to_06_multi_project_boq_excess_and_non_gl_draft_isolation(self):
        # Test 1: Multiple projects & contracts under 1 customer
        client = APIClient()
        client.force_authenticate(user=self.checker)
        res = client.get(f"/api/ar/customers/{self.cust_prof.id}/summary/", HTTP_X_COMPANY_ID=str(self.company.id))
        self.assertEqual(res.status_code, 200)
        self.assertEqual(len(res.data["contracts"]), 2)

        # Test 2 & 3: Progressive RA bills & BOQ cumulative math
        ra1 = self._certify_and_post_ra(curr_qty="40.000", cert_no="CERT-001")
        self.assertEqual(ra1.lines.first().cumulative_qty, Decimal("40.000"))

        # Test 4: Excess beyond BOQ qty (40 + 70 = 110 > 100) fails without APPROVED VO
        with self.assertRaises(ValidationError):
            RABillingService.create_or_update_ra_bill(
                company=self.company, user=self.maker,
                data={"party": self.customer, "contract": self.con1, "bill_date": date(2026, 11, 20)},
                lines_data=[{"boq_line": self.boq_line, "current_qty": "70.000"}],
            )
        vo = ProjectVariationOrder.objects.create(
            company=self.company, project=self.prj1, variation_no="VO-01", title="Extra Cut",
            additional_value=Decimal("20000.00"), submitted_by=self.maker, status=ProjectVariationOrder.Status.APPROVED,
        )

        # Test 5 & 6: Draft & Submitted-Uncertified RA Bill do NOT inflate GL or Trade Debtors or Aging/DSO
        gl_count_before = LedgerEntry.objects.filter(company=self.company).count()
        ar_before = ARIntelligenceService.get_ar_dashboard(company=self.company, as_of_date=date(2026, 11, 25))["kpis"]["total_receivables"]

        ra2_draft = RABillingService.create_or_update_ra_bill(
            company=self.company, user=self.maker,
            data={"party": self.customer, "contract": self.con1, "bill_date": date(2026, 11, 22)},
            lines_data=[{"boq_line": self.boq_line, "current_qty": "70.000", "variation_order": vo}],
        )
        self.assertIsNone(ra2_draft.voucher_id)
        RABillingService.transition_workflow(ra_bill=ra2_draft, action="verify_measurement", user=self.maker)
        RABillingService.transition_workflow(ra_bill=ra2_draft, action="approve_engineer", user=self.maker)
        RABillingService.transition_workflow(ra_bill=ra2_draft, action="review_pm", user=self.maker)
        RABillingService.transition_workflow(ra_bill=ra2_draft, action="review_accounts", user=self.checker)
        RABillingService.transition_workflow(ra_bill=ra2_draft, action="authorize", user=self.checker)
        RABillingService.transition_workflow(ra_bill=ra2_draft, action="submit_client", user=self.maker)

        self.assertEqual(LedgerEntry.objects.filter(company=self.company).count(), gl_count_before)
        dash_after = ARIntelligenceService.get_ar_dashboard(company=self.company, as_of_date=date(2026, 11, 25))["kpis"]
        self.assertEqual(dash_after["total_receivables"], ar_before)
        self.assertEqual(Decimal(dash_after["ra_pending_certification"]), Decimal("70000.00"))

    def test_07_to_09_and_17_18_single_post_retention_advance_recovery(self):
        # Test 17: Customer advance receipt is liability (not sales revenue)
        adv_rcp = ARReceiptAllocationService.create_receipt(
            company=self.company, user=self.maker,
            data={"party": self.customer, "project": self.prj1, "receipt_mode": CustomerReceipt.ReceiptMode.ADVANCE, "receipt_date": date(2026, 11, 1), "amount": "50000.00"},
        )
        adv_rec = AdvanceRecord.objects.get(company=self.company, source_voucher=adv_rcp.voucher)
        self.assertEqual(adv_rec.remaining_amount, Decimal("50000.00"))
        # Revenue GL must still be 0
        rev_gl = LedgerEntry.objects.filter(company=self.company, account=self.acc_rev).count()
        self.assertEqual(rev_gl, 0)

        # Test 7, 8, 9: Certified RA posts once, retention separate, advance recovered cleanly
        ra = self._certify_and_post_ra(curr_qty="50.000", bill_date=date(2026, 11, 12), adv_rec="10000.00", ret_pct="5.00", cert_no="CERT-77")
        with self.assertRaises(ValidationError):
            RABillingService.post_to_ar(ra_bill=ra, user=self.checker)  # Double posting blocked

        adv_rec.refresh_from_db()
        self.assertEqual(adv_rec.remaining_amount, Decimal("40000.00"))

        ret_sched = RetentionSchedule.objects.get(source_voucher=ra.voucher, direction=RetentionSchedule.Direction.RECEIVABLE)
        self.assertEqual(ret_sched.retention_amount, Decimal("2500.00"))  # 5% of 50,000

        # Test 18: Retention release cannot exceed eligible remaining retention
        from apps.party_hub.services import RetentionService
        with self.assertRaises(ValidationError):
            RetentionService.release_retention(
                company=self.company, user=self.checker, retention=ret_sched,
                release_amount=Decimal("3000.00"), release_date=date(2026, 11, 20),
                settlement_mode="DIRECT_BANK", bank_account=self.acc_bank,
            )

    def test_10_to_16_and_25_26_allocations_concurrency_reversal(self):
        # Create two posted invoices (each 100k + 13k VAT = 113k)
        si1 = SalesInvoiceService.create_draft_invoice(
            company=self.company, user=self.maker,
            data={"party": self.customer, "invoice_date": date(2026, 11, 5), "due_date": date(2026, 11, 15)},
            lines_data=[{"description": "Supply A", "quantity": "1", "unit_rate": "100000.00", "tax_rate_pct": "13.00"}],
        )
        SalesInvoiceService.transition_and_post(invoice=si1, action="submit", user=self.maker)
        SalesInvoiceService.transition_and_post(invoice=si1, action="approve", user=self.checker)
        si1 = SalesInvoiceService.transition_and_post(invoice=si1, action="post", user=self.checker)

        si2 = SalesInvoiceService.create_draft_invoice(
            company=self.company, user=self.maker,
            data={"party": self.customer, "invoice_date": date(2026, 11, 6), "due_date": date(2026, 12, 1)},
            lines_data=[{"description": "Supply B", "quantity": "1", "unit_rate": "100000.00", "tax_rate_pct": "13.00"}],
        )
        SalesInvoiceService.transition_and_post(invoice=si2, action="submit", user=self.maker)
        SalesInvoiceService.transition_and_post(invoice=si2, action="approve", user=self.checker)
        si2 = SalesInvoiceService.transition_and_post(invoice=si2, action="post", user=self.checker)

        # Test 10, 12, 13: Receipt 150k -> allocate 100k to si1 & 20k to si2 -> leaves 30k unallocated & 13k/93k open!
        rcp1 = ARReceiptAllocationService.create_receipt(
            company=self.company, user=self.maker,
            data={"party": self.customer, "receipt_no": "RCP-MULTI-1", "receipt_date": date(2026, 11, 18), "amount": "150000.00"},
        )
        # Test 25: Same receipt cannot be posted twice
        with self.assertRaises(ValidationError):
            ARReceiptAllocationService.create_receipt(
                company=self.company, user=self.maker,
                data={"party": self.customer, "receipt_no": "RCP-MULTI-1", "receipt_date": date(2026, 11, 18), "amount": "150000.00"},
            )

        ARReceiptAllocationService.allocate_receipt(
            company=self.company, user=self.maker, receipt=rcp1,
            allocations=[
                {"open_item_id": str(si1.open_item.id), "allocated_amount": "100000.00"},
                {"open_item_id": str(si2.open_item.id), "allocated_amount": "20000.00"},
            ],
        )
        si1.open_item.refresh_from_db()
        si2.open_item.refresh_from_db()
        rcp1.open_item.refresh_from_db()
        self.assertEqual(si1.open_item.remaining_amount, Decimal("13000.00"))
        self.assertEqual(si2.open_item.remaining_amount, Decimal("93000.00"))
        self.assertEqual(rcp1.open_item.remaining_amount, Decimal("30000.00"))

        # Test 14, 15, 26: Over-allocating receipt or invoice blocked
        rcp2 = ARReceiptAllocationService.create_receipt(
            company=self.company, user=self.maker,
            data={"party": self.customer, "receipt_no": "RCP-MULTI-2", "receipt_date": date(2026, 11, 19), "amount": "50000.00"},
        )
        with self.assertRaises(ValidationError):  # Exceeds invoice 1 remaining 13k
            ARReceiptAllocationService.allocate_receipt(
                company=self.company, user=self.maker, receipt=rcp2,
                allocations=[{"open_item_id": str(si1.open_item.id), "allocated_amount": "20000.00"}],
            )
        with self.assertRaises(ValidationError):  # Exceeds receipt 2 balance 50k
            ARReceiptAllocationService.allocate_receipt(
                company=self.company, user=self.maker, receipt=rcp2,
                allocations=[{"open_item_id": str(si2.open_item.id), "allocated_amount": "60000.00"}],
            )

        # Test 11: Second receipt settles si1 remaining 13k!
        ARReceiptAllocationService.allocate_receipt(
            company=self.company, user=self.maker, receipt=rcp2,
            allocations=[{"open_item_id": str(si1.open_item.id), "allocated_amount": "13000.00"}],
        )
        si1.open_item.refresh_from_db()
        self.assertEqual(si1.open_item.status, OpenItem.Status.SETTLED)

        # Test 16 & 28: Reversal of rcp2->si1 restores open balance & keeps immutable reversal + audit log!
        ba = BillAllocation.objects.get(settlement_voucher=rcp2.voucher, against_voucher=si1.voucher)
        ARReceiptAllocationService.reverse_allocation(company=self.company, user=self.checker, allocation_id=ba.id, reason="Client bank bounce check")
        si1.open_item.refresh_from_db()
        rcp2.open_item.refresh_from_db()
        self.assertEqual(si1.open_item.remaining_amount, Decimal("13000.00"))
        self.assertEqual(rcp2.open_item.remaining_amount, Decimal("50000.00"))
        self.assertEqual(ReceiptAllocationReversal.objects.filter(company=self.company).count(), 1)
        self.assertTrue(ARAuditEvent.objects.filter(company=self.company, action="ALLOCATION_REVERSED").exists())

    def test_19_to_24_and_27_29_30_disputes_aging_dso_statements_recon_rbac_reports(self):
        # Post 1 RA bill + 1 customer advance + 1 receipt
        ARReceiptAllocationService.create_receipt(
            company=self.company, user=self.maker,
            data={"party": self.customer, "project": self.prj1, "receipt_mode": CustomerReceipt.ReceiptMode.ADVANCE, "receipt_date": date(2026, 11, 1), "amount": "40000.00"},
        )
        ra = self._certify_and_post_ra(curr_qty="60.000", bill_date=date(2026, 11, 5), adv_rec="5000.00", ret_pct="5.00", cert_no="CERT-99")
        si = SalesInvoiceService.create_draft_invoice(
            company=self.company, user=self.maker,
            data={"party": self.customer, "invoice_date": date(2026, 10, 1), "due_date": date(2026, 10, 15)},
            lines_data=[{"description": "Disputed Milestone", "quantity": "1", "unit_rate": "20000.00", "tax_rate_pct": "13.00"}],
        )
        SalesInvoiceService.transition_and_post(invoice=si, action="submit", user=self.maker)
        SalesInvoiceService.transition_and_post(invoice=si, action="approve", user=self.checker)
        si = SalesInvoiceService.transition_and_post(invoice=si, action="post", user=self.checker)

        # Test 19: Disputed item stays traceable and separated on dashboard
        PartyDispute.objects.create(
            company=self.company, hub_side=PartyDispute.HubSide.RECEIVABLE, party=self.customer,
            open_item=si.open_item, dispute_no="DSP-T1", disputed_amount=si.open_item.original_amount,
            description="Rate dispute", raised_by=self.collector,
        )
        si.open_item.status = OpenItem.Status.DISPUTED
        si.open_item.save(update_fields=["status"])

        dash = ARIntelligenceService.get_ar_dashboard(company=self.company, as_of_date=date(2026, 11, 30))
        self.assertEqual(Decimal(dash["kpis"]["disputed_receivables"]), si.open_item.original_amount)

        # Test 20 & 21: Aging + DSO methodology comparison
        dso_avg = ARIntelligenceService.compute_dso_suite(company=self.company, as_of_date=date(2026, 11, 30), method="AVG_RECEIVABLES")
        dso_cls = ARIntelligenceService.compute_dso_suite(company=self.company, as_of_date=date(2026, 11, 30), method="CLOSING_AR")
        self.assertEqual(dso_avg["methodology"], "AVG_RECEIVABLES")
        self.assertEqual(dso_cls["methodology"], "CLOSING_AR")
        self.assertIn("Draft & Uncertified RA Bills", dso_avg["current_period"]["exclusions"])

        # Test 22, 23, 24: Customer statement agrees with subledger & full GL Control Reconciliation passes 100%
        stmt = ARStatementReconciliationService.generate_customer_statement(
            company=self.company, user=self.checker, party=self.customer,
            from_date=date(2026, 10, 1), to_date=date(2026, 11, 30),
        )
        ctrl = ARIntelligenceService.compute_control_reconciliation(company=self.company, as_of_date=date(2026, 11, 30))
        self.assertTrue(ctrl["is_fully_reconciled"], f"Variance detected: {ctrl}")
        debtor_row = next(r for r in ctrl["controls"] if r["control_role"] == "SUNDRY_DEBTORS")
        self.assertEqual(Decimal(stmt["closing_balance"]), Decimal(debtor_row["subledger_balance"]))

        # Statement import reconciliation identifies unmatched external items without auto-posting GL
        gl_before = LedgerEntry.objects.filter(company=self.company).count()
        recon = ARStatementReconciliationService.import_and_match(
            company=self.company, user=self.checker, party=self.customer,
            statement_to=date(2026, 11, 30), csv_text="date,reference,description,debit,credit\n2026-11-10,UNKNOWN-99,Missing bill,5000,0",
        )
        self.assertEqual(recon.status, "EXCEPTIONS_PENDING")
        self.assertEqual(LedgerEntry.objects.filter(company=self.company).count(), gl_before)

        # Test 27 & 29: Unauthorized collector blocked (HTTP 403) + offline draft cannot bypass approval/post gate
        client = APIClient()
        client.force_authenticate(user=self.collector)
        r_forb_post = client.post(f"/api/ar/ra-bills/{ra.id}/post/", {}, format="json", HTTP_X_COMPANY_ID=str(self.company.id))
        self.assertEqual(r_forb_post.status_code, 403)
        r_forb_ov = client.post(f"/api/ar/customers/{self.cust_prof.id}/credit-override/", {"override_limit": "99999999", "reason": "hack"}, format="json", HTTP_X_COMPANY_ID=str(self.company.id))
        self.assertEqual(r_forb_ov.status_code, 403)

        # Offline draft invoice created via API stays DRAFT and cannot be posted directly via draft endpoint
        client.force_authenticate(user=self.maker)
        draft_res = client.post(
            "/api/ar/invoices/",
            {
                "party_id": str(self.customer.id),
                "invoice_date": "2026-11-28",
                "lines": [{"description": "Offline Queued Invoice", "quantity": "1", "unit_rate": "10000.00", "tax_rate_pct": "13.00"}],
            },
            format="json",
            HTTP_X_COMPANY_ID=str(self.company.id),
        )
        self.assertEqual(draft_res.status_code, 201)
        self.assertEqual(draft_res.data["status"], "DRAFT")
        # Direct post without approval fails!
        bad_post = client.post(f"/api/ar/invoices/{draft_res.data['id']}/post/", {}, format="json", HTTP_X_COMPANY_ID=str(self.company.id))
        self.assertIn(bad_post.status_code, (400, 403))

        # Test 30: PDF & XLSX exports match underlying report row count
        rep = ARReportService.build_report_data(company=self.company, report_code="ra_billing_register")
        xlsx_bytes = ARReportService.export_xlsx(rep)
        wb = openpyxl.load_workbook(io.BytesIO(xlsx_bytes), data_only=False)
        ws = wb.active
        # Header (3 rows + blank row -> data rows start row 4) => max_row - 3 == row_count
        self.assertEqual(ws.max_row - 3, rep["row_count"])
        pdf_bytes = ARReportService.export_pdf(rep)
        self.assertTrue(pdf_bytes.startswith(b"%PDF"))

