"""Country VAT helpers for C2C freight pricing and invoices.

VAT is a fixed amount per pickup/origin country (not a percentage).
"""

from __future__ import annotations

from decimal import Decimal, ROUND_HALF_UP

from core.countries import normalize_country_code

_TWOPLACES = Decimal('0.01')
_ZERO = Decimal('0.00')


def vat_for_country(country_code) -> Decimal:
    """Return active fixed VAT amount for a country, or 0 if missing/inactive."""
    code = normalize_country_code(country_code)
    if not code:
        return _ZERO
    from core.models import CountryVatRate

    row = (
        CountryVatRate.objects
        .filter(country_code=code, is_active=True)
        .only('vat_amount')
        .first()
    )
    if row is None:
        return _ZERO
    return Decimal(row.vat_amount).quantize(_TWOPLACES)


def apply_vat(net: Decimal, vat_amount: Decimal) -> dict:
    """
    Net is ex-VAT. VAT is a fixed amount (not a %).

    Returns vat_amount, total_incl_vat (2 dp).
    """
    net_q = Decimal(net or 0).quantize(_TWOPLACES, rounding=ROUND_HALF_UP)
    vat_q = Decimal(vat_amount or 0).quantize(_TWOPLACES, rounding=ROUND_HALF_UP)
    if vat_q < 0:
        vat_q = _ZERO
    total = (net_q + vat_q).quantize(_TWOPLACES, rounding=ROUND_HALF_UP)
    return {
        'vat_amount': vat_q,
        'total_incl_vat': total,
    }


def vat_fields_for_net(net: Decimal, country_code) -> dict:
    """Convenience: lookup country fixed VAT and add to net."""
    code = normalize_country_code(country_code) or ''
    vat_amount = vat_for_country(code)
    applied = apply_vat(net, vat_amount)
    return {
        'vat_country_code': code or None,
        'vat_amount': str(applied['vat_amount']),
        'total_incl_vat': str(applied['total_incl_vat']),
    }


def zero_vat_fields(net: Decimal | None = None, country_code=None) -> dict:
    net_q = Decimal(net or 0).quantize(_TWOPLACES, rounding=ROUND_HALF_UP) if net is not None else None
    return {
        'vat_country_code': normalize_country_code(country_code) if country_code else None,
        'vat_amount': '0.00',
        'total_incl_vat': str(net_q) if net_q is not None else '0.00',
    }


def shipment_is_c2c(shipment) -> bool:
    if getattr(shipment, 'country_to_country', False):
        return True
    pickup = normalize_country_code(getattr(shipment, 'pickup_country_code', None))
    delivery = normalize_country_code(getattr(shipment, 'delivery_country_code', None))
    return bool(pickup and delivery and pickup != delivery)
