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,
    LedgerEntry,
    Party,
    Voucher,
    VoucherDesignRevision,
    VoucherLayoutBlueprint,
    VoucherThemeConfig,
)
from apps.accounting.services import (
    ApprovalService,
    PostingRuleEngine,
    PostingService,
    VoucherDesignService,
    VoucherService,
)
from apps.banking.models import Bank, BankAccount, BankBranch
from apps.inventory.models import ItemCategory, ItemMaster, StockMovement, UnitOfMeasure, Warehouse
from apps.loans.models import BankFacility
from apps.localization.bs_calendar import bs_to_ad
from apps.projects.models import Project
from apps.tenancy.models import Branch, Company, FiscalYear


class VoucherLayoutsDesignStudioAndLogicTests(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.admin = User.objects.create_user(username="ds_admin", email="ds_admin@test.local", password="Password@123")
        self.finance = User.objects.create_user(username="ds_fin", email="ds_fin@test.local", password="Password@123")
        self.supervisor = User.objects.create_user(username="ds_sup", email="ds_sup@test.local", password="Password@123")

        self.company = Company.objects.create(
            code="DSCO", name="Maya Design Studio Infra", pan_vat_no="605554443", base_currency="NPR"
        )
        self.branch = Branch.objects.create(company=self.company, code="KTM", name="Kathmandu HO")
        CompanyMembership.objects.create(user=self.admin, company=self.company, role=self.roles["COMPANY_ADMIN"], is_default=True)
        CompanyMembership.objects.create(user=self.finance, company=self.company, role=self.roles["FINANCE_MANAGER"], 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.v_date = bs_to_ad(2083, 4, 20)

        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_bank = Account.objects.create(company=self.company, code="10201", name="Nabil Bank", account_type=Account.AccountType.ASSET, control_role=Account.ControlRole.BANK, allow_direct_posting=True)
        self.acc_inv = Account.objects.create(company=self.company, code="13001", name="Site Inventory", account_type=Account.AccountType.ASSET, control_role=Account.ControlRole.INVENTORY, allow_direct_posting=True)
        self.acc_wip = Account.objects.create(company=self.company, code="14001", name="Project WIP", account_type=Account.AccountType.EXPENSE, control_role=Account.ControlRole.PROJECT_WIP, allow_direct_posting=True)
        self.acc_exp = Account.objects.create(company=self.company, code="50201", name="Wages & Direct Cost", account_type=Account.AccountType.EXPENSE, control_role=Account.ControlRole.DIRECT_EXPENSES, allow_direct_posting=True)
        self.acc_rev = Account.objects.create(company=self.company, code="40101", name="Contract Revenue", account_type=Account.AccountType.INCOME, allow_direct_posting=True)
        self.acc_ar = Account.objects.create(company=self.company, code="11001", name="Sundry Debtors", account_type=Account.AccountType.ASSET, control_role=Account.ControlRole.SUNDRY_DEBTORS, requires_subledger=True, is_control_account=True, 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_sub = Account.objects.create(company=self.company, code="20201", name="Subcontractor Payable", account_type=Account.AccountType.LIABILITY, control_role=Account.ControlRole.SUBCONTRACTOR_PAYABLE, requires_subledger=True, is_control_account=True, allow_direct_posting=True)
        self.acc_vat_in = Account.objects.create(company=self.company, code="12501", name="Input VAT", account_type=Account.AccountType.ASSET, control_role=Account.ControlRole.INPUT_VAT, allow_direct_posting=True)
        self.acc_vat_out = Account.objects.create(company=self.company, code="20401", name="Output VAT", account_type=Account.AccountType.LIABILITY, control_role=Account.ControlRole.OUTPUT_VAT, allow_direct_posting=True)
        self.acc_tds = Account.objects.create(company=self.company, code="20501", name="TDS Payable", control_role=Account.ControlRole.TDS_PAYABLE, account_type=Account.AccountType.LIABILITY, allow_direct_posting=True)
        self.acc_ret_pay = Account.objects.create(company=self.company, code="20601", name="Retention Payable", account_type=Account.AccountType.LIABILITY, control_role=Account.ControlRole.RETENTION_PAYABLE, allow_direct_posting=True)
        self.acc_ret_rec = Account.objects.create(company=self.company, code="11601", name="Retention Receivable", account_type=Account.AccountType.ASSET, control_role=Account.ControlRole.RETENTION_RECEIVABLE, allow_direct_posting=True)
        self.acc_loan_liab = Account.objects.create(company=self.company, code="22001", name="Term Loan Liability", account_type=Account.AccountType.LIABILITY, allow_direct_posting=True)
        self.acc_int_exp = Account.objects.create(company=self.company, code="60101", name="Bank Interest Expense", account_type=Account.AccountType.EXPENSE, allow_direct_posting=True)
        self.acc_asset = Account.objects.create(company=self.company, code="15001", name="Plant & Machinery", account_type=Account.AccountType.ASSET, allow_direct_posting=True)
        self.acc_accum = Account.objects.create(company=self.company, code="15901", name="Accum Depr", account_type=Account.AccountType.ASSET, account_class=Account.AccountClass.CONTRA_ASSET, control_role=Account.ControlRole.ACCUM_DEPRECIATION, allow_direct_posting=True)
        self.acc_gain = Account.objects.create(company=self.company, code="42001", name="Gain on Disposal", account_type=Account.AccountType.INCOME, control_role=Account.ControlRole.OTHER_INCOME, allow_direct_posting=True)

        self.project = Project.objects.create(company=self.company, code="PRJ-DS", name="Highway Bridge", budget_amount=Decimal("2000000.00"))
        self.client_party = Party.objects.create(company=self.company, party_type=Party.PartyType.CUSTOMER, code="CLI-01", name="DoR Nepal", control_account=self.acc_ar)
        self.sub_party = Party.objects.create(company=self.company, party_type=Party.PartyType.SUBCONTRACTOR, code="SUB-01", name="Piling Works JV", control_account=self.acc_sub)

        cat = ItemCategory.objects.create(company=self.company, code="STEEL", name="TMT Steel")
        uom = UnitOfMeasure.objects.create(company=self.company, code="MT", name="Metric Ton")
        self.item = ItemMaster.objects.create(company=self.company, item_code="TMT-16", name="16mm Rebar", category=cat, primary_unit=uom, standard_rate=Decimal("100000.00"), inventory_account=self.acc_inv)
        self.wh = Warehouse.objects.create(company=self.company, code="WH-SITE", name="Bridge Store", store_kind=Warehouse.StoreKind.SITE_STORE)

        bank_obj = Bank.objects.create(company=self.company, name="Nabil Bank Ltd", short_code="NBL")
        bank_br = BankBranch.objects.create(bank=bank_obj, branch_code="KTM", name="Kantipath")
        self.bank_rec = BankAccount.objects.create(
            company=self.company, bank_branch=bank_br, account_name="Nabil Current",
            account_number_masked="****4321", account_number_encrypted="enc", account_number_hash="hash4321",
            account_type=BankAccount.AccountType.CURRENT, gl_account=self.acc_bank,
        )
        self.loan_fac = BankFacility.objects.create(
            company=self.company, bank_account=self.bank_rec, project=self.project,
            facility_code="TL-01", facility_name="Excavator Term Loan", facility_type=BankFacility.FacilityType.EQUIPMENT_LOAN,
            sanction_date=self.v_date, maturity_date=self.v_date.replace(year=self.v_date.year + 2),
            sanctioned_limit=Decimal("5000000.00"), linked_liability_account=self.acc_loan_liab, linked_interest_account=self.acc_int_exp,
        )

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

    def test_39_blueprints_8_themes_hierarchy_revisions_and_rbac_guard(self):
        summary = VoucherDesignService.ensure_default_design_studio_catalog(self.company)
        self.assertGreaterEqual(summary["total_blueprints"], 39)
        self.assertEqual(VoucherThemeConfig.objects.filter(company=self.company, voucher_type="ALL").count(), 8)

        # Distinct layout families exist (no universal one-form catalog)
        families = set(VoucherLayoutBlueprint.objects.filter(company=self.company).values_list("layout_family", flat=True))
        self.assertGreaterEqual(len(families), 8)

        # Resolve hierarchical scope: company -> branch -> user
        res_co = VoucherDesignService.resolve_blueprint_and_theme(company=self.company, voucher_type="PAYMENT")
        self.assertEqual(res_co["blueprint"]["scope"], "COMPANY")
        self.assertEqual(res_co["blueprint"]["layout_family"], "BANKING_SETTLEMENT")

        bp_branch = VoucherLayoutBlueprint.objects.create(
            company=self.company, branch=self.branch, voucher_type="PAYMENT",
            layout_family="BANKING_SETTLEMENT", title="Kathmandu Branch Payment",
            default_theme_code="FORMAL_PRINT", is_default=False,
        )
        res_br = VoucherDesignService.resolve_blueprint_and_theme(company=self.company, voucher_type="PAYMENT", branch=self.branch)
        self.assertEqual(res_br["blueprint"]["scope"], "BRANCH")
        self.assertEqual(res_br["theme"]["theme_code"], "FORMAL_PRINT")

        # Design Studio edit creates revision + restore rolls back cleanly
        co_bp = VoucherLayoutBlueprint.objects.get(company=self.company, voucher_type="CONTRA", branch__isnull=True, user__isnull=True)
        patch = self.client.patch(
            f"/api/v1/voucher-blueprints/{co_bp.id}/",
            {"title": "Treasury Contra v2", "default_theme_code": "TALLY_CLASSIC", "change_summary": "Updated Contra title"},
            format="json",
        )
        self.assertEqual(patch.status_code, 200)
        self.assertEqual(patch.json()["version"], 2)
        rev = VoucherDesignRevision.objects.get(blueprint=co_bp, version=2)
        restore = self.client.post(f"/api/v1/voucher-blueprints/{co_bp.id}/restore/", {"revision_id": str(rev.id)}, format="json")
        self.assertEqual(restore.status_code, 200)
        self.assertEqual(restore.json()["version"], 3)

        # Functional Context API works per voucher type
        ctx_loan = self.client.get("/api/v1/vouchers/functional-context/?voucher_type=LOAN_REPAYMENT")
        self.assertEqual(ctx_loan.status_code, 200)
        self.assertEqual(len(ctx_loan.json()["loan_facilities"]), 1)

        # RBAC 403 for supervisor trying to edit design blueprint
        self.client.force_authenticate(user=self.supervisor)
        denied = self.client.patch(f"/api/v1/voucher-blueprints/{bp_branch.id}/", {"title": "Hack"}, format="json")
        self.assertEqual(denied.status_code, 403)

    def test_theme_never_changes_accounting_logic_and_13_dim_logic_view(self):
        lines_contra = PostingRuleEngine.derive_scenario_lines(
            company=self.company,
            voucher_type="CONTRA",
            scenario={"taxable_amount": "25000.00", "source_account": str(self.acc_cash.id), "destination_account": str(self.acc_bank.id)},
            project=self.project,
        )
        plan = PostingRuleEngine.build_voucher_accounting_plan(
            company=self.company, voucher_type="CONTRA", voucher_date=self.v_date, lines_data=lines_contra
        )
        self.assertTrue(plan["is_valid"])
        self.assertEqual(Decimal(plan["total_debit"]), Decimal("25000.00"))
        self.assertEqual(len(plan["cash_bank_impact"]), 2)
        for key in ("journal_preview", "tax_tds_impact", "retention_impact", "inventory_movements", "cash_bank_impact", "project_cost_impact", "invoice_allocations", "statement_impact", "resulting_balances"):
            self.assertIn(key, plan)

        # Same payload posted under TALLY_CLASSIC vs CONSTRUCTION_SITE creates identical GL figures
        v1 = VoucherService.create_draft(company=self.company, user=self.finance, data={"voucher_type": "CONTRA", "voucher_date": self.v_date, "theme_code": "TALLY_CLASSIC"}, lines_data=lines_contra)
        v2 = VoucherService.create_draft(company=self.company, user=self.finance, data={"voucher_type": "CONTRA", "voucher_date": self.v_date, "theme_code": "CONSTRUCTION_SITE"}, lines_data=lines_contra)
        VoucherService.submit_voucher(voucher=v1, user=self.finance)
        ApprovalService.approve_voucher(voucher=v1, user=self.admin)
        PostingService.post_voucher(voucher=v1, user=self.admin)
        VoucherService.submit_voucher(voucher=v2, user=self.finance)
        ApprovalService.approve_voucher(voucher=v2, user=self.admin)
        PostingService.post_voucher(voucher=v2, user=self.admin)

        le1 = [(l.account_id, l.base_debit, l.base_credit) for l in LedgerEntry.objects.filter(voucher=v1).order_by("voucher_line__line_no")]
        le2 = [(l.account_id, l.base_debit, l.base_credit) for l in LedgerEntry.objects.filter(voucher=v2).order_by("voucher_line__line_no")]
        self.assertEqual(le1, le2)

    def test_specialized_derivations_stock_single_movement_loan_and_asset(self):
        # 1. Receipt Note (Stock In) + Material Issue (Stock Out once)
        lines_in = PostingRuleEngine.derive_scenario_lines(company=self.company, voucher_type="MATERIAL_RETURN", scenario={"taxable_amount": "500000.00"}, project=self.project)
        v_in = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={"voucher_type": "RECEIPT_NOTE", "voucher_date": self.v_date, "inventory_items": [{"item_id": str(self.item.id), "warehouse_id": str(self.wh.id), "quantity": "5", "rate": "100000.00"}]},
            lines_data=lines_in,
        )
        VoucherService.submit_voucher(voucher=v_in, user=self.finance)
        ApprovalService.approve_voucher(voucher=v_in, user=self.admin)
        PostingService.post_voucher(voucher=v_in, user=self.admin)
        self.assertEqual(StockMovement.objects.filter(voucher=v_in).count(), 1)

        # Idempotent re-post never doubles stock movement
        PostingService.post_voucher(voucher=v_in, user=self.admin)
        self.assertEqual(StockMovement.objects.filter(voucher=v_in).count(), 1)

        lines_out = PostingRuleEngine.derive_scenario_lines(company=self.company, voucher_type="MATERIAL_ISSUE", scenario={"taxable_amount": "200000.00"}, project=self.project)
        v_out = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={"voucher_type": "MATERIAL_ISSUE", "voucher_date": self.v_date, "project": self.project, "inventory_items": [{"item_id": str(self.item.id), "warehouse_id": str(self.wh.id), "quantity": "2", "rate": "100000.00"}]},
            lines_data=lines_out,
        )
        VoucherService.submit_voucher(voucher=v_out, user=self.finance)
        ApprovalService.approve_voucher(voucher=v_out, user=self.admin)
        PostingService.post_voucher(voucher=v_out, user=self.admin)
        last_mv = StockMovement.objects.filter(warehouse=self.wh, item=self.item).order_by("-created_at").first()
        self.assertEqual(last_mv.balance_qty_after, Decimal("3.000"))

        # Over-issue blocked by negative stock guard
        lines_bad = PostingRuleEngine.derive_scenario_lines(company=self.company, voucher_type="MATERIAL_ISSUE", scenario={"taxable_amount": "900000.00"}, project=self.project)
        v_bad = VoucherService.create_draft(
            company=self.company,
            user=self.finance,
            data={"voucher_type": "MATERIAL_ISSUE", "voucher_date": self.v_date, "project": self.project, "inventory_items": [{"item_id": str(self.item.id), "warehouse_id": str(self.wh.id), "quantity": "9", "rate": "100000.00"}]},
            lines_data=lines_bad,
        )
        VoucherService.submit_voucher(voucher=v_bad, user=self.finance)
        ApprovalService.approve_voucher(voucher=v_bad, user=self.admin)
        with self.assertRaises(ValidationError):
            PostingService.post_voucher(voucher=v_bad, user=self.admin)

        # 2. Subcontractor Bill, Client RA Bill, Loan Repayment, Asset Disposal balanced cleanly
        sub_lines = PostingRuleEngine.derive_scenario_lines(
            company=self.company, voucher_type="SUBCONTRACTOR_BILL",
            scenario={"taxable_amount": "100000.00", "retention_pct": "5", "tds_rate": "1.5"},
            party=self.sub_party, project=self.project,
        )
        self.assertEqual(sum(l["debit"] for l in sub_lines), sum(l["credit"] for l in sub_lines))

        loan_lines = PostingRuleEngine.derive_scenario_lines(
            company=self.company, voucher_type="LOAN_REPAYMENT",
            scenario={"taxable_amount": "55000.00", "bank_account": str(self.acc_bank.id), "liability_account": str(self.acc_loan_liab.id), "interest_account": str(self.acc_int_exp.id), "principal_amount": "50000.00", "interest_amount": "5000.00"},
        )
        self.assertEqual(sum(l["debit"] for l in loan_lines), Decimal("55000.00"))
        self.assertEqual(sum(l["credit"] for l in loan_lines), Decimal("55000.00"))

        disp_lines = PostingRuleEngine.derive_scenario_lines(
            company=self.company, voucher_type="ASSET_DISPOSAL",
            scenario={"taxable_amount": "100000.00", "bank_account": str(self.acc_bank.id), "asset_cost": "100000.00", "accumulated_depreciation": "40000.00", "proceeds_amount": "75000.00"},
        )
        # Proceeds 75k + Accum Depr 40k = 115k Dr; Asset 100k + Gain 15k = 115k Cr!
        self.assertEqual(sum(l["debit"] for l in disp_lines), Decimal("115000.00"))
        self.assertEqual(sum(l["credit"] for l in disp_lines), Decimal("115000.00"))
