from datetime import date
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, Voucher
from apps.accounting.services import ReportingService, VoucherService, PostingService
from apps.banking.models import Bank, BankBranch, BankStatementLine, ChequeLeaf
from apps.banking.services import BankingService
from apps.currency.models import ExchangeRate
from apps.currency.services import run_period_end_revaluation
from apps.localization.bs_calendar import bs_to_ad
from apps.loans.models import BankFacility, BankGuarantee, NrbRegulatoryConfig
from apps.loans.services import LoanService
from apps.projects.models import Project
from apps.tenancy.models import Company, FiscalYear


class EnterpriseTreasuryBankingLoansTests(TestCase):
    def setUp(self):
        self.roles = {
            code: Role.objects.create(
                code=code,
                name=spec["name"],
                description=spec["description"],
                permissions=spec["permissions"],
                is_system=True,
            )
            for code, spec in ROLE_PRESETS.items()
        }
        self.company = Company.objects.create(
            code="TRES1", name="Treasury Construction Ltd", base_currency="NPR", multi_currency_enabled=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.admin = User.objects.create_user(
            username="tres_adm", email="tadm@test.local", password="Password@123"
        )
        self.checker = User.objects.create_user(
            username="tres_chk", email="tchk@test.local", password="Password@123"
        )
        CompanyMembership.objects.create(
            user=self.admin, company=self.company, role=self.roles["COMPANY_ADMIN"], is_default=True
        )
        CompanyMembership.objects.create(
            user=self.checker, company=self.company, role=self.roles["FINANCE_MANAGER"], is_default=True
        )

        self.equity = Account.objects.create(
            company=self.company, code="3010", name="Capital", account_type=Account.AccountType.EQUITY, opening_credit=Decimal("0.00")
        )
        self.bank = Bank.objects.create(company=self.company, name="Nabil", short_code="NABIL")
        self.bbranch = BankBranch.objects.create(bank=self.bank, branch_code="KTM", name="Kathmandu")
        self.ba = BankingService.create_bank_account(
            company=self.company,
            user=self.admin,
            bank_branch=self.bbranch,
            account_name="Nabil NPR",
            account_number="0011223344",
            account_type="CURRENT",
            purpose="GENERAL",
            currency="NPR",
            opening_balance=Decimal("1000000.00"),
        )
        self.project = Project.objects.create(company=self.company, code="PRJ-T1", name="Dam Project")

    def test_duplicate_bank_account_blocked_and_masked(self):
        self.assertTrue(self.ba.account_number_masked.endswith("3344"))
        with self.assertRaises(ValidationError):
            BankingService.create_bank_account(
                company=self.company,
                user=self.admin,
                bank_branch=self.bbranch,
                account_name="Dup",
                account_number="0011223344",
                account_type="CURRENT",
                purpose="GENERAL",
                currency="NPR",
                opening_balance=Decimal("0.00"),
            )

    def test_statement_import_dedup_automatch_partial_and_charge_posting(self):
        # Create posted payment voucher matching one statement debit
        exp = Account.objects.create(company=self.company, code="5010", name="Mat Exp", account_type=Account.AccountType.EXPENSE)
        v = VoucherService.create_draft(
            company=self.company,
            user=self.admin,
            data={"voucher_type": Voucher.VoucherType.PAYMENT, "voucher_date": date(2026, 11, 20), "reference_no": "REF-77"},
            lines_data=[
                {"account": exp, "debit": Decimal("50000.00"), "credit": Decimal("0.00")},
                {"account": self.ba.gl_account, "debit": Decimal("0.00"), "credit": Decimal("50000.00")},
            ],
        )
        v.status = Voucher.Status.APPROVED
        v.save()
        PostingService.post_voucher(voucher=v, user=self.admin)

        csv_bytes = (
            b"Date,Reference,Cheque,Description,Debit,Credit,Balance\n"
            b"2026-11-20,REF-77,,Steel Payment,50000.00,0.00,950000.00\n"
            b"2026-11-21,CHG-01,,SMS & Account Fee,500.00,0.00,949500.00\n"
        )
        imp1 = BankingService.import_statement(
            company=self.company, user=self.admin, bank_account=self.ba, file_name="s1.csv", file_format="CSV", content_bytes=csv_bytes
        )
        self.assertEqual(imp1.imported_count, 2)
        self.assertEqual(imp1.skipped_duplicates, 0)

        # Re-importing same CSV skips duplicates cleanly
        imp2 = BankingService.import_statement(
            company=self.company, user=self.admin, bank_account=self.ba, file_name="s1.csv", file_format="CSV", content_bytes=csv_bytes
        )
        self.assertEqual(imp2.imported_count, 0)
        self.assertEqual(imp2.skipped_duplicates, 2)

        lines = list(BankStatementLine.objects.filter(bank_account=self.ba).order_by("txn_date"))
        self.assertEqual(lines[0].match_status, BankStatementLine.MatchStatus.MATCHED)
        self.assertEqual(lines[1].match_status, BankStatementLine.MatchStatus.UNMATCHED)

        # One-click bank charge suggestion posts JV & reconciles line
        BankingService.post_charge_or_interest(statement_line=lines[1], user=self.admin, kind="CHARGE")
        lines[1].refresh_from_db()
        self.assertEqual(lines[1].match_status, BankStatementLine.MatchStatus.MATCHED)

    def test_cheque_bounce_reverses_voucher_and_prevents_duplicates(self):
        book = BankingService.create_cheque_book(
            company=self.company,
            bank_account=self.ba,
            book_code="CB-1",
            prefix="CH-",
            start_number=1,
            end_number=3,
            issued_date=date(2026, 11, 1),
        )
        leaf = ChequeLeaf.objects.get(cheque_book=book, cheque_number="CH-1")
        exp = Account.objects.create(company=self.company, code="5010", name="Expense", account_type=Account.AccountType.EXPENSE)
        v = VoucherService.create_draft(
            company=self.company,
            user=self.admin,
            data={"voucher_type": Voucher.VoucherType.PAYMENT, "voucher_date": date(2026, 11, 20)},
            lines_data=[
                {"account": exp, "debit": Decimal("15000.00"), "credit": Decimal("0.00")},
                {"account": self.ba.gl_account, "debit": Decimal("0.00"), "credit": Decimal("15000.00")},
            ],
        )
        v.status = Voucher.Status.APPROVED
        v.save()
        v = PostingService.post_voucher(voucher=v, user=self.admin)

        leaf.status = ChequeLeaf.Status.ISSUED
        leaf.voucher = v
        leaf.amount = Decimal("15000.00")
        leaf.save()

        BankingService.transition_cheque(leaf=leaf, action="bounce", user=self.admin, action_date=date(2026, 11, 22), reason="Insufficient funds")
        leaf.refresh_from_db()
        v.refresh_from_db()
        self.assertEqual(leaf.status, ChequeLeaf.Status.BOUNCED)
        self.assertEqual(v.status, Voucher.Status.REVERSED)
        self.assertEqual(BankingService.get_gl_balance(self.ba.gl_account), Decimal("1000000.00"))

    def test_multi_currency_revaluation_and_loans_od_cc_bg(self):
        # Foreign Currency Bank Account + Revaluation
        ba_usd = BankingService.create_bank_account(
            company=self.company,
            user=self.admin,
            bank_branch=self.bbranch,
            account_name="USD Account",
            account_number="99887766",
            account_type="FOREIGN_CURRENCY",
            purpose="GENERAL",
            currency="USD",
            opening_balance=Decimal("0.00"),
        )
        rev_acc = Account.objects.create(company=self.company, code="4010", name="FX Sales", account_type=Account.AccountType.INCOME)
        v_fc = VoucherService.create_draft(
            company=self.company,
            user=self.admin,
            data={"voucher_type": Voucher.VoucherType.RECEIPT, "voucher_date": date(2026, 11, 10), "currency": "USD", "exchange_rate": Decimal("133.000000")},
            lines_data=[
                {"account": ba_usd.gl_account, "debit": Decimal("1000.00"), "credit": Decimal("0.00")},
                {"account": rev_acc, "debit": Decimal("0.00"), "credit": Decimal("1000.00")},
            ],
        )
        v_fc.status = Voucher.Status.APPROVED
        v_fc.save()
        PostingService.post_voucher(voucher=v_fc, user=self.admin)

        ExchangeRate.objects.create(
            company=self.company,
            from_currency="USD",
            to_currency="NPR",
            effective_date=date(2026, 11, 28),
            buy_rate=Decimal("135.000000"),
            sell_rate=Decimal("135.000000"),
            mid_rate=Decimal("135.000000"),
        )
        run = run_period_end_revaluation(
            company=self.company, user=self.admin, revaluation_date=date(2026, 11, 28), currency_code="USD"
        )
        self.assertEqual(run.unrealized_gain_loss, Decimal("2000.00"))

        # NRB Limit Check + Term Loan + CC Drawing Power + BG Invocation
        NrbRegulatoryConfig.objects.create(
            company=self.company,
            directive_code="NRB-TEST",
            title="Test Directive",
            effective_from=date(2026, 1, 1),
            od_max_limit_npr=Decimal("1000000.00"),
            cc_default_haircut_pct=Decimal("25.00"),
        )
        with self.assertRaises(ValidationError):
            LoanService.create_facility(
                company=self.company,
                user=self.admin,
                data={
                    "bank_account": self.ba,
                    "facility_code": "OD-OVER",
                    "facility_name": "Excess OD",
                    "facility_type": BankFacility.FacilityType.OVERDRAFT,
                    "sanction_date": date(2026, 11, 1),
                    "maturity_date": date(2027, 11, 1),
                    "sanctioned_limit": Decimal("2000000.00"),
                },
            )

        tl = LoanService.create_facility(
            company=self.company,
            user=self.admin,
            data={
                "bank_account": self.ba,
                "project": self.project,
                "facility_code": "TL-01",
                "facility_name": "Equipment Term Loan",
                "facility_type": BankFacility.FacilityType.TERM_LOAN,
                "sanction_date": date(2026, 11, 1),
                "maturity_date": date(2027, 11, 1),
                "sanctioned_limit": Decimal("1200000.00"),
                "tenure_months": 12,
                "moratorium_months": 2,
                "schedule_method": BankFacility.ScheduleMethod.EQUAL_PRINCIPAL,
            },
        )
        LoanService.disburse_loan(
            facility=tl, user=self.admin, disbursement_date=date(2026, 11, 2), amount=Decimal("1200000.00")
        )
        self.assertEqual(tl.schedule.count(), 12)
        self.assertEqual(tl.schedule.first().principal_due, Decimal("0.00"))  # Moratorium month 1

        cc = LoanService.create_facility(
            company=self.company,
            user=self.admin,
            data={
                "bank_account": self.ba,
                "facility_code": "CC-01",
                "facility_name": "Working Capital CC",
                "facility_type": BankFacility.FacilityType.CASH_CREDIT,
                "sanction_date": date(2026, 11, 1),
                "maturity_date": date(2027, 11, 1),
                "sanctioned_limit": Decimal("1000000.00"),
            },
        )
        dp = LoanService.assess_drawing_power(
            facility=cc, assessment_date=date(2026, 11, 15), eligible_stock=Decimal("800000.00"), eligible_receivables=Decimal("400000.00")
        )
        # 800k * 75% (25% NRB haircut) + 400k * 70% (30% rec haircut) = 600k + 280k = 880k
        self.assertEqual(dp.computed_drawing_power, Decimal("880000.00"))

        bg = LoanService.issue_bank_guarantee(
            company=self.company,
            user=self.admin,
            data={
                "bank_account": self.ba,
                "project": self.project,
                "bg_number": "BG-99",
                "bg_type": BankGuarantee.BGType.PERFORMANCE,
                "beneficiary": "Client Authority",
                "amount": Decimal("500000.00"),
                "margin_percent": Decimal("10.00"),
                "commission_amount": Decimal("5000.00"),
                "issue_date": date(2026, 11, 5),
                "expiry_date": date(2027, 11, 5),
            },
        )
        self.assertEqual(bg.margin_amount, Decimal("50000.00"))
        LoanService.invoke_bank_guarantee(bg=bg, user=self.admin, invocation_date=date(2026, 11, 25))
        bg.refresh_from_db()
        self.assertEqual(bg.status, BankGuarantee.Status.INVOKED)

        # Trial Balance & Balance Sheet remain balanced after all FX, Loan, BG & Bank postings!
        tb = ReportingService.get_trial_balance(company=self.company)
        bs = ReportingService.get_balance_sheet(company=self.company)
        self.assertTrue(tb["is_balanced"])
        self.assertTrue(bs["is_balanced"])

        # Treasury overview & PDF/Excel exports work via API
        client = APIClient()
        client.force_authenticate(user=self.admin)
        headers = {"HTTP_X_COMPANY_ID": str(self.company.id)}
        self.assertEqual(client.get("/api/v1/dashboard/treasury/", **headers).status_code, 200)
        self.assertEqual(client.get(f"/api/v1/banking/bank-accounts/{self.ba.id}/export/?ext=pdf", **headers).status_code, 200)
        self.assertEqual(client.get(f"/api/v1/banking/bank-accounts/{self.ba.id}/export/?ext=xlsx", **headers).status_code, 200)
