"""
Centralized tier inference for subscription-based features.

Single source of truth for "what tier is this account?" - all feature gates
should import and use this module rather than implementing their own inference.
"""

from enum import Enum
from typing import Optional


class Tier(str, Enum):
    """Subscription tiers in ascending order of features."""
    FREE = "free"
    PRO = "pro"
    SCALE = "scale"
    UNLEASHED = "unleashed"

    def __ge__(self, other: "Tier") -> bool:
        order = [Tier.FREE, Tier.PRO, Tier.SCALE, Tier.UNLEASHED]
        return order.index(self) >= order.index(other)

    def __gt__(self, other: "Tier") -> bool:
        order = [Tier.FREE, Tier.PRO, Tier.SCALE, Tier.UNLEASHED]
        return order.index(self) > order.index(other)

    def __le__(self, other: "Tier") -> bool:
        order = [Tier.FREE, Tier.PRO, Tier.SCALE, Tier.UNLEASHED]
        return order.index(self) <= order.index(other)

    def __lt__(self, other: "Tier") -> bool:
        order = [Tier.FREE, Tier.PRO, Tier.SCALE, Tier.UNLEASHED]
        return order.index(self) < order.index(other)


def infer_tier(plan_name: Optional[str]) -> Tier:
    """
    Infer tier from plan name (case-insensitive substring match).

    This is the ONLY place tier inference logic should live. All other
    modules should import and use this function.

    Args:
        plan_name: The plan name from the database (e.g., "Pro Monthly", "Scale Annual")

    Returns:
        The inferred Tier enum value
    """
    if not plan_name:
        return Tier.FREE

    name = plan_name.lower()

    # Order matters: check most specific first
    if "unleashed" in name:
        return Tier.UNLEASHED
    if "scale" in name or "enterprise" in name:
        return Tier.SCALE
    if "pro" in name:
        return Tier.PRO

    return Tier.FREE


def is_paid(tier: Tier) -> bool:
    """Check if tier has paid features (Pro or above)."""
    return tier >= Tier.PRO


def has_ai_features(tier: Tier) -> bool:
    """Check if tier has AI-powered features (Pro or above)."""
    return tier >= Tier.PRO


def has_freestyle(tier: Tier) -> bool:
    """Check if tier has freestyle/advanced automation (Scale or above)."""
    return tier >= Tier.SCALE
