"""
Spectra Runner CLI
Command-line interface for the local test runner

Usage:
    spectra-runner login --token YOUR_TOKEN
    spectra-runner start
    spectra-runner logout
    spectra-runner status
"""
import asyncio
import sys

import click
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from . import __version__
from .config import ConfigManager
from .websocket_client import WebSocketClient
from .job_handler import JobHandler

console = Console()


@click.group()
@click.version_option(version=__version__, prog_name="spectra-runner")
def main():
    """
    Spectra Runner - Run tests locally with Docker
    
    Run your tests on your own machine while using the Spectra Dashboard.
    """
    pass


@main.command()
@click.option('--token', '-t', required=True, help='Your runner token from Spectra Dashboard')
@click.option('--backend-url', '-u', default=None, help='Custom backend URL (optional)')
def login(token: str, backend_url: str):
    """Save your authentication token (one-time setup)"""
    
    if not token.startswith("sr_"):
        console.print("⚠️  Token should start with 'sr_'. Please check your token.", style="yellow")
        console.print("   Get your token from: Dashboard → Settings → Local Runner", style="dim")
        return
    
    config = ConfigManager()
    config.save_token(token, backend_url)
    
    console.print()
    console.print("✓ Token saved successfully!", style="green bold")
    console.print()
    console.print("Next step: Run [bold]spectra-runner start[/bold] to begin")
    console.print()


@main.command()
def start():
    """Start the runner and wait for jobs"""
    
    config = ConfigManager()
    
    # Check if logged in
    if not config.has_token():
        console.print("❌ Not logged in. Run [bold]spectra-runner login --token YOUR_TOKEN[/bold] first", style="red")
        return
    
    # Print startup banner
    console.print()
    console.print(Panel.fit(
        f"[bold cyan]Spectra Runner v{__version__}[/bold cyan]",
        border_style="cyan"
    ))
    console.print()
    
    # Print security info (transparency!)
    console.print("📋 [dim]What this runner does:[/dim]")
    console.print("   ✓ Receives test jobs from Spectra backend")
    console.print("   ✓ Runs tests in Docker containers")
    console.print("   ✓ Sends results back to Dashboard")
    console.print()
    console.print("🔒 [dim]Security:[/dim]")
    console.print("   • Tests run in isolated containers")
    console.print("   • Only temp workspace is mounted")
    console.print("   • All commands are shown in this terminal")
    console.print()
    
    # Start the runner
    try:
        asyncio.run(run_runner(config))
    except KeyboardInterrupt:
        console.print("\n👋 Stopped by user", style="yellow")
    except Exception as e:
        console.print(f"\n❌ Error: {e}", style="red")
        sys.exit(1)


async def run_runner(config: ConfigManager):
    """Main runner loop"""
    
    # Create WebSocket client
    client = WebSocketClient(
        backend_url=config.get_backend_url(),
        token=config.get_token()
    )
    
    # Create job handler
    job_handler = JobHandler()
    
    # Set job handler
    client.set_job_handler(job_handler.handle_job)
    
    # Connect
    console.print("🔌 Connecting to backend...", style="dim")
    connected = await client.connect()
    
    if not connected:
        console.print("❌ Failed to connect. Check your token and try again.", style="red")
        return
    
    console.print("✓ Connected!", style="green")
    console.print()
    console.print("⏳ Waiting for jobs... [dim](Press Ctrl+C to stop)[/dim]")
    console.print("─" * 50)
    
    # Listen for jobs
    await client.listen()


@main.command()
def logout():
    """Remove saved token and configuration"""
    
    config = ConfigManager()
    config.clear()
    
    console.print("✓ Logged out successfully", style="green")


@main.command()
def status():
    """Check runner status and configuration"""
    
    config = ConfigManager()
    
    console.print()
    
    if config.has_token():
        cfg = config.get_config()
        
        table = Table(title="Spectra Runner Status", show_header=False)
        table.add_column("Key", style="cyan")
        table.add_column("Value")
        
        table.add_row("Status", "[green]✓ Logged in[/green]")
        table.add_row("Backend", cfg.get("backend_url", "N/A"))
        table.add_row("Config file", str(config.CONFIG_FILE))
        table.add_row("Saved at", cfg.get("saved_at", "N/A"))
        
        console.print(table)
        console.print()
        console.print("Run [bold]spectra-runner start[/bold] to begin receiving jobs")
    else:
        console.print("❌ Not logged in", style="red")
        console.print()
        console.print("Run [bold]spectra-runner login --token YOUR_TOKEN[/bold] to get started")
    
    console.print()


if __name__ == "__main__":
    main()
