"""
Stats and models display — works without the API server.
"""

import json
import os

from elgringo.cli.colors import Colors


def run_stats():
    """Show team cost stats and agent insights — works without server."""
    print(f"\n{Colors.BOLD}{'─' * 60}{Colors.RESET}")
    print(f"{Colors.BOLD}  El Gringo — Team Stats{Colors.RESET}")
    print(f"{Colors.BOLD}{'─' * 60}{Colors.RESET}\n")

    # Read costs directly from local files
    try:
        from elgringo.routing.cost_tracker import CostTracker
        tracker = CostTracker()
        stats = tracker.get_statistics()

        # Today's costs
        today = stats.get("today", {})
        today_total = today.get("total_cost", 0)
        today_by_agent = today.get("by_agent", {})

        # Monthly costs
        month = stats.get("this_month", {})
        month_total = month.get("total_cost", 0)
        month_by_agent = month.get("by_agent", {})

        # Use monthly if today is empty
        total = month_total if month_total > today_total else today_total
        by_agent = month_by_agent if month_total > today_total else today_by_agent
        period = "this month" if month_total > today_total else "today"

        if total > 0:
            print(f"  {Colors.CYAN}Spend ({period}):{Colors.RESET} ${total:.4f}")
            if by_agent:
                for agent, cost in sorted(by_agent.items(), key=lambda x: -x[1]):
                    bar = "█" * max(1, int(cost / max(total, 0.0001) * 20))
                    print(f"    {agent:<20} ${cost:.4f}  {Colors.GREEN}{bar}{Colors.RESET}")
            print()
        else:
            print(f"  {Colors.DIM}No cost data yet. Costs are tracked when you use agents.{Colors.RESET}\n")

        # Model breakdown
        by_model = stats.get("by_model", {})
        if by_model:
            print(f"  {Colors.CYAN}By Model:{Colors.RESET}")
            for model, info in sorted(by_model.items(), key=lambda x: -x[1].get("total_cost", 0)):
                cost = info.get("total_cost", 0)
                reqs = info.get("total_requests", 0)
                if cost > 0:
                    print(f"    {model:<24} ${cost:.4f}  ({reqs} requests)")
            print()

        # Budget
        budget = stats.get("budget", {})
        daily_pct = budget.get("daily_percent", 0)
        monthly_pct = budget.get("monthly_percent", 0)
        if daily_pct > 0 or monthly_pct > 0:
            print(f"  {Colors.CYAN}Budget:{Colors.RESET}")
            print(f"    Daily:   {daily_pct:.0f}% used")
            print(f"    Monthly: {monthly_pct:.0f}% used")
            print()

    except Exception:
        # Fallback: try API if available
        try:
            import urllib.request
            base = os.getenv("ELGRINGO_API_URL", "http://127.0.0.1:8090")
            req = urllib.request.Request(f"{base}/v1/costs")
            with urllib.request.urlopen(req, timeout=3) as resp:
                costs = json.loads(resp.read())
            total = costs.get("total_cost", 0)
            by_agent = costs.get("by_agent", {})
            print(f"  {Colors.CYAN}Total Spend:{Colors.RESET} ${total:.4f}")
            if by_agent:
                for agent, cost in sorted(by_agent.items(), key=lambda x: -x[1]):
                    bar = "█" * max(1, int(cost / max(total, 0.0001) * 20))
                    print(f"    {agent:<20} ${cost:.4f}  {Colors.GREEN}{bar}{Colors.RESET}")
            print()
        except Exception:
            print(f"  {Colors.DIM}No cost data available.{Colors.RESET}\n")

    # Agent performance from feedback loop
    try:
        from elgringo.intelligence.feedback_loop import FeedbackLearningLoop
        loop = FeedbackLearningLoop()
        state = loop._load_state() if hasattr(loop, '_load_state') else {}
        adjustments = state.get("expertise_adjustments", {})
        if adjustments:
            print(f"  {Colors.CYAN}Agent Performance (from feedback):{Colors.RESET}")
            for agent, score in sorted(adjustments.items(), key=lambda x: -x[1]):
                color = Colors.GREEN if score >= 0 else Colors.RED
                direction = "+" if score >= 0 else ""
                print(f"    {agent:<20} {color}{direction}{score:.2f}{Colors.RESET}")
            print()
    except Exception:
        pass

    print(f"{Colors.BOLD}{'─' * 60}{Colors.RESET}\n")


def run_models():
    """Show available models and their status — works without server."""
    import subprocess as _sp

    print(f"\n{Colors.BOLD}{'─' * 60}{Colors.RESET}")
    print(f"{Colors.BOLD}  El Gringo — Models{Colors.RESET}")
    print(f"{Colors.BOLD}{'─' * 60}{Colors.RESET}\n")

    # Cloud agents — check by API key presence
    cloud_agents = [
        ("ChatGPT", "OPENAI_API_KEY", "gpt-4o", "Senior Developer"),
        ("Gemini", "GEMINI_API_KEY,GOOGLE_API_KEY", "gemini-2.5-flash", "Creative Innovator"),
        ("Grok", "XAI_API_KEY,GROK_API_KEY", "grok-3", "Strategic Reasoner"),
        ("Grok-Fast", "XAI_API_KEY,GROK_API_KEY", "grok-3-fast", "Rapid Coder"),
        ("Claude", "ANTHROPIC_API_KEY", "claude-sonnet-4-5", "Lead Architect"),
    ]

    print(f"  {Colors.CYAN}Cloud Agents:{Colors.RESET}")
    for name, env_keys, model, role in cloud_agents:
        has_key = any(os.environ.get(k) for k in env_keys.split(","))
        dot = f"{Colors.GREEN}●{Colors.RESET}" if has_key else f"{Colors.RED}○{Colors.RESET}"
        status = "" if has_key else f" {Colors.DIM}(no key){Colors.RESET}"
        print(f"    {dot} {name:<16} {Colors.DIM}{model:<24}{Colors.RESET} {role}{status}")
    print()

    # Ollama models
    print(f"  {Colors.CYAN}Local Models (Ollama):{Colors.RESET}")
    try:
        result = _sp.run(["ollama", "list"], capture_output=True, text=True, timeout=5)
        if result.returncode == 0:
            lines = result.stdout.strip().splitlines()
            if len(lines) > 1:  # has models (first line is header)
                for line in lines[1:]:
                    parts = line.split()
                    if parts:
                        model_name = parts[0]
                        size = parts[2] + " " + parts[3] if len(parts) > 3 else ""
                        print(f"    {Colors.GREEN}●{Colors.RESET} {model_name:<28} {Colors.DIM}{size}{Colors.RESET}")
            else:
                print(f"    {Colors.DIM}No models pulled. Try: ollama pull llama3.2:3b{Colors.RESET}")
        else:
            print(f"    {Colors.DIM}Ollama not running{Colors.RESET}")
    except FileNotFoundError:
        print(f"    {Colors.DIM}Ollama not installed (https://ollama.com){Colors.RESET}")
    except Exception:
        print(f"    {Colors.DIM}Ollama not available{Colors.RESET}")
    print()

    # MLX
    print(f"  {Colors.CYAN}MLX (Apple Silicon):{Colors.RESET}")
    try:
        import importlib
        importlib.import_module("mlx_lm")
        print(f"    {Colors.GREEN}●{Colors.RESET} mlx_lm available")
        try:
            import elgringo.agents.qwen_mlx  # noqa: F401
            print(f"    {Colors.DIM}Qwen models auto-load on first use{Colors.RESET}")
        except ImportError:
            pass
    except ImportError:
        print(f"    {Colors.DIM}Not available (pip install mlx-lm){Colors.RESET}")
    print()

    print(f"{Colors.BOLD}{'─' * 60}{Colors.RESET}\n")
