"""Subscription plans and their limits.

``-1`` means unlimited. Feature flags (e.g. ``sso``) gate capabilities beyond raw
counts. Plans are code-defined so self-hosters can tune them without a database.
"""

from __future__ import annotations

from dataclasses import dataclass

UNLIMITED = -1


@dataclass(frozen=True)
class Plan:
    name: str
    title: str
    max_agents: int
    max_workflows: int
    max_members: int
    max_runs_per_month: int
    monthly_token_quota: int
    features: frozenset[str]

    def allows(self, feature: str) -> bool:
        return feature in self.features

    def as_dict(self) -> dict:
        return {
            "name": self.name,
            "title": self.title,
            "limits": {
                "max_agents": self.max_agents,
                "max_workflows": self.max_workflows,
                "max_members": self.max_members,
                "max_runs_per_month": self.max_runs_per_month,
                "monthly_token_quota": self.monthly_token_quota,
            },
            "features": sorted(self.features),
        }


PLANS: dict[str, Plan] = {
    "free": Plan(
        name="free",
        title="Free",
        max_agents=3,
        max_workflows=3,
        max_members=3,
        max_runs_per_month=200,
        monthly_token_quota=1_000_000,
        features=frozenset({"core"}),
    ),
    "pro": Plan(
        name="pro",
        title="Pro",
        max_agents=50,
        max_workflows=50,
        max_members=25,
        max_runs_per_month=25_000,
        monthly_token_quota=100_000_000,
        features=frozenset({"core", "sso"}),
    ),
    "enterprise": Plan(
        name="enterprise",
        title="Enterprise",
        max_agents=UNLIMITED,
        max_workflows=UNLIMITED,
        max_members=UNLIMITED,
        max_runs_per_month=UNLIMITED,
        monthly_token_quota=UNLIMITED,
        features=frozenset({"core", "sso", "saml", "priority_support"}),
    ),
}


def get_plan(name: str | None) -> Plan:
    return PLANS.get((name or "free").lower(), PLANS["free"])
