"""
CA Automator — UAE-specific calculation engines.

UAE Corporate Tax needs no engine of its own: it's the same marginal-slab
mechanic as engines.personal_tax(), just with status='company' and a
2-slab rate_master seed (0% to AED 375,000, 9% above) — see the
`uae_corporate_tax` lambda in engines.ENGINES. VAT needs no engine either:
engines.vat_return() only ever reads `vat.standard_rate` from rate_master,
which is exactly the UAE VAT Decree-Law's shape (a single 5% standard rate,
zero-rated/exempt/blocked-input mechanics all already modelled) — see
seed.sql's UAE section.

This module is for the one UAE mechanic that genuinely needs its own code:
administrative penalties under Cabinet Decision 49/2021 (as amended by
108/2021's 2022 late-payment revision) — a fixed-AED-figure / capped-
percentage regime, structurally nothing like Nepal's Sec 117-120 instalment
interest or India's Sec 234A/B/C/F, so it doesn't fit engines.penalty() or
india_engines.india_interest_penalty() at all.

Same design rule as engines.py/india_engines.py: no statutory number is
hard-coded here — every figure is read from rate_master (domain='penalty',
country='AE' via the ambient country_service context) and every UNVERIFIED
code is surfaced back to the caller, never silently trusted. This is a
reasonable, defensible core model, not a filing-ready implementation of UAE
tax law, and has not been reviewed by a qualified UAE tax professional.
"""
from db import rate_dict

R2 = lambda x: round(float(x or 0), 2)


def _val(rates, code, default=None):
    r = rates.get(code)
    if not r:
        return default
    return r["value_num"] if r["value_num"] is not None else default


def uae_penalties(fy, data):
    """
    Federal Tax Authority administrative penalties (Cabinet Decision
    49/2021, late-payment mechanics as revised by 108/2021 effective
    1 Jan 2022).

    data: {
      late_registration: bool,
      late_deregistration: bool,               flat fee, does NOT repeat monthly
        (Cabinet Decision 49/2021 Sch. 1 sets this as a single AED 1,000 fee,
        unlike the pre-108/2021 monthly-repeating version some older
        summaries still describe),
      late_return_filed: bool, late_return_is_repeat: bool (a repeat
        violation within 24 months of the last one),
      records_not_kept: bool, records_repeat_violation: bool,
      unpaid_tax: the tax still outstanding after its due date,
      months_since_due_date: whole months elapsed since the due date (0 =
        still within the due date, so no late-payment penalty at all),
    }

    Late-payment penalty (108/2021, in force from 1 Jan 2022): 2% of unpaid
    tax on the day after the due date, then a further 4% on the same day
    one month later and every month after that for as long as tax remains
    outstanding — capped in total at 300% of the unpaid tax.
    """
    rates, unverified = rate_dict("penalty", fy)
    lines = []

    def add(head, basis, amount):
        if amount:
            lines.append({"head": head, "basis": basis, "amount": R2(amount)})

    if data.get("late_registration"):
        add("Late VAT registration", "Flat fee", _val(rates, "late_registration_fee", 0) or 0)

    if data.get("late_deregistration"):
        add("Late VAT deregistration", "Flat fee", _val(rates, "late_deregistration_fee", 0) or 0)

    if data.get("late_return_filed"):
        fee_code = "late_return_fee_repeat" if data.get("late_return_is_repeat") else "late_return_fee_first"
        head = "Late return filing" + (" (repeat within 24 months)" if data.get("late_return_is_repeat") else " (first occurrence)")
        add(head, "Flat fee", _val(rates, fee_code, 0) or 0)

    if data.get("records_not_kept"):
        fee_code = "record_keeping_fee_repeat" if data.get("records_repeat_violation") else "record_keeping_fee_first"
        head = "Failure to keep required records" + (" (repeat)" if data.get("records_repeat_violation") else " (first occurrence)")
        add(head, "Flat fee", _val(rates, fee_code, 0) or 0)

    unpaid_tax = float(data.get("unpaid_tax", 0) or 0)
    months_late = max(0, int(data.get("months_since_due_date", 0) or 0))
    if unpaid_tax > 0 and months_late > 0:
        immediate_pct = _val(rates, "late_payment_immediate_pct", 0) or 0
        monthly_pct = _val(rates, "late_payment_monthly_pct", 0) or 0
        cap_pct = _val(rates, "late_payment_cap_pct", 0) or 0
        # The 2% immediate charge applies once the due date has passed; the
        # 4%/month charge starts one month after that and repeats every
        # month tax remains unpaid — so a firm 1 month late owes 2% + 4%
        # (one monthly charge), 2 months late owes 2% + 8%, and so on.
        monthly_charges = months_late
        raw_pct = immediate_pct + monthly_pct * monthly_charges
        applied_pct = min(raw_pct, cap_pct) if cap_pct else raw_pct
        amount = unpaid_tax * applied_pct
        add("Late payment of tax", f"{unpaid_tax:,.2f} unpaid x {applied_pct * 100:.0f}%"
            f" ({immediate_pct * 100:.0f}% immediate + {monthly_pct * 100:.0f}%/month x {monthly_charges} month(s)"
            + (f", capped at {cap_pct * 100:.0f}%" if cap_pct and raw_pct > cap_pct else "") + ")", amount)

    return {"lines": lines, "total": R2(sum(l["amount"] for l in lines)), "unverified": unverified}
