"""Helper functions."""

from datetime import datetime, timezone
from decimal import Decimal


def calculate_trial_days_remaining(trial_end: datetime | str | None) -> int | None:
    """Calculate remaining trial days.

    Args:
        trial_end: Trial end datetime or ISO string

    Returns:
        Number of remaining days, or None if no trial
    """
    if not trial_end:
        return None

    if isinstance(trial_end, str):
        # Parse ISO format string
        trial_end = datetime.fromisoformat(trial_end.replace("Z", "+00:00"))

    # Ensure timezone-aware comparison
    now = datetime.now(timezone.utc)
    if trial_end.tzinfo is None:
        trial_end = trial_end.replace(tzinfo=timezone.utc)

    delta = trial_end - now
    return max(0, delta.days)


def format_currency(
    amount: int | float | Decimal,
    currency: str = "EUR",
    locale: str = "it-IT",
) -> str:
    """Format amount as currency string.

    Args:
        amount: Amount (in cents if int, in units if float/Decimal)
        currency: Currency code (default: EUR)
        locale: Locale for formatting (default: it-IT)

    Returns:
        Formatted currency string

    Example:
        format_currency(34900, "EUR")  # "349,00 EUR"
        format_currency(349.00, "EUR")  # "349,00 EUR"
    """
    # Convert cents to units if integer
    if isinstance(amount, int):
        amount = amount / 100

    # Format with 2 decimal places
    formatted = f"{float(amount):,.2f}"

    # Swap thousand and decimal separators for IT locale
    if locale.startswith("it"):
        formatted = formatted.replace(",", "X").replace(".", ",").replace("X", ".")

    return f"{formatted} {currency.upper()}"


def parse_timestamp(ts: int | str | datetime | None) -> datetime | None:
    """Parse various timestamp formats to datetime.

    Args:
        ts: Unix timestamp (int), ISO string, or datetime

    Returns:
        datetime object or None
    """
    if ts is None:
        return None

    if isinstance(ts, datetime):
        return ts

    if isinstance(ts, int):
        return datetime.fromtimestamp(ts, tz=timezone.utc)

    if isinstance(ts, str):
        return datetime.fromisoformat(ts.replace("Z", "+00:00"))

    return None


def cents_to_decimal(cents: int) -> Decimal:
    """Convert cents to decimal amount.

    Args:
        cents: Amount in cents

    Returns:
        Decimal amount
    """
    return Decimal(cents) / 100


def decimal_to_cents(amount: Decimal | float) -> int:
    """Convert decimal amount to cents.

    Args:
        amount: Decimal amount

    Returns:
        Amount in cents
    """
    return int(Decimal(str(amount)) * 100)
