"""Command-line interface for MCPBundles proxy."""

import click
import os
import signal
from mcpbundles_proxy.config import load_token, CONFIG_DIR
from mcpbundles_proxy.auth import oauth_flow
from mcpbundles_proxy.daemon import start_daemon, stop_daemon, get_status, get_pid_file


@click.group()
@click.version_option(version='0.1.0', prog_name='mcpbundles-proxy')
def cli():
    """MCPBundles Desktop Proxy - Tunnel cloud requests to local services."""
    pass


@cli.command()
def login():
    """Authenticate with MCPBundles."""
    try:
        oauth_flow()
        click.echo("✅ Successfully authenticated!")
    except Exception as e:
        click.echo(f"❌ Authentication failed: {e}", err=True)
        raise SystemExit(1)


@cli.command()
def start():
    """Start tunnel daemon in background."""
    # Check if already running
    if is_running():
        click.echo("⚠️  Proxy is already running")
        click.echo("   Use 'mcpbundles-proxy status' to check connection")
        return
    
    # Check for token
    token = load_token()
    if not token:
        click.echo("❌ Not authenticated. Run 'mcpbundles-proxy login' first.")
        raise SystemExit(1)
    
    # Start daemon
    click.echo("Starting tunnel daemon...")
    start_daemon(token)
    click.echo("✅ Tunnel started")
    click.echo("   Use 'mcpbundles-proxy status' to check connection")
    click.echo("   Use 'mcpbundles-proxy logs' to view logs")


@cli.command()
def stop():
    """Stop tunnel daemon."""
    if not is_running():
        click.echo("⚠️  Proxy is not running")
        return
    
    click.echo("Stopping tunnel daemon...")
    stop_daemon()
    click.echo("✅ Tunnel stopped")


@cli.command()
def restart():
    """Restart tunnel daemon."""
    if is_running():
        click.echo("Stopping tunnel daemon...")
        stop_daemon()
        import time
        time.sleep(1)
    
    click.echo("Starting tunnel daemon...")
    token = load_token()
    if not token:
        click.echo("❌ Not authenticated. Run 'mcpbundles-proxy login' first.")
        raise SystemExit(1)
    
    start_daemon(token)
    click.echo("✅ Tunnel restarted")


@cli.command()
def status():
    """Show connection status."""
    status_data = get_status()
    
    if status_data['running']:
        click.echo(f"✅ Running (PID: {status_data['pid']})")
        if 'uptime' in status_data:
            click.echo(f"   Uptime: {status_data['uptime']}")
        if 'user' in status_data:
            click.echo(f"   User: {status_data['user']}")
        if 'tunnel_status' in status_data:
            status_icon = "🟢" if status_data['tunnel_status'] == 'connected' else "🟡"
            click.echo(f"   Tunnel: {status_icon} {status_data['tunnel_status']}")
    else:
        click.echo("🔴 Not running")
        click.echo("   Use 'mcpbundles-proxy start' to start the tunnel")


@cli.command()
@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 logs(lines, follow):
    """View tunnel logs."""
    log_file = CONFIG_DIR / 'tunnel.log'
    
    if not log_file.exists():
        click.echo("No logs found")
        click.echo("   Logs will appear after running 'mcpbundles-proxy start'")
        return
    
    if follow:
        # Follow mode - stream logs
        try:
            import time
            with open(log_file, 'r') as f:
                # Seek to end
                f.seek(0, 2)
                click.echo("Following logs (Ctrl+C to stop)...")
                while True:
                    line = f.readline()
                    if line:
                        click.echo(line.rstrip())
                    else:
                        time.sleep(0.1)
        except KeyboardInterrupt:
            click.echo("\nStopped following logs")
    else:
        # Show last N lines
        with open(log_file, 'r') as f:
            log_lines = f.readlines()
            for line in log_lines[-lines:]:
                click.echo(line.rstrip())


@cli.command()
def logout():
    """Remove stored credentials."""
    from mcpbundles_proxy.config import delete_token
    
    if is_running():
        click.echo("⚠️  Stopping tunnel daemon first...")
        stop_daemon()
    
    delete_token()
    click.echo("✅ Logged out successfully")


def is_running():
    """Check if daemon is running."""
    pid_file = get_pid_file()
    
    if not pid_file.exists():
        return False
    
    try:
        pid = int(pid_file.read_text())
        # Check if process exists
        os.kill(pid, 0)  # Doesn't actually kill, just checks
        return True
    except (ValueError, ProcessLookupError, PermissionError):
        # PID file exists but process doesn't
        pid_file.unlink(missing_ok=True)
        return False


if __name__ == '__main__':
    cli()

