"""Proxy commands: proxy start, proxy stop, proxy status, proxy logs.

These preserve the existing WebSocket tunnel functionality from the
original mcpbundles-proxy, now under the 'proxy' subcommand group.
"""

import os
import time

import click

from mcpbundles.config import load_token, CONFIG_DIR
from mcpbundles.daemon import start_daemon, stop_daemon, get_status, get_pid_file
from mcpbundles.output import render_success, render_error, render_warning, stdout_console


def _is_running() -> bool:
    """Check if tunnel daemon is running."""
    pid_file = get_pid_file()
    if not pid_file.exists():
        return False
    try:
        pid = int(pid_file.read_text())
        os.kill(pid, 0)
        return True
    except (ValueError, ProcessLookupError, PermissionError):
        pid_file.unlink(missing_ok=True)
        return False


@click.group()
def proxy() -> None:
    """Manage the local WebSocket tunnel (browser, SQLite, Claude Code)."""
    pass


@proxy.command("start")
def proxy_start() -> None:
    """Start tunnel daemon in background."""
    if _is_running():
        render_warning("Proxy is already running. Use 'mcpbundles proxy status' to see details.")
        return

    token = load_token()
    if not token:
        render_error("Not authenticated. Run 'mcpbundles login' first.")
        raise SystemExit(1)

    stdout_console.print("Starting tunnel daemon...")
    start_daemon(token)
    render_success("Tunnel started")
    stdout_console.print("  Use [cyan]mcpbundles proxy status[/] for details")
    stdout_console.print("  Use [cyan]mcpbundles proxy logs[/] to view logs")


@proxy.command("stop")
def proxy_stop() -> None:
    """Stop tunnel daemon."""
    if not _is_running():
        render_warning("Proxy is not running.")
        return

    stdout_console.print("Stopping tunnel daemon...")
    stop_daemon()
    render_success("Tunnel stopped")


@proxy.command("restart")
def proxy_restart() -> None:
    """Restart tunnel daemon."""
    if _is_running():
        stdout_console.print("Stopping tunnel daemon...")
        stop_daemon()
        time.sleep(1)

    token = load_token()
    if not token:
        render_error("Not authenticated. Run 'mcpbundles login' first.")
        raise SystemExit(1)

    stdout_console.print("Starting tunnel daemon...")
    start_daemon(token)
    render_success("Tunnel restarted")


@proxy.command("status")
def proxy_status() -> None:
    """Show tunnel connection status."""
    status_data = get_status()

    if status_data["running"]:
        from rich.panel import Panel

        lines = [
            f"  [bold]PID:[/bold]     {status_data.get('pid', '?')}",
        ]
        if "uptime" in status_data:
            lines.append(f"  [bold]Uptime:[/bold]  {status_data['uptime']}")
        if "tunnel_status" in status_data:
            icon = "[green]●[/]" if status_data["tunnel_status"] == "connected" else "[yellow]●[/]"
            lines.append(f"  [bold]Tunnel:[/bold]  {icon} {status_data['tunnel_status']}")

        stdout_console.print(Panel("\n".join(lines), title="Proxy Status", border_style="green", padding=(1, 2)))
    else:
        stdout_console.print("[red]●[/] Proxy is not running")
        stdout_console.print("  Use [cyan]mcpbundles proxy start[/] to start the tunnel")


@proxy.command("logs")
@click.option("-n", "--lines", default=50, help="Number of lines to show (default: 50)")
@click.option("-f", "--follow", is_flag=True, help="Follow log output (like tail -f)")
def proxy_logs(lines: int, follow: bool) -> None:
    """View tunnel logs."""
    log_file = CONFIG_DIR / "tunnel.log"

    if not log_file.exists():
        stdout_console.print("No logs found.")
        stdout_console.print("  Logs appear after running [cyan]mcpbundles proxy start[/]")
        return

    if follow:
        try:
            with open(log_file, "r") as f:
                f.seek(0, 2)
                stdout_console.print("Following logs (Ctrl+C to stop)...")
                while True:
                    line = f.readline()
                    if line:
                        print(line.rstrip())
                    else:
                        time.sleep(0.1)
        except KeyboardInterrupt:
            print("\nStopped following logs")
    else:
        with open(log_file, "r") as f:
            log_lines = f.readlines()
            for line in log_lines[-lines:]:
                print(line.rstrip())
