"""
Лимиты тарифа по плану подписки.
Используется для проверки: CRM-интеграции, шаблоны, срок хранения истории.
"""
from typing import Any

from sqlalchemy.orm import Session

from app.db.models import Subscription, Plan


# Лимиты по имени плана (если в plan.features нет crm_count/templates)
# custom_bot_allowed: True на всех тарифах — MTProto и кастомный бот доступны всем
_DEFAULT_LIMITS = {
    "free": {"crm_count": 1, "templates_limit": 0, "history_days": 1, "custom_bot_allowed": True},
    "start lite": {"crm_count": 1, "templates_limit": 2, "history_days": 7, "custom_bot_allowed": True},
    "start": {"crm_count": 1, "templates_limit": 2, "history_days": 7, "custom_bot_allowed": True},
    "basic": {"crm_count": 1, "templates_limit": None, "history_days": 30, "custom_bot_allowed": True},
    "pro": {"crm_count": 3, "templates_limit": None, "history_days": 90, "custom_bot_allowed": True},
    "business": {"crm_count": -1, "templates_limit": None, "history_days": 90, "custom_bot_allowed": True},
    "enterprise": {"crm_count": -1, "templates_limit": None, "history_days": 365, "custom_bot_allowed": True},
    "starter": {"crm_count": 1, "templates_limit": 5, "history_days": 30, "custom_bot_allowed": True},
    "professional": {"crm_count": 3, "templates_limit": 20, "history_days": 90, "custom_bot_allowed": True},
}


def get_plan_limits(db: Session, tenant_id: int) -> dict[str, Any]:
    """
    Возвращает лимиты тарифа для тенанта: crm_count, templates_limit, history_days.
    - crm_count: макс. число CRM-интеграций (-1 = без лимита)
    - templates_limit: макс. шаблонов (None = без лимита)
    - history_days: сколько дней хранить/показывать историю уведомлений
    - custom_bot_allowed: разрешён ли кастомный Telegram-бот (brand bot / MTProto)
    """
    subscription = (
        db.query(Subscription)
        .filter(
            Subscription.tenant_id == tenant_id,
            Subscription.status == "active",
        )
        .first()
    )
    if not subscription or not subscription.plan:
        return {"crm_count": 1, "templates_limit": 0, "history_days": 1, "custom_bot_allowed": True}

    plan = subscription.plan
    features = plan.features or {}
    name = (plan.name or "").strip().lower()

    crm_count = features.get("crm_count")
    if crm_count is None:
        for key, limits in _DEFAULT_LIMITS.items():
            if key in name:
                crm_count = limits["crm_count"]
                break
        if crm_count is None:
            crm_count = 1

    templates_limit = features.get("templates")
    if templates_limit is None:
        name_matched = False
        for key, limits in _DEFAULT_LIMITS.items():
            if key in name:
                templates_limit = limits["templates_limit"]
                name_matched = True
                break
        if not name_matched:
            templates_limit = 5
    if templates_limit == "unlimited":
        templates_limit = None

    history_days = features.get("history_days")
    if history_days is None:
        for key, limits in _DEFAULT_LIMITS.items():
            if key in name:
                history_days = limits["history_days"]
                break
        if history_days is None:
            history_days = 30

    custom_bot_allowed = features.get("custom_bot_allowed")
    if custom_bot_allowed is None:
        for key, limits in _DEFAULT_LIMITS.items():
            if key in name:
                custom_bot_allowed = limits.get("custom_bot_allowed", True)
                break
        if custom_bot_allowed is None:
            custom_bot_allowed = True

    return {
        "crm_count": int(crm_count) if crm_count is not None else 1,
        "templates_limit": int(templates_limit) if templates_limit is not None else None,
        "history_days": int(history_days),
        "custom_bot_allowed": bool(custom_bot_allowed),
    }
