import base64
import hashlib
import hmac
import os
import struct
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import date
from decimal import Decimal
from unittest.mock import patch

from django.conf import settings
from django.core.management import call_command
from django.db import IntegrityError, close_old_connections
from django.test import TransactionTestCase
from django.utils import timezone
from rest_framework.test import APIClient

from apps.accounting.models import Account, LedgerEntry, Voucher, VoucherLine
from apps.accounting.services.core import PostingService
from apps.accounts_rbac.models import CompanyMembership, Role, User
from apps.banking.models import Bank, BankAccount, BankBranch, ChequeBook, ChequeLeaf
from apps.system_admin.models import InstallationSession
from apps.system_admin.mysql_concurrency import run_with_deadlock_retry, verify_mysql_production_posture
from apps.tenancy.models import Company, FiscalYear


def _totp_from_base32(secret: str, ts: float | None = None) -> str:
    padded = secret.upper() + "=" * ((8 - len(secret) % 8) % 8)
    key = base64.b32decode(padded)
    counter = int((ts or time.time()) // 30)
    msg = struct.pack(">Q", counter)
    digest = hmac.new(key, msg, hashlib.sha1).digest()
    offset = digest[-1] & 0x0F
    code = (struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF) % 1_000_000
    return f"{code:06d}"


class MySQLProductionArchitectureTests(TransactionTestCase):
    """Verifies authoritative MySQL InnoDB/utf8mb4/strict/READ-COMMITTED posture and constraints."""

    def test_mysql_engine_and_innodb_posture(self):
        self.assertIn("mysql", settings.DATABASES["default"]["ENGINE"])
        posture = verify_mysql_production_posture()
        self.assertTrue(posture["connected"])
        self.assertTrue(posture["all_innodb_ok"], f"Non-InnoDB tables detected: {posture}")
        self.assertTrue(posture["strict_mode_ok"], f"Strict SQL mode missing: {posture}")
        self.assertTrue(posture["read_committed_ok"], f"READ-COMMITTED missing: {posture}")
        self.assertTrue(posture["utf8mb4_ok"], f"utf8mb4 charset missing: {posture}")

    def test_cheque_leaf_mysql_uniqueness_without_partial_index(self):
        company = Company.objects.create(code="TST-CHQ", name="Test Infra Ltd")
        cash_acc = Account.objects.create(company=company, code="1025", name="NIC Asia Bank", account_type="ASSET")
        bank_inst = Bank.objects.create(company=company, name="NIC Asia Bank", short_code="NICA")
        bank_branch = BankBranch.objects.create(bank=bank_inst, branch_code="KTM-01", name="Kathmandu Main")
        bank = BankAccount.objects.create(
            company=company,
            bank_branch=bank_branch,
            account_name="Operating",
            account_number_masked="****8901",
            account_number_encrypted="enc_demo_012345678901",
            account_number_hash=hashlib.sha256(b"012345678901").hexdigest(),
            gl_account=cash_acc,
        )
        book = ChequeBook.objects.create(
            company=company,
            bank_account=bank,
            book_code="BK-01",
            start_number=1001,
            end_number=1010,
            issued_date=date(2026, 8, 1),
        )
        # Multiple RECEIVED leaves with issued_unique_key=None coexist cleanly without NULL collisions
        r1 = ChequeLeaf.objects.create(
            company=company, bank_account=bank, cheque_book=book, cheque_number="99001", direction="RECEIVED"
        )
        r2 = ChequeLeaf.objects.create(
            company=company, bank_account=bank, cheque_book=book, cheque_number="99002", direction="RECEIVED"
        )
        self.assertIsNone(r1.issued_unique_key)
        self.assertIsNone(r2.issued_unique_key)

        # Duplicate ISSUED cheque leaf (1001 vs 01001) on same company & bank account rejected by MySQL unique index
        ChequeLeaf.objects.create(
            company=company, bank_account=bank, cheque_book=book, cheque_number="1001", direction="ISSUED"
        )
        with self.assertRaises(IntegrityError):
            ChequeLeaf.objects.create(
                company=company, bank_account=bank, cheque_book=book, cheque_number="01001", direction="ISSUED"
            )

    def test_concurrent_voucher_posting_balanced_under_mysql_read_committed(self):
        user = User.objects.create_user(username="acc_thread_mgr", email="mgr@maya.local", password="StrongPassword!9988")
        company = Company.objects.create(code="CONC-01", name="Concurrency Civil Ltd")
        fy = FiscalYear.resolve_from_bs_year(company=company, bs_start_year=2083, name="2083/84")
        fy.is_current = True
        fy.save(update_fields=["is_current"])
        fy.generate_nepal_periods(2083)
        period = fy.periods.order_by("start_date").first()

        dr_acc = Account.objects.create(company=company, code="5011", name="Cement Material Expense", account_type="EXPENSE")
        cr_acc = Account.objects.create(company=company, code="1021", name="Everest Operating Bank", account_type="ASSET")

        vouchers = []
        for idx in range(6):
            v = Voucher.objects.create(
                company=company,
                fiscal_year=fy,
                fiscal_period=period,
                voucher_type=Voucher.VoucherType.PAYMENT,
                voucher_date=fy.start_date,
                bs_date="2083-04-05",
                status=Voucher.Status.APPROVED,
                narration=f"Concurrent contractor payout #{idx + 1}",
                created_by=user,
                approved_by=user,
            )
            VoucherLine.objects.create(voucher=v, line_no=1, account=dr_acc, debit=Decimal("2500.00"), credit=Decimal("0.00"))
            VoucherLine.objects.create(voucher=v, line_no=2, account=cr_acc, debit=Decimal("0.00"), credit=Decimal("2500.00"))
            vouchers.append(v)

        def worker(v_obj):
            close_old_connections()
            try:
                return run_with_deadlock_retry(PostingService.post_voucher, voucher=v_obj, user=user)
            finally:
                close_old_connections()

        with ThreadPoolExecutor(max_workers=4) as pool:
            results = list(pool.map(worker, vouchers))

        self.assertEqual(len(results), 6)
        voucher_nos = [Voucher.objects.get(pk=r.pk).voucher_no for r in results]
        self.assertEqual(len(set(voucher_nos)), 6, f"Expected 6 distinct sequential voucher numbers, got {voucher_nos}")
        entries = LedgerEntry.objects.filter(company=company)
        self.assertEqual(entries.count(), 12)
        total_dr = sum(e.debit for e in entries)
        total_cr = sum(e.credit for e in entries)
        self.assertEqual(total_dr, Decimal("15000.00"))
        self.assertEqual(total_dr, total_cr)


class BootstrapAndSecurityHardeningTests(TransactionTestCase):
    """Tests cryptographic bootstrap, zero fake data guarantee, MFA, lock, and tenant isolation."""

    def test_cryptographic_bootstrap_locks_permanently_and_enforces_no_demo_data(self):
        client = APIClient()
        token = "prod-bootstrap-secret-token-xyz-2026"

        with patch.dict(os.environ, {"BOOTSTRAP_SETUP_TOKEN": token}):
            st = client.get("/api/v1/bootstrap/status/")
            self.assertEqual(st.status_code, 200)
            self.assertTrue(st.data["bootstrap_allowed"])
            self.assertFalse(st.data["initialized"])

            # Invalid token rejected
            bad_tok = client.post(
                "/api/v1/bootstrap/init-superadmin/",
                {
                    "setup_token": "wrong-token",
                    "username": "erp_director",
                    "email": "dir@himalayan.com.np",
                    "password": "VeryStrongPassword!2026",
                },
                format="json",
            )
            self.assertEqual(bad_tok.status_code, 403)

            # Default weak usernames prohibited
            bad_user = client.post(
                "/api/v1/bootstrap/init-superadmin/",
                {
                    "setup_token": token,
                    "username": "admin",
                    "email": "admin@himalayan.com.np",
                    "password": "VeryStrongPassword!2026",
                },
                format="json",
            )
            self.assertEqual(bad_user.status_code, 400)

            # Valid bootstrap succeeds and creates zero fake companies/vouchers
            ok = client.post(
                "/api/v1/bootstrap/init-superadmin/",
                {
                    "setup_token": token,
                    "username": "erp_director",
                    "email": "dir@himalayan.com.np",
                    "full_name": "Chief Financial Director",
                    "password": "VeryStrongPassword!2026",
                },
                format="json",
            )
            self.assertEqual(ok.status_code, 201, ok.data)
            self.assertIn("mfa_setup", ok.data)
            secret = ok.data["mfa_setup"]["secret"]
            self.assertEqual(Company.objects.count(), 0)
            self.assertEqual(Voucher.objects.count(), 0)

            # Confirm MFA via live TOTP
            totp = _totp_from_base32(secret)
            mfa_res = client.post("/api/v1/bootstrap/confirm-mfa/", {"totp_code": totp}, format="json")
            self.assertEqual(mfa_res.status_code, 200)
            self.assertTrue(mfa_res.data["mfa_verified"])

            # Re-calling bootstrap endpoint is permanently blocked
            replay = client.post(
                "/api/v1/bootstrap/init-superadmin/",
                {
                    "setup_token": token,
                    "username": "rogue_admin",
                    "email": "rogue@example.com",
                    "password": "AnotherStrongPassword!2026",
                },
                format="json",
            )
            self.assertEqual(replay.status_code, 403)

            # Complete Setup Wizard company provisioning + final installer lock
            wiz_co = client.post(
                "/api/v1/admin/install/wizard/",
                {
                    "step": 6,
                    "payload": {
                        "create_company": True,
                        "company_code": "HIM-01",
                        "company_name": "Himalayan Civil Works Pvt. Ltd.",
                        "pan_vat_no": "601234567",
                        "fiscal_year_name": "2083/84",
                        "bs_start_year": 2083,
                    },
                },
                format="json",
            )
            self.assertEqual(wiz_co.status_code, 200)
            self.assertEqual(Company.objects.count(), 1)
            self.assertEqual(Voucher.objects.count(), 0)

            lock_res = client.post("/api/v1/admin/install/wizard/", {"step": 13, "finalize": True}, format="json")
            self.assertEqual(lock_res.status_code, 200)
            self.assertEqual(InstallationSession.objects.first().status, InstallationSession.Status.LOCKED)

    def test_cross_company_idor_and_privilege_escalation_blocked(self):
        co_a = Company.objects.create(code="CO-A", name="Company Alpha")
        co_b = Company.objects.create(code="CO-B", name="Company Beta")
        Account.objects.create(company=co_b, code="9991", name="Secret Beta Treasury", account_type="ASSET")

        staff_role, _ = Role.objects.get_or_create(
            code="SITE_CLERK",
            defaults={"name": "Site Clerk", "permissions": ["accounting.voucher.view"], "is_system": True},
        )
        user_a = User.objects.create_user(username="alpha_clerk", email="a@maya.local", password="StrongPassword!1234")
        m = CompanyMembership.objects.create(user=user_a, company=co_a, role=staff_role, is_default=True, is_active=True)
        m.roles.add(staff_role)

        c = APIClient()
        c.force_authenticate(user=user_a)

        # Attempt to escalate into Installation Wizard or Company Beta ledger via forged X-Company-ID
        admin_probe = c.get("/api/v1/admin/install/wizard/")
        self.assertEqual(admin_probe.status_code, 403)

        idor_probe = c.get("/api/v1/accounts/", HTTP_X_COMPANY_ID=str(co_b.id))
        self.assertIn(idor_probe.status_code, (403, 404, 200))
        if idor_probe.status_code == 200:
            rows = idor_probe.data.get("results", idor_probe.data)
            self.assertFalse(any(r.get("code") == "9991" for r in rows))

    def test_cli_bootstrap_superadmin_command(self):
        call_command(
            "bootstrap_superadmin",
            username="cli_director",
            email="cli@maya.local",
            full_name="CLI Director",
            password="EnterpriseStrongPassword!99",
        )
        u = User.objects.get(username="cli_director")
        self.assertTrue(u.is_superuser)
        self.assertEqual(Voucher.objects.count(), 0)

