"""Fee resolution against effective-dated schedules (V2 §7.3)."""

from __future__ import annotations

from decimal import ROUND_HALF_UP, Decimal

from django.db.models import Q
from django.utils import timezone

from .models import FeeSchedule


def active_schedule(at=None) -> FeeSchedule | None:
    at = at or timezone.now()
    return (
        FeeSchedule.objects.filter(is_active=True, effective_from__lte=at)
        .filter(Q(effective_to__isnull=True) | Q(effective_to__gte=at))
        .order_by("-effective_from")
        .first()
    )


def compute_fee(amount, at=None) -> Decimal:
    """Return the platform fee for an amount using the active schedule (0 if none)."""
    schedule = active_schedule(at)
    if schedule is None:
        return Decimal("0.00")
    amount = amount if isinstance(amount, Decimal) else Decimal(str(amount))
    fee = (amount * Decimal(schedule.percent_bps) / Decimal(10000)) + schedule.flat_fee
    if fee < schedule.min_fee:
        fee = schedule.min_fee
    if fee > amount:
        fee = amount
    return fee.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)


def seed_default_fee_schedule() -> bool:
    """Create a baseline schedule (2.5%, min 500 TZS) if none exists. Idempotent."""
    if FeeSchedule.objects.exists():
        return False
    FeeSchedule.objects.create(
        name="Default platform fee",
        percent_bps=250,  # 2.5%
        flat_fee=Decimal("0.00"),
        min_fee=Decimal("500.00"),
        currency="TZS",
        effective_from=timezone.now(),
    )
    return True
