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.accounts_rbac.constants import ROLE_PRESETS
from apps.accounts_rbac.models import CompanyMembership, Role, User
from apps.accounting.models import (
    Account,
    CostCategory,
    CostCenter,
    LedgerEntry,
    Party,
    ScenarioDefinition,
    Voucher,
    VoucherClass,
    VoucherLineCostAllocation,
    VoucherRevision,
    VoucherTypeConfig,
)
from apps.accounting.services import (
    ApprovalService,
    ExtendedReportService,
    PostingService,
    TallyConfigService,
    VoucherService,
)
from apps.inventory.models import ItemCategory, ItemMaster, UnitOfMeasure, Warehouse
from apps.localization.bs_calendar import bs_to_ad
from apps.party_hub.models import OpenItem
from apps.projects.models import Project
from apps.tenancy.models import Company, FiscalYear


class TallyPrimeVoucherEngineTests(TestCase):
    def setUp(self):
        self.roles = {
            code: Role.objects.create(code=code, name=spec["name"], permissions=spec["permissions"])
            for code, spec in ROLE_PRESETS.items()
        }
        self.finance = User.objects.create_user(
            username="tally_fin", email="tally_fin@test.local", password="Password@123"
        )
        self.approver = User.objects.create_user(
            username="tally_app", email="tally_app@test.local", password="Password@123"
        )
        self.supervisor = User.objects.create_user(
            username="tally_sup", email="tally_sup@test.local", password="Password@123"
        )
        self.company = Company.objects.create(
            code="TALLYCO",
            name="Tally Infrastructure Co.",
            pan_vat_no="609998881",
            base_currency="NPR",
            calendar_preference=Company.CalendarPref.BS,
        )
        CompanyMembership.objects.create(
            user=self.finance, company=self.company, role=self.roles["FINANCE_MANAGER"], is_default=True
        )
        CompanyMembership.objects.create(
            user=self.approver, company=self.company, role=self.roles["COMPANY_ADMIN"], is_default=True
        )
        CompanyMembership.objects.create(
            user=self.supervisor, company=self.company, role=self.roles["SITE_SUPERVISOR"], is_default=True
        )
        self.fy = FiscalYear.objects.create(
            company=self.company,
            name="2083/84",
            start_date=bs_to_ad(2083, 4, 1),
            end_date=bs_to_ad(2084, 3, 31),
            is_current=True,
        )
        self.fy.generate_nepal_periods(2083)

        self.acc_bank = Account.objects.create(
            company=self.company, code="10201", name="Nabil Bank Current", account_type=Account.AccountType.ASSET, control_role=Account.ControlRole.BANK, allow_direct_posting=True
        )
        self.acc_cash = Account.objects.create(
            company=self.company, code="10101", name="Site Cash", account_type=Account.AccountType.ASSET, control_role=Account.ControlRole.CASH, allow_direct_posting=True
        )
        self.acc_exp = Account.objects.create(
            company=self.company, code="51010", name="Concrete & Rebar Cost", account_type=Account.AccountType.EXPENSE, allow_direct_posting=True
        )
        self.acc_vat = Account.objects.create(
            company=self.company, code="11501", name="Input VAT 13%", account_type=Account.AccountType.ASSET, control_role=Account.ControlRole.INPUT_VAT, allow_direct_posting=True
        )
        self.acc_ap = Account.objects.create(
            company=self.company, code="20101", name="Sundry Creditors", account_type=Account.AccountType.LIABILITY, control_role=Account.ControlRole.SUNDRY_CREDITORS, requires_subledger=True, is_control_account=True, allow_direct_posting=True
        )
        self.acc_inv = Account.objects.create(
            company=self.company, code="12001", name="Site Store Inventory", account_type=Account.AccountType.ASSET, control_role=Account.ControlRole.INVENTORY, allow_direct_posting=True
        )
        self.supplier = Party.objects.create(
            company=self.company, party_type=Party.PartyType.SUPPLIER, code="SUP-HIMAL", name="Himal Cement Pvt Ltd", control_account=self.acc_ap, pan_vat_no="601122334"
        )
        self.project = Project.objects.create(
            company=self.company, code="PRJ-TALLY", name="Kathmandu Ring Road Overpass", budget_amount=Decimal("5000000.00")
        )
        self.cost_cat = CostCategory.objects.create(company=self.company, code="SITE", name="Site Blocks")
        self.cc_a = CostCenter.objects.create(
            company=self.company, cost_category=self.cost_cat, project=self.project, code="CC-A", name="Pillar A"
        )
        self.cc_b = CostCenter.objects.create(
            company=self.company, cost_category=self.cost_cat, project=self.project, code="CC-B", name="Pillar B"
        )
        cat = ItemCategory.objects.create(company=self.company, code="MAT", name="Cement & Steel")
        uom = UnitOfMeasure.objects.create(company=self.company, code="BAG", name="50kg Bag")
        self.item = ItemMaster.objects.create(
            company=self.company, item_code="CEM-OPC", name="OPC Cement", category=cat, primary_unit=uom, standard_rate=Decimal("800.00"), inventory_account=self.acc_inv
        )
        self.warehouse = Warehouse.objects.create(
            company=self.company, code="WH-MAIN", name="Main Yard", store_kind=Warehouse.StoreKind.CENTRAL
        )
        self.v_date = bs_to_ad(2083, 4, 15)

        self.client = APIClient()
        self.client.force_authenticate(user=self.finance)

    def test_default_catalog_subtypes_multi_series_and_monthly_reset(self):
        summary = TallyConfigService.ensure_default_voucher_catalog(self.company)
        self.assertGreaterEqual(summary["total_types"], 30)

        cfg = VoucherTypeConfig.objects.create(
            company=self.company,
            parent_type="PAYMENT",
            code="HO_BANK_PAY",
            name="Head Office Bank Payment",
            voucher_category=VoucherTypeConfig.Category.ACCOUNTING,
            abbreviation="HBP",
            numbering_method=VoucherTypeConfig.NumberingMethod.MULTI_SERIES,
            series_code="HO2",
            prefix="HBP-",
            zero_pad_width=4,
            reset_frequency=VoucherTypeConfig.ResetFrequency.MONTHLY,
        )
        v1 = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={"voucher_type": "PAYMENT", "voucher_type_config": cfg, "voucher_date": self.v_date},
            lines_data=[
                {"account": self.acc_exp, "debit": Decimal("1000.00"), "credit": Decimal("0.00")},
                {"account": self.acc_bank, "debit": Decimal("0.00"), "credit": Decimal("1000.00")},
            ],
        )
        VoucherService.submit_voucher(voucher=v1, user=self.finance)
        ApprovalService.approve_voucher(voucher=v1, user=self.approver)
        v1 = PostingService.post_voucher(voucher=v1, user=self.approver)
        self.assertTrue(v1.voucher_no.startswith("HBP-208304-"))

        # Next BS month resets sequence back to 0001
        v2_date = bs_to_ad(2083, 5, 10)
        v2 = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={"voucher_type": "PAYMENT", "voucher_type_config": cfg, "voucher_date": v2_date},
            lines_data=[
                {"account": self.acc_exp, "debit": Decimal("500.00"), "credit": Decimal("0.00")},
                {"account": self.acc_bank, "debit": Decimal("0.00"), "credit": Decimal("500.00")},
            ],
        )
        VoucherService.submit_voucher(voucher=v2, user=self.finance)
        ApprovalService.approve_voucher(voucher=v2, user=self.approver)
        v2 = PostingService.post_voucher(voucher=v2, user=self.approver)
        self.assertEqual(v2.voucher_no, "HBP-208305-0001")

    def test_single_entry_mode_and_voucher_class_automation(self):
        # Single-Entry payment automatically generates balancing Credit line on Bank Account
        v_single = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={
                "voucher_type": "PAYMENT",
                "entry_mode": Voucher.EntryMode.SINGLE_ENTRY,
                "single_entry_account": self.acc_bank,
                "voucher_date": self.v_date,
                "narration": "Single entry site expense",
            },
            lines_data=[
                {"account": self.acc_exp, "debit": Decimal("2500.00"), "credit": Decimal("0.00"), "amount": Decimal("2500.00")},
            ],
        )
        self.assertEqual(v_single.lines.count(), 2)
        auto_bank = v_single.lines.filter(account=self.acc_bank).first()
        self.assertIsNotNone(auto_bank)
        self.assertEqual(auto_bank.credit, Decimal("2500.00"))

        # Voucher Class automatically adds 13% VAT line and offsets creditor payable
        cfg_pur = VoucherTypeConfig.objects.create(
            company=self.company, parent_type="PURCHASE", code="PUR_STD", name="Purchase Std", abbreviation="PU"
        )
        vclass = VoucherClass.objects.create(
            company=self.company,
            voucher_type_config=cfg_pur,
            code="VAT13",
            name="13% VAT Purchase",
            default_ledger=self.acc_inv,
            tax_ledger=self.acc_vat,
            default_tax_rate=Decimal("13.00"),
            default_project=self.project,
        )
        v_cls = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={
                "voucher_type": "PURCHASE",
                "voucher_type_config": cfg_pur,
                "voucher_class": vclass,
                "party": self.supplier,
                "voucher_date": self.v_date,
                "entry_mode": Voucher.EntryMode.ITEM_INVOICE,
                "inventory_items": [
                    {
                        "item_id": str(self.item.id),
                        "warehouse_id": str(self.warehouse.id),
                        "quantity": "10",
                        "rate": "800.00",
                    }
                ],
            },
            lines_data=[
                {"account": self.acc_inv, "debit": Decimal("8000.00"), "credit": Decimal("0.00")},
            ],
        )
        self.assertEqual(v_cls.inventory_items.count(), 1)
        vat_line = v_cls.lines.filter(account=self.acc_vat).first()
        ap_line = v_cls.lines.filter(account=self.acc_ap).first()
        self.assertIsNotNone(vat_line)
        self.assertEqual(vat_line.debit, Decimal("1040.00"))
        self.assertEqual(ap_line.credit, Decimal("9040.00"))

    def test_cost_centre_multi_split_validation_and_report(self):
        # Invalid percentage sum (80% != 100%) blocked on draft creation
        with self.assertRaises(ValidationError):
            VoucherService.create_draft(
                company=self.company,
                user=self.finance,
                data={"voucher_type": "JOURNAL", "voucher_date": self.v_date},
                lines_data=[
                    {
                        "account": self.acc_exp,
                        "debit": Decimal("1000.00"),
                        "credit": Decimal("0.00"),
                        "cost_allocations": [
                            {"cost_center": str(self.cc_a.id), "allocation_mode": "PERCENTAGE", "percentage": "50.00", "amount": "500.00"},
                            {"cost_center": str(self.cc_b.id), "allocation_mode": "PERCENTAGE", "percentage": "30.00", "amount": "300.00"},
                        ],
                    },
                    {"account": self.acc_cash, "debit": Decimal("0.00"), "credit": Decimal("1000.00")},
                ],
            )

        # Valid 60% / 40% split posts and appears accurately in CostCentreReport
        v = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={"voucher_type": "JOURNAL", "voucher_date": self.v_date, "project": self.project},
            lines_data=[
                {
                    "account": self.acc_exp,
                    "debit": Decimal("10000.00"),
                    "credit": Decimal("0.00"),
                    "cost_allocations": [
                        {"cost_center": str(self.cc_a.id), "allocation_mode": "PERCENTAGE", "percentage": "60.00", "amount": "6000.00"},
                        {"cost_center": str(self.cc_b.id), "allocation_mode": "PERCENTAGE", "percentage": "40.00", "amount": "4000.00"},
                    ],
                },
                {"account": self.acc_cash, "debit": Decimal("0.00"), "credit": Decimal("10000.00")},
            ],
        )
        self.assertEqual(VoucherLineCostAllocation.objects.filter(voucher_line__voucher=v).count(), 2)
        VoucherService.submit_voucher(voucher=v, user=self.finance)
        ApprovalService.approve_voucher(voucher=v, user=self.approver)
        PostingService.post_voucher(voucher=v, user=self.approver)

        rep = ExtendedReportService.get_cost_centre_report(company=self.company)
        by_code = {r["code"]: r for r in rep["rows"]}
        self.assertEqual(Decimal(by_code["CC-A"]["debit"]), Decimal("6000.00"))
        self.assertEqual(Decimal(by_code["CC-B"]["debit"]), Decimal("4000.00"))

    def test_provisional_isolation_scenario_and_conversion_and_reversing_pair(self):
        v_opt = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={
                "voucher_type": "OPTIONAL",
                "provisional_kind": Voucher.ProvisionalKind.OPTIONAL,
                "voucher_date": self.v_date,
                "narration": "What-if machinery lease",
            },
            lines_data=[
                {"account": self.acc_exp, "debit": Decimal("50000.00"), "credit": Decimal("0.00")},
                {"account": self.acc_bank, "debit": Decimal("0.00"), "credit": Decimal("50000.00")},
            ],
        )
        self.assertEqual(v_opt.status, Voucher.Status.OPTIONAL)
        self.assertEqual(LedgerEntry.objects.filter(company=self.company).count(), 0)

        # Direct posting blocked
        with self.assertRaises(ValidationError):
            PostingService.post_voucher(voucher=v_opt, user=self.finance)

        # Scenario Statement picks up Optional impact cleanly without touching GL
        scen = ExtendedReportService.get_scenario_statement(company=self.company, include_optional=True)
        self.assertEqual(scen["provisional_voucher_count"], 1)
        by_code = {r["code"]: r for r in scen["rows"]}
        self.assertEqual(Decimal(by_code["51010"]["actual_net"]), Decimal("0.00"))
        self.assertEqual(Decimal(by_code["51010"]["provisional_net"]), Decimal("50000.00"))

        # Convert Optional -> Regular Posted Voucher
        regular = VoucherService.convert_provisional_to_regular(voucher=v_opt, user=self.approver)
        self.assertEqual(regular.status, Voucher.Status.POSTED)
        self.assertEqual(regular.provisional_kind, Voucher.ProvisionalKind.REGULAR)
        v_opt.refresh_from_db()
        self.assertEqual(v_opt.status, Voucher.Status.CANCELLED)

        # Reversing Journal creates & posts both primary + auto-reversal next day
        v_rev = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={
                "voucher_type": "REVERSING_JOURNAL",
                "provisional_kind": Voucher.ProvisionalKind.REVERSING_JOURNAL,
                "voucher_date": self.v_date,
                "reverse_on_date": self.v_date + timedelta(days=1),
                "narration": "Period-end accrual",
            },
            lines_data=[
                {"account": self.acc_exp, "debit": Decimal("12000.00"), "credit": Decimal("0.00")},
                {"account": self.acc_ap, "party": self.supplier, "debit": Decimal("0.00"), "credit": Decimal("12000.00")},
            ],
        )
        pair = VoucherService.post_reversing_journal_pair(voucher=v_rev, user=self.approver)
        self.assertEqual(pair["primary"].status, Voucher.Status.POSTED)
        self.assertEqual(pair["reversal"].status, Voucher.Status.POSTED)
        self.assertEqual(LedgerEntry.objects.filter(voucher=pair["primary"]).count(), 2)
        self.assertEqual(LedgerEntry.objects.filter(voucher=pair["reversal"]).count(), 2)

    def test_bill_wise_settlement_revisions_inline_account_and_rbac_guard(self):
        # Create OpenItem AP invoice directly via posted Purchase voucher
        v_pur = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={"voucher_type": "PURCHASE", "party": self.supplier, "supplier_invoice_no": "BILL-991", "voucher_date": self.v_date},
            lines_data=[
                {"account": self.acc_exp, "debit": Decimal("15000.00"), "credit": Decimal("0.00")},
                {"account": self.acc_ap, "party": self.supplier, "debit": Decimal("0.00"), "credit": Decimal("15000.00")},
            ],
        )
        VoucherService.submit_voucher(voucher=v_pur, user=self.finance)
        ApprovalService.approve_voucher(voucher=v_pur, user=self.approver)
        PostingService.post_voucher(voucher=v_pur, user=self.approver)
        oi = OpenItem.objects.get(company=self.company, party=self.supplier, is_unallocated_credit=False)
        self.assertEqual(oi.remaining_amount, Decimal("15000.00"))

        # Payment voucher with bill_wise_allocations AGAINST_REF settles OpenItem
        v_pay = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={
                "voucher_type": "PAYMENT",
                "party": self.supplier,
                "voucher_date": self.v_date,
                "bill_wise_allocations": [{"ref_type": "AGAINST_REF", "open_item_id": str(oi.id), "ref_no": oi.document_no, "amount": "10000.00"}],
            },
            lines_data=[
                {"account": self.acc_ap, "party": self.supplier, "debit": Decimal("10000.00"), "credit": Decimal("0.00")},
                {"account": self.acc_bank, "debit": Decimal("0.00"), "credit": Decimal("10000.00")},
            ],
        )
        # Edit draft via REST API PATCH -> creates VoucherRevision
        patch_res = self.client.patch(
            f"/api/v1/vouchers/{v_pay.id}/",
            {
                "voucher_type": "PAYMENT",
                "voucher_date": self.v_date.isoformat(),
                "party": str(self.supplier.id),
                "narration": "Updated payment narration",
                "bill_wise_allocations": [{"ref_type": "AGAINST_REF", "open_item_id": str(oi.id), "ref_no": oi.document_no, "amount": "10000.00"}],
                "lines": [
                    {"account": str(self.acc_ap.id), "party": str(self.supplier.id), "debit": "10000.00", "credit": "0.00"},
                    {"account": str(self.acc_bank.id), "debit": "0.00", "credit": "10000.00"},
                ],
            },
            format="json",
        )
        self.assertEqual(patch_res.status_code, 200)
        self.assertEqual(VoucherRevision.objects.filter(voucher=v_pay).count(), 1)

        v_pay.refresh_from_db()
        VoucherService.submit_voucher(voucher=v_pay, user=self.finance)
        ApprovalService.approve_voucher(voucher=v_pay, user=self.approver)
        PostingService.post_voucher(voucher=v_pay, user=self.approver)
        oi.refresh_from_db()
        self.assertEqual(oi.remaining_amount, Decimal("5000.00"))

        # Inline Alt+C account creation endpoint
        inline_res = self.client.post(
            "/api/v1/accounts/inline-create/",
            {"code": "59991", "name": "Temp Site Clearing", "account_type": "EXPENSE", "account_class": "EXPENSE"},
            format="json",
        )
        self.assertEqual(inline_res.status_code, 201)

        # RBAC 403 guard for Supervisor
        self.client.force_authenticate(user=self.supervisor)
        denied_type = self.client.post(
            "/api/v1/voucher-types/",
            {"parent_type": "PAYMENT", "code": "X_BAD", "name": "Denied"},
            format="json",
        )
        self.assertEqual(denied_type.status_code, 403)
        denied_scen = self.client.get("/api/v1/reports/scenarios/")
        self.assertEqual(denied_scen.status_code, 403)

