"""
Unit tests for server/uae_engines.py, plus the uae_corporate_tax lambda in
server/engines.py's ENGINES dict (personal_tax() reused with status='company',
no dedicated function of its own — see engines.py's own comment there).

Run with: cd server && ../venv/bin/python3 -m unittest tests.test_uae_engines -v
"""
import os
import sys
import tempfile
import unittest

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))


class UaeEnginesTests(unittest.TestCase):
    def setUp(self):
        self._tmpdir = tempfile.mkdtemp()
        os.environ["CA_DATA_DIR"] = self._tmpdir
        for mod in ("db", "country_service", "engines", "uae_engines", "india_engines"):
            sys.modules.pop(mod, None)
        import db as db_mod
        import country_service as cs_mod
        import engines as eng_mod
        import uae_engines as ue_mod
        global db, cs, eng, ue
        db, cs, eng, ue = db_mod, cs_mod, eng_mod, ue_mod
        db.init_db()
        self.fy = db.current_fy_label()

    # --------------------------------------------------------- corporate tax

    def test_income_within_zero_band_owes_nothing(self):
        with cs.use_country("AE"):
            result = eng.personal_tax(self.fy, "company", 300000)
        self.assertEqual(result["tax_payable"], 0.0)

    def test_income_above_threshold_taxed_at_nine_percent_on_the_excess(self):
        with cs.use_country("AE"):
            result = eng.personal_tax(self.fy, "company", 500000)
        # 375,000 @ 0% + 125,000 @ 9% = 11,250
        self.assertEqual(result["tax_payable"], 11250.0)

    def test_uae_corporate_tax_reachable_via_the_compute_registry(self):
        with cs.use_country("AE"):
            result = eng.compute("uae_corporate_tax", self.fy, {"taxable_income": 500000})
        self.assertEqual(result["tax_payable"], 11250.0)

    def test_no_female_rebate_leaks_into_a_company_computation(self):
        with cs.use_country("AE"):
            result = eng.personal_tax(self.fy, "company", 500000, {"is_resident_woman": True})
        self.assertEqual(result["rebate"], 0.0)

    # ----------------------------------------------------------- penalties

    def test_no_triggers_gives_zero_penalty(self):
        with cs.use_country("AE"):
            result = ue.uae_penalties(self.fy, {})
        self.assertEqual(result["total"], 0.0)
        self.assertEqual(result["lines"], [])

    def test_late_registration_flat_fee(self):
        with cs.use_country("AE"):
            result = ue.uae_penalties(self.fy, {"late_registration": True})
        self.assertEqual(result["total"], 10000.0)

    def test_late_return_first_vs_repeat(self):
        with cs.use_country("AE"):
            first = ue.uae_penalties(self.fy, {"late_return_filed": True})
            repeat = ue.uae_penalties(self.fy, {"late_return_filed": True, "late_return_is_repeat": True})
        self.assertEqual(first["total"], 1000.0)
        self.assertEqual(repeat["total"], 2000.0)

    def test_record_keeping_first_vs_repeat(self):
        with cs.use_country("AE"):
            first = ue.uae_penalties(self.fy, {"records_not_kept": True})
            repeat = ue.uae_penalties(self.fy, {"records_not_kept": True, "records_repeat_violation": True})
        self.assertEqual(first["total"], 10000.0)
        self.assertEqual(repeat["total"], 50000.0)

    def test_late_payment_combines_immediate_and_monthly_charges(self):
        with cs.use_country("AE"):
            result = ue.uae_penalties(self.fy, {"unpaid_tax": 100000, "months_since_due_date": 2})
        # 2% immediate + 4% x 2 months = 10% of 100,000 = 10,000
        self.assertEqual(result["total"], 10000.0)

    def test_late_payment_capped_at_300_percent(self):
        with cs.use_country("AE"):
            result = ue.uae_penalties(self.fy, {"unpaid_tax": 100000, "months_since_due_date": 80})
        # raw would be 2% + 4%*80 = 322%, capped at 300%
        self.assertEqual(result["total"], 300000.0)

    def test_zero_months_since_due_date_means_no_late_payment_penalty(self):
        with cs.use_country("AE"):
            result = ue.uae_penalties(self.fy, {"unpaid_tax": 100000, "months_since_due_date": 0})
        self.assertEqual(result["total"], 0.0)

    def test_multiple_triggers_combine_into_one_total(self):
        with cs.use_country("AE"):
            result = ue.uae_penalties(self.fy, {
                "late_registration": True, "records_not_kept": True,
                "unpaid_tax": 100000, "months_since_due_date": 1,
            })
        # 10,000 + 10,000 + (2% + 4%) x 100,000 = 10,000 + 10,000 + 6,000
        self.assertEqual(result["total"], 26000.0)
        self.assertEqual(len(result["lines"]), 3)

    def test_uae_penalties_reachable_via_the_compute_registry(self):
        with cs.use_country("AE"):
            result = eng.compute("uae_penalties", self.fy, {"late_registration": True})
        self.assertEqual(result["total"], 10000.0)

    # ------------------------------------------------- shared VAT reuse (AE)

    def test_vat_return_reuses_the_shared_engine_with_the_uae_rate(self):
        with cs.use_country("AE"):
            result = eng.vat_return(self.fy, {"sales": [{"taxable_amount": 100000}]})
        self.assertEqual(result["rate"], 5.0)  # 5% standard rate, expressed as a percent
        self.assertEqual(result["totals"]["output_vat"], 5000.0)
