"""
Plan feature gating for ModuleDesk.

Defines what each plan tier includes and exposes check functions that
routes and services call before allowing gated operations.

Plan values (stored in public.organizations.plan):
  internal  — platform owner: unlimited everything, no billing
  free      — up to 2 modules, 20 AI credits/month, basic features only
  basic     — unlimited modules, 200 AI credits/month, full inbox + AI
  pro       — unlimited modules, 1000 AI credits/month (or BYOK), all features
"""

from __future__ import annotations

from typing import Optional, TYPE_CHECKING

if TYPE_CHECKING:
    from ..public_models import Organization


# ── Limits ────────────────────────────────────────────────────────────────────

PLAN_LIMITS: dict[str, dict] = {
    "internal": {
        "module_limit": None,       # unlimited
        "ai_credits": None,         # unlimited
        "template_limit": None,     # unlimited
    },
    "free": {
        "module_limit": 2,
        "ai_credits": 20,
        "template_limit": 5,
    },
    "basic": {
        "module_limit": None,
        "ai_credits": 200,
        "template_limit": None,
    },
    "pro": {
        "module_limit": None,
        "ai_credits": None,         # unlimited / BYOK
        "template_limit": None,
    },
}

# ── Feature flags per plan ────────────────────────────────────────────────────

PLAN_FEATURES: dict[str, dict[str, bool]] = {
    "internal": {
        "order_sync": True, "analytics": True, "vip_badges": True,
        "tl_dr": True, "ai_badge": True, "topic_segmentation": True,
        "website_indicator": True, "url_safety": True, "next_ticket": True,
        "wysiwyg": True, "signature": True, "attachments": True, "product_link": True,
        "ai_classify": True, "ai_draft": True, "ai_summarize": True,
        "ai_translate": True, "rag": True, "generated_guides": True,
        "doc_scraping": True, "semantic_search": True,
        "website_checks": True, "credentials": True,
    },
    "free": {
        "order_sync": False, "analytics": False, "vip_badges": False,
        "tl_dr": False, "ai_badge": False, "topic_segmentation": False,
        "website_indicator": False, "url_safety": False, "next_ticket": False,
        "wysiwyg": False, "signature": False, "attachments": False, "product_link": False,
        "ai_classify": False, "ai_draft": False, "ai_summarize": False,
        "ai_translate": False, "rag": False, "generated_guides": False,
        "doc_scraping": False, "semantic_search": False,
        "website_checks": False, "credentials": False,
    },
    "basic": {
        "order_sync": True, "analytics": True, "vip_badges": True,
        "tl_dr": True, "ai_badge": True, "topic_segmentation": True,
        "website_indicator": True, "url_safety": True, "next_ticket": True,
        "wysiwyg": True, "signature": True, "attachments": True, "product_link": True,
        "ai_classify": True, "ai_draft": True, "ai_summarize": True,
        "ai_translate": False, "rag": False, "generated_guides": False,
        "doc_scraping": False, "semantic_search": False,
        "website_checks": False, "credentials": False,
    },
    "pro": {
        "order_sync": True, "analytics": True, "vip_badges": True,
        "tl_dr": True, "ai_badge": True, "topic_segmentation": True,
        "website_indicator": True, "url_safety": True, "next_ticket": True,
        "wysiwyg": True, "signature": True, "attachments": True, "product_link": True,
        "ai_classify": True, "ai_draft": True, "ai_summarize": True,
        "ai_translate": True, "rag": True, "generated_guides": True,
        "doc_scraping": True, "semantic_search": True,
        "website_checks": True, "credentials": True,
    },
}

# Price per module in euro cents (for display purposes)
PLAN_PRICE_CENTS: dict[str, int] = {
    "internal": 0,
    "free": 0,
    "basic": 600,   # €6
    "pro": 1200,    # €12
}


# ── Check functions ───────────────────────────────────────────────────────────

def get_plan(org: "Organization") -> str:
    return org.plan if org.plan in PLAN_LIMITS else "free"


def check_feature(org: "Organization", feature: str) -> bool:
    """Return True if the org's plan includes the named feature."""
    plan = get_plan(org)
    return PLAN_FEATURES.get(plan, {}).get(feature, False)


def check_ai_credits(org: "Organization") -> bool:
    """Return True if the org has AI credits remaining (or unlimited)."""
    plan = get_plan(org)
    limit = PLAN_LIMITS[plan]["ai_credits"]
    if limit is None:
        return True     # unlimited (internal or BYOK)
    return org.ai_credits_used < limit


def get_module_limit(org: "Organization") -> Optional[int]:
    """Return the module limit for this org's plan, or None if unlimited."""
    plan = get_plan(org)
    return PLAN_LIMITS[plan]["module_limit"]


def get_template_limit(org: "Organization") -> Optional[int]:
    """Return the predefined message template limit, or None if unlimited."""
    plan = get_plan(org)
    return PLAN_LIMITS[plan]["template_limit"]


def get_ai_credit_limit(org: "Organization") -> Optional[int]:
    """Return monthly AI credit limit, or None if unlimited."""
    plan = get_plan(org)
    return PLAN_LIMITS[plan]["ai_credits"]


def is_byok(org: "Organization") -> bool:
    """Return True if the org has a BYOK OpenAI key configured."""
    return bool(org.openai_api_key_encrypted)
