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

from apps.accounting.models import Account, AdvanceRecord, LedgerEntry, Party, Voucher
from apps.accounting.services import PostingRuleEngine, PostingService, VoucherService
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.document_engine.services.document_registry import ensure_default_document_types
from apps.document_engine.services.excel_service import generate_excel_or_csv
from apps.document_engine.services.pdf_service import generate_pdf_document
from apps.party_hub.models import CustomerProfile, OpenItem, PartyDispute, PaymentProposal, RetentionSchedule
from apps.party_hub.services import (
    AgingAnalysisService,
    InvoiceAllocationService,
    PartyReconciliationService,
    PayableService,
    ReceivableService,
    RetentionService,
    StatementGenerationService,
)
from apps.projects.models import Project
from apps.tenancy.models import Company, FiscalPeriod, FiscalYear


class EnterpriseDebtorsCreditorsHubTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(username="hub_ctrl", email="hub_ctrl@maya.local", password="Password@123")
        self.company = Company.objects.create(code="HB01", name="Himalayan Infra Hub Pvt Ltd", pan_vat_no="600112299")
        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)
        role = Role.objects.create(
            code="HB_ADMIN", name="Admin", permissions=ROLE_PRESETS["SUPER_ADMIN"]["permissions"],
        )
        CompanyMembership.objects.create(user=self.user, company=self.company, role=role, is_default=True)

        self.collector = User.objects.create_user(username="collector_u", email="collector_u@maya.local", password="Password@123")
        col_role = Role.objects.create(
            code="HB_COLLECTOR", name="Collection Officer", permissions=ROLE_PRESETS["COLLECTION_OFFICER"]["permissions"],
        )
        CompanyMembership.objects.create(user=self.collector, company=self.company, role=col_role, is_default=True)

        self.project = Project.objects.create(company=self.company, code="PRJ-HUB", name="Highway Corridor Contract")

        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_bank = mk_acc("1020", "Nabil Project Bank", "ASSET", "ASSET", Account.ControlRole.BANK, open_dr="5000000.00")
        self.acc_ar = mk_acc("1100", "Sundry Debtors Control", "ASSET", "ASSET", Account.ControlRole.SUNDRY_DEBTORS, True)
        self.acc_ret_rec = mk_acc("1160", "Retention Receivable", "ASSET", "ASSET", Account.ControlRole.RETENTION_RECEIVABLE, True)
        self.acc_sup_adv = mk_acc("1150", "Supplier Advance", "ASSET", "ASSET", Account.ControlRole.SUPPLIER_ADVANCE, True)
        self.acc_vat_in = mk_acc("1250", "Input VAT", "ASSET", "ASSET", Account.ControlRole.INPUT_VAT)
        self.acc_ap = mk_acc("2010", "Sundry Creditors Control", "LIABILITY", "LIABILITY", Account.ControlRole.SUNDRY_CREDITORS, True)
        self.acc_sub = mk_acc("2020", "Subcontractor Control", "LIABILITY", "LIABILITY", Account.ControlRole.SUBCONTRACTOR_PAYABLE, True)
        self.acc_vat_out = mk_acc("2040", "Output VAT", "LIABILITY", "LIABILITY", Account.ControlRole.OUTPUT_VAT)
        self.acc_tds = mk_acc("2050", "TDS Payable", "LIABILITY", "LIABILITY", Account.ControlRole.TDS_PAYABLE)
        self.acc_ret_pay = mk_acc("2060", "Retention Payable", "LIABILITY", "LIABILITY", Account.ControlRole.RETENTION_PAYABLE, True)
        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", "Subcontract & Material Cost", "EXPENSE", "EXPENSE", Account.ControlRole.DIRECT_EXPENSES)
        self.acc_bad = mk_acc("6090", "Bad Debt Write-Off", "EXPENSE", "LOSS", Account.ControlRole.BAD_DEBT_ALLOWANCE)

        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="****8899", account_number_encrypted="enc", account_number_hash="hash8899",
            gl_account=self.acc_bank, opening_balance=Decimal("5000000.00"),
        )

        self.cust_prof = ReceivableService.register_customer(
            company=self.company, user=self.user,
            party_data={"code": "CLI-ABC", "name": "ABC Infrastructure Client", "pan_vat_no": "301112233", "project": self.project},
            profile_data={"customer_category": "GOVERNMENT", "pan_vat_no": "301112233", "contract_number": "CON-01"},
        )
        self.customer = self.cust_prof.party
        self.subcontractor = Party.objects.create(
            company=self.company, party_type=Party.PartyType.SUBCONTRACTOR, code="SUB-01",
            name="Gurkha Civil Works", pan_vat_no="605544332", control_account=self.acc_sub, project=self.project,
        )

    def test_control_account_guard_ra_billing_retention_and_gl_reconciliation(self):
        # 1. Direct manual journal to Sundry Debtors without party reference is blocked
        v_bad = VoucherService.create_draft(
            company=self.company, user=self.user,
            data={"voucher_type": Voucher.VoucherType.JOURNAL, "voucher_date": date(2026, 11, 5), "narration": "Invalid direct control"},
            lines_data=[
                {"account": self.acc_ar, "debit": Decimal("1000.00"), "credit": Decimal("0.00")},
                {"account": self.acc_rev, "debit": Decimal("0.00"), "credit": Decimal("1000.00")},
            ],
        )
        v_bad.status = Voucher.Status.APPROVED
        v_bad.save()
        with self.assertRaises(ValidationError):
            PostingService.post_voucher(voucher=v_bad, user=self.user)

        # 2. Client RA Bill: Certified 1,000,000 + 13% VAT (130,000) - 5% Retention (50,000) - Adv Rec (100,000) - Ded (20,000) = 960,000 Net Debtors
        v_adv = ReceivableService.record_customer_receipt_or_advance(
            company=self.company, user=self.user, party=self.customer,
            receipt_date=date(2026, 11, 2), amount=Decimal("200000.00"),
            bank_or_cash_account=self.acc_bank, is_advance=True, project=self.project,
        )
        self.assertEqual(AdvanceRecord.objects.filter(source_voucher=v_adv).count(), 1)

        v_ra = ReceivableService.create_and_post_invoice_or_bill(
            company=self.company, user=self.user, party=self.customer,
            voucher_type=Voucher.VoucherType.CLIENT_RA_BILL, invoice_date=date(2026, 11, 10), due_date=date(2026, 11, 25),
            gross_amount=Decimal("1000000.00"), vat_rate=Decimal("13.00"), retention_pct=Decimal("5.00"),
            advance_recovery_amount=Decimal("100000.00"), other_deductions=Decimal("20000.00"), project=self.project,
        )
        oi_ra = OpenItem.objects.get(voucher=v_ra, is_unallocated_credit=False)
        self.assertEqual(oi_ra.original_amount, Decimal("960000.00"))
        ret_rec = RetentionSchedule.objects.get(source_voucher=v_ra, direction=RetentionSchedule.Direction.RECEIVABLE)
        self.assertEqual(ret_rec.retention_amount, Decimal("50000.00"))

        # 3. Subcontractor RA Bill: 500,000 - 5% Retention (25,000) - 1.5% TDS (7,500) -> Net Subcontractor Payable 467,500 (+ VAT 13% = 532,500)
        PayableService.create_and_post_bill_or_note(
            company=self.company, user=self.user, party=self.subcontractor,
            voucher_type=Voucher.VoucherType.SUBCONTRACTOR_BILL, bill_date=date(2026, 11, 12), due_date=date(2026, 11, 28),
            gross_amount=Decimal("500000.00"), vat_rate=Decimal("13.00"), tds_rate=Decimal("1.50"),
            retention_pct=Decimal("5.00"), project=self.project, supplier_invoice_no="SUB-RA-01",
        )

        # 4. Run full GL <-> Subledger Control Reconciliation
        run = PartyReconciliationService.run_reconciliation(company=self.company, user=self.user, as_of_date=date(2026, 11, 29))
        self.assertTrue(run.is_reconciled)
        self.assertEqual(run.exception_count, 0)

    def test_explicit_1_to_many_allocation_never_auto_clears_and_blocks_overpay(self):
        v1 = ReceivableService.create_and_post_invoice_or_bill(
            company=self.company, user=self.user, party=self.customer,
            voucher_type=Voucher.VoucherType.SALES, invoice_date=date(2026, 11, 1), due_date=date(2026, 11, 10),
            gross_amount=Decimal("100000.00"), vat_rate=Decimal("0.00"), project=self.project, reference_no="INV-001",
        )
        v2 = ReceivableService.create_and_post_invoice_or_bill(
            company=self.company, user=self.user, party=self.customer,
            voucher_type=Voucher.VoucherType.SALES, invoice_date=date(2026, 11, 3), due_date=date(2026, 11, 15),
            gross_amount=Decimal("75000.00"), vat_rate=Decimal("0.00"), project=self.project, reference_no="INV-002",
        )
        v3 = ReceivableService.create_and_post_invoice_or_bill(
            company=self.company, user=self.user, party=self.customer,
            voucher_type=Voucher.VoucherType.SALES, invoice_date=date(2026, 11, 5), due_date=date(2026, 11, 20),
            gross_amount=Decimal("50000.00"), vat_rate=Decimal("0.00"), project=self.project, reference_no="INV-003",
        )
        rec = ReceivableService.record_customer_receipt_or_advance(
            company=self.company, user=self.user, party=self.customer,
            receipt_date=date(2026, 11, 18), amount=Decimal("125000.00"), bank_or_cash_account=self.acc_bank, project=self.project,
        )

        # Must NOT auto-clear any invoice upon receipt posting
        oi1 = OpenItem.objects.get(voucher=v1, is_unallocated_credit=False)
        oi2 = OpenItem.objects.get(voucher=v2, is_unallocated_credit=False)
        oi3 = OpenItem.objects.get(voucher=v3, is_unallocated_credit=False)
        unalloc = OpenItem.objects.get(voucher=rec, is_unallocated_credit=True)
        self.assertEqual(oi1.remaining_amount, Decimal("100000.00"))
        self.assertEqual(unalloc.remaining_amount, Decimal("125000.00"))

        # Explicit 1-to-Many settlement: 100k -> INV-001, 25k -> INV-002
        res = InvoiceAllocationService.allocate_batch(
            company=self.company, user=self.user, party=self.customer, settlement_voucher=rec,
            allocations=[
                {"open_item_id": str(oi1.id), "allocated_amount": "100000.00"},
                {"open_item_id": str(oi2.id), "allocated_amount": "25000.00"},
            ],
            hub_side=OpenItem.HubSide.RECEIVABLE,
        )
        oi1.refresh_from_db()
        oi2.refresh_from_db()
        oi3.refresh_from_db()
        self.assertEqual(oi1.status, OpenItem.Status.SETTLED)
        self.assertEqual(oi2.remaining_amount, Decimal("50000.00"))
        self.assertEqual(oi3.remaining_amount, Decimal("50000.00"))
        self.assertEqual(Decimal(res["unallocated_remaining"]), Decimal("0.00"))

        # Second receipt: over-allocation against INV-002 blocked; disputed INV-003 blocked
        rec2 = ReceivableService.record_customer_receipt_or_advance(
            company=self.company, user=self.user, party=self.customer,
            receipt_date=date(2026, 11, 22), amount=Decimal("60000.00"), bank_or_cash_account=self.acc_bank,
        )
        with self.assertRaises(ValidationError):
            InvoiceAllocationService.allocate_batch(
                company=self.company, user=self.user, party=self.customer, settlement_voucher=rec2,
                allocations=[{"open_item_id": str(oi2.id), "allocated_amount": "55000.00"}],
                hub_side=OpenItem.HubSide.RECEIVABLE,
            )

        oi3.status = OpenItem.Status.DISPUTED
        oi3.save(update_fields=["status"])
        with self.assertRaises(ValidationError):
            InvoiceAllocationService.allocate_batch(
                company=self.company, user=self.user, party=self.customer, settlement_voucher=rec2,
                allocations=[{"open_item_id": str(oi3.id), "allocated_amount": "10000.00"}],
                hub_side=OpenItem.HubSide.RECEIVABLE,
            )

    def test_advance_adjustment_retention_release_writeoff_and_aging_kpi_analytics(self):
        v_adv = ReceivableService.record_customer_receipt_or_advance(
            company=self.company, user=self.user, party=self.customer,
            receipt_date=date(2026, 11, 2), amount=Decimal("100000.00"), bank_or_cash_account=self.acc_bank, is_advance=True,
        )
        adv = AdvanceRecord.objects.get(source_voucher=v_adv)

        v_bill = ReceivableService.create_and_post_invoice_or_bill(
            company=self.company, user=self.user, party=self.customer,
            voucher_type=Voucher.VoucherType.CLIENT_RA_BILL, invoice_date=date(2026, 11, 10), due_date=date(2026, 11, 15),
            gross_amount=Decimal("200000.00"), vat_rate=Decimal("0.00"), retention_pct=Decimal("10.00"), project=self.project,
        )
        oi = OpenItem.objects.get(voucher=v_bill, is_unallocated_credit=False)  # 180,000 net AR + 20,000 retention

        # Aging separates ordinary open AR (180k) from Retention (20k) & Customer Advance (100k)
        ag = AgingAnalysisService.compute_aging(company=self.company, hub_side=OpenItem.HubSide.RECEIVABLE, as_of_date=date(2026, 11, 29))
        self.assertEqual(Decimal(ag["totals"]["total"]), Decimal("180000.00"))
        self.assertEqual(Decimal(ag["retention_total"]), Decimal("20000.00"))
        self.assertEqual(Decimal(ag["advance_total"]), Decimal("100000.00"))

        # Explicit Customer Advance adjustment reduces invoice & advance balance
        InvoiceAllocationService.adjust_party_advance(
            company=self.company, user=self.user, advance=adv, open_item=oi,
            amount=Decimal("100000.00"), adjustment_date=date(2026, 11, 20),
        )
        oi.refresh_from_db()
        adv.refresh_from_db()
        self.assertEqual(oi.remaining_amount, Decimal("80000.00"))
        self.assertEqual(adv.remaining_amount, Decimal("0.00"))

        # Retention release transfers held retention cleanly
        ret = RetentionSchedule.objects.get(source_voucher=v_bill)
        RetentionService.release_retention(
            company=self.company, user=self.user, retention=ret,
            release_amount=Decimal("10000.00"), release_date=date(2026, 11, 25),
        )
        ret.refresh_from_db()
        self.assertEqual(ret.remaining_retention, Decimal("10000.00"))

        # Write off remaining 80k bad debt
        wo = InvoiceAllocationService.write_off_bad_debt(
            company=self.company, user=self.user, open_item=oi,
            writeoff_date=date(2026, 11, 29), amount=Decimal("80000.00"), reason="Approved contract short-closure",
        )
        self.assertEqual(wo["status"], OpenItem.Status.WRITTEN_OFF)

        # GL Reconciliation must remain 100% balanced across all control roles
        run = PartyReconciliationService.run_reconciliation(company=self.company, user=self.user)
        self.assertTrue(run.is_reconciled)

    def test_payment_proposal_rbac_and_document_engine_statements(self):
        ensure_default_document_types()
        v_ap = PayableService.create_and_post_bill_or_note(
            company=self.company, user=self.user, party=self.subcontractor,
            voucher_type=Voucher.VoucherType.SUBCONTRACTOR_BILL, bill_date=date(2026, 11, 8), due_date=date(2026, 11, 18),
            gross_amount=Decimal("100000.00"), vat_rate=Decimal("0.00"), tds_rate=Decimal("1.50"), retention_pct=Decimal("0.00"),
            supplier_invoice_no="BILL-991", project=self.project,
        )
        oi_ap = OpenItem.objects.get(voucher=v_ap, is_unallocated_credit=False)

        prop = PayableService.create_payment_proposal(
            company=self.company, user=self.user, proposal_date=date(2026, 11, 28),
            bank_account=self.bank_account, items=[{"open_item_id": str(oi_ap.id), "proposed_amount": str(oi_ap.remaining_amount)}],
        )
        # Cannot execute DRAFT proposal
        with self.assertRaises(ValidationError):
            PayableService.execute_payment_proposal(company=self.company, user=self.user, proposal=prop)

        prop.status = PaymentProposal.Status.APPROVED
        prop.approved_by = self.user
        prop.save(update_fields=["status", "approved_by"])
        exec_res = PayableService.execute_payment_proposal(company=self.company, user=self.user, proposal=prop)
        oi_ap.refresh_from_db()
        self.assertEqual(oi_ap.status, OpenItem.Status.SETTLED)
        self.assertIn("voucher_no", exec_res)

        # Statement PDF & Excel via centralized Document Engine
        stmt = StatementGenerationService.create_statement_record(
            company=self.company, user=self.user, party=self.subcontractor,
            statement_type="SUPPLIER_STATEMENT", from_date=date(2026, 11, 1), to_date=date(2026, 11, 29),
        )
        pdf_bytes, _, _ = generate_pdf_document(
            company=self.company, doc_type_code="SUPPLIER_STATEMENT", source_id=str(stmt.id), user=self.user, archive=False,
        )
        self.assertTrue(pdf_bytes.startswith(b"%PDF"))

        xlsx_bytes, _, _, _ = generate_excel_or_csv(
            company=self.company, doc_type_code="DEBTORS_AGING", source_id="all", output_format="XLSX", user=self.user, archive=False,
        )
        self.assertGreater(len(xlsx_bytes), 500)

        # RBAC: Collection Officer can view debtors dashboard & log follow-ups, but is denied bad-debt write-off (403)
        cli = APIClient()
        cli.force_authenticate(user=self.collector)
        hdr = {"HTTP_X_COMPANY_ID": str(self.company.id)}
        self.assertEqual(cli.get("/api/v1/debtors/dashboard/", **hdr).status_code, 200)
        self.assertEqual(
            cli.post("/api/v1/debtors/write-offs/", {"open_item_id": str(oi_ap.id), "amount": "10.00"}, format="json", **hdr).status_code,
            403,
        )
