from __future__ import annotations

from decimal import Decimal, ROUND_HALF_UP
from typing import Any

LIFETIME = "Lifetime"


def normalize_discount_percent(value: Any) -> int:
    try:
        pct = int(str(value).strip())
    except Exception:
        pct = 0
    return max(0, min(100, pct))


def discounted_amount(base_amount: Any, discount_percent: Any) -> int:
    try:
        base = Decimal(str(base_amount).replace(",", "").strip())
    except Exception:
        base = Decimal("0")
    if base < 0:
        base = Decimal("0")
    pct = Decimal(normalize_discount_percent(discount_percent))
    final = base * (Decimal("100") - pct) / Decimal("100")
    return max(0, int(final.quantize(Decimal("1"), rounding=ROUND_HALF_UP)))


def normalize_bulk_expiry(expiry: Any, lifetime: Any = False) -> str:
    lifetime_flag = lifetime is True or str(lifetime or "").strip().lower() in {
        "1", "true", "yes", "on", "lifetime"
    }
    if lifetime_flag:
        return LIFETIME
    return str(expiry or "").strip()


def is_lifetime_expiry(expiry: Any) -> bool:
    raw = str(expiry or "").strip().lower()
    return not raw or raw in {"lifetime", "life time", "never", "permanent"}


def expiry_label(expiry: Any) -> str:
    return LIFETIME if is_lifetime_expiry(expiry) else str(expiry).strip()


def normalize_bulk_quantity(value: Any, minimum: int = 5, maximum: int = 10000) -> int:
    try:
        qty = int(str(value).strip())
    except Exception:
        qty = minimum
    return max(minimum, min(maximum, qty))


def bulk_order_summary(unit_price: Any, quantity: Any, discount_percent: Any) -> dict[str, int]:
    qty = normalize_bulk_quantity(quantity)
    try:
        unit = int(Decimal(str(unit_price).replace(",", "").strip()).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
    except Exception:
        unit = 0
    unit = max(0, unit)
    subtotal = unit * qty
    pct = normalize_discount_percent(discount_percent)
    final = discounted_amount(subtotal, pct)
    return {
        "quantity": qty,
        "unit_price": unit,
        "subtotal": subtotal,
        "discount_percent": pct,
        "discount_amount": max(0, subtotal - final),
        "final_amount": final,
    }
