"""Terminal UI — interactive chat in the terminal."""
from __future__ import annotations

import asyncio
from rich.console import Console
from rich.panel import Panel
from rich.markdown import Markdown
from rich.text import Text
from prompt_toolkit import PromptSession
from prompt_toolkit.history import InMemoryHistory

from hivemind.node import Node


console = Console()


def print_banner(node: Node) -> None:
    """Print the HiveMind startup banner."""
    model_status = "✅ Loaded" if node.model.loaded else "❌ Not loaded"
    plugins = ", ".join(node.plugins.loaded) or "none"

    banner = Text()
    banner.append("🧠 HiveMind", style="bold magenta")
    banner.append(f" v0.1.0\n\n", style="dim")
    banner.append(f"  Node:    {node.name} ({node.id})\n")
    banner.append(f"  Model:   {model_status}\n")
    banner.append(f"  Plugins: {plugins}\n")
    banner.append(f"  Cache:   {node.cache.size} entries\n")

    console.print(Panel(banner, title="HiveMind Node", border_style="magenta"))
    console.print("[dim]Type /help for commands, /quit to exit[/dim]\n")


async def run_tui(node: Node) -> None:
    """Run the interactive terminal UI."""
    print_banner(node)

    session = PromptSession(history=InMemoryHistory())

    while True:
        try:
            user_input = await asyncio.get_event_loop().run_in_executor(
                None, lambda: session.prompt("You > ")
            )
        except (EOFError, KeyboardInterrupt):
            break

        text = user_input.strip()
        if not text:
            continue

        # Commands
        if text.startswith("/"):
            cmd = text.lower().split()[0]
            if cmd in ("/quit", "/exit", "/q"):
                break
            elif cmd == "/status":
                s = node.status
                console.print(f"\n[bold]Node:[/bold] {s['name']} ({s['id']})")
                console.print(f"[bold]Model:[/bold] {'✅' if s['model_loaded'] else '❌'}")
                console.print(f"[bold]Plugins:[/bold] {', '.join(s['plugins'])}")
                console.print(f"[bold]Cache:[/bold] {s['cache_size']} entries")
                console.print(f"[bold]History:[/bold] {s['history_length']} messages\n")
                continue
            elif cmd == "/clear":
                node.history.clear()
                console.print("[dim]History cleared.[/dim]\n")
                continue
            elif cmd == "/plugins":
                for cap in node.plugins.all_capabilities():
                    console.print(f"  [cyan]{cap.plugin}.{cap.name}[/cyan]: {cap.description}")
                console.print()
                continue
            elif cmd == "/peers":
                if not node.network:
                    console.print("  [dim]Netzwerk nicht aktiviert. Setze network.enabled: true in config.yaml[/dim]\n")
                    continue
                peers = node.network.peers.all_peers
                if not peers:
                    console.print("  [dim]Keine Peers bekannt.[/dim]\n")
                    continue
                console.print(f"\n  [bold]Peers ({node.network.peers.status_summary()}):[/bold]")
                for p in peers:
                    status = "[green]●[/green]" if p.online else "[red]○[/red]"
                    age = f"{p.hours_since_seen:.0f}h ago" if not p.online else "online"
                    console.print(f"    {status} {p.name or p.node_id}  {p.address}  ({age})")
                console.print()
                continue
            elif cmd == "/addpeer":
                parts = text.split()
                if len(parts) < 2:
                    console.print("  [dim]Usage: /addpeer host:port[/dim]\n")
                    continue
                try:
                    addr = parts[1]
                    from hivemind.network.protocol import PeerInfo as _PI
                    host, port = _PI.parse_address(addr)
                    if node.network:
                        node.network.peers.add_manual(host, port)
                        console.print(f"  [green]Peer hinzugefügt: {addr}[/green]\n")
                        asyncio.create_task(node.network.connect_to(host, int(port)))
                    else:
                        console.print("  [dim]Netzwerk nicht aktiviert.[/dim]\n")
                except Exception as e:
                    console.print(f"  [red]Fehler: {e}[/red]\n")
                continue
            elif cmd == "/help":
                console.print("\n[bold]Commands:[/bold]")
                console.print("  /status    — Show node status")
                console.print("  /plugins   — List loaded plugins & capabilities")
                console.print("  /peers     — Show known peers")
                console.print("  /addpeer   — Add peer: /addpeer host:port")
                console.print("  /clear     — Clear conversation history")
                console.print("  /quit      — Exit HiveMind\n")
                continue
            else:
                console.print(f"[red]Unknown command: {cmd}[/red]\n")
                continue

        # Chat
        with console.status("[magenta]Thinking...[/magenta]"):
            response, meta = await node.chat(text)

        console.print()
        console.print(Panel(Markdown(response), title="🧠 HiveMind", border_style="magenta"))
        # Routing info
        src = meta.get("source", "local")
        conf = meta.get("confidence", 0.0)
        src_name = meta.get("source_name", "")
        src_spec = meta.get("source_specialization", "")
        topics = meta.get("topics", [])
        conf_color = "green" if conf >= 0.8 else "yellow" if conf >= 0.5 else "red"
        if src == "cache":
            src_str = "📦 [dim]Cache[/dim]"
        elif src == "network":
            spec_str = f" · {src_spec}" if src_spec else ""
            src_str = f"🌐 [cyan]{src_name}{spec_str}[/cyan]"
        else:
            spec_str = f" · {src_spec}" if src_spec else ""
            src_str = f"🎯 [dim]Lokal ({src_name}{spec_str})[/dim]"
        topics_str = f" · [{', '.join(topics[:3])}]" if topics else ""
        console.print(f"   {src_str} · Score: [{conf_color}]{conf:.2f}[/{conf_color}]{topics_str}\n")
