"""LLMHosts tier detection and capability reporting.

Detects which pip extras are installed and reports available features.
- Core tier (~50MB): CLI, proxy, rule-based router, exact cache, TUI
- Smart tier (~150MB): + kNN router, ModernBERT, namespace cache, vCache
- Full tier (~2GB): + PyTorch, FAISS-GPU, Qwen router, vLLM
"""

from __future__ import annotations

import logging

logger = logging.getLogger(__name__)


def detect_tier() -> str:
    """Detect installed pip tier: 'core', 'smart', or 'full'."""
    import importlib.util

    if importlib.util.find_spec("torch") is not None:
        return "full"
    if importlib.util.find_spec("onnxruntime") is not None:
        return "smart"
    return "core"


def get_capabilities(tier: str | None = None) -> dict[str, bool]:
    """Return capabilities map for the given tier."""
    t = tier or detect_tier()
    return {
        # Core features (always available)
        "proxy": True,
        "openai_compat": True,
        "anthropic_compat": True,
        "rule_based_router": True,
        "exact_hash_cache": True,
        "tui_dashboard": True,
        "web_dashboard": True,
        "byok_management": True,
        "cost_tracking": True,
        "audit_logging": True,
        "health_monitoring": True,
        "fallback_chain": True,
        "latency_tracking": True,
        # Smart features
        "knn_router": t in ("smart", "full"),
        "modernbert_router": t in ("smart", "full"),
        "namespace_cache": t in ("smart", "full"),
        "vcache_semantic": t in ("smart", "full"),
        "embedding_pipeline": t in ("smart", "full"),
        # Full features
        "qwen_router": t == "full",
        "faiss_gpu": t == "full",
        "vllm_integration": t == "full",
    }


def print_tier_info() -> None:
    """Print tier information to console."""
    from rich.console import Console
    from rich.table import Table

    console = Console()
    tier = detect_tier()
    caps = get_capabilities(tier)

    table = Table(title=f"LLMHosts -- Installed Tier: [{tier.upper()}]")
    table.add_column("Feature", style="cyan")
    table.add_column("Available", style="green")
    table.add_column("Tier Required", style="yellow")

    for feature, available in caps.items():
        tier_req = "core"
        if feature in ("knn_router", "modernbert_router", "namespace_cache", "vcache_semantic", "embedding_pipeline"):
            tier_req = "smart"
        elif feature in ("qwen_router", "faiss_gpu", "vllm_integration"):
            tier_req = "full"

        status = "✓" if available else "✗"
        style = "green" if available else "red"
        table.add_row(feature.replace("_", " ").title(), f"[{style}]{status}[/{style}]", tier_req)

    console.print(table)

    if tier == "core":
        console.print("\n[yellow]Upgrade: pip install llmhosts[smart] for ML-powered routing and caching[/yellow]")
    elif tier == "smart":
        console.print("\n[yellow]Upgrade: pip install llmhosts[full] for GPU-accelerated features[/yellow]")
