"""Command line interface for SurfAI."""

import asyncio
import json
from pathlib import Path

import click

from .browser import Browser
from .config import Config


@click.group()
def cli():
    """SurfAI - Natural Language Browser Automation"""
    pass


@cli.command()
@click.option("--model", "-m", required=True, help="Model name (kimi, deepseek, openai)")
@click.option("--key", "-k", required=True, help="API key")
@click.option("--base-url", "-u", help="Custom base URL (optional)")
def config(model: str, key: str, base_url: str | None):
    """Configure LLM API keys."""
    cfg = Config.load()
    cfg.set_model(model, key, base_url)
    
    # Set as default if it's the first model
    if len(cfg.models) == 1:
        cfg.default_model = model
        cfg.save()
    
    click.echo(f"✓ Configured {model} model")
    click.echo(f"  Config saved to: {Config.get_config_path()}")


@cli.command()
@click.option("--model", "-m", help="Model to use (overrides default)")
@click.option("--headless", "-h", is_flag=True, default=True, help="Run in headless mode")
@click.option("--visible", "-v", is_flag=True, help="Show browser window")
@click.argument("instruction")
def run(instruction: str, model: str | None, headless: bool, visible: bool):
    """Execute a browser automation task."""
    headless = not visible  # --visible overrides --headless
    
    async def execute():
        cfg = Config.load()
        
        # Check if any model is configured
        if not cfg.models:
            click.echo("❌ No model configured. Run one of:")
            click.echo("   surfai config --model kimi --key <your-key>")
            click.echo("   surfai config --model deepseek --key <your-key>")
            return
        
        used_model = model or cfg.default_model
        click.echo(f"🤖 Using model: {used_model}")
        click.echo(f"🌐 Task: {instruction}")
        click.echo("⏳ Executing...\n")
        
        try:
            async with Browser(headless=headless, model=used_model, config=cfg) as browser:
                results = await browser.execute_task(instruction)
                
                # Display results
                if results["actions_executed"]:
                    click.echo("✓ Actions executed:")
                    for action in results["actions_executed"]:
                        click.echo(f"  • {action}")
                
                if results["extracted_data"]:
                    click.echo("\n📊 Extracted data:")
                    for i, data in enumerate(results["extracted_data"], 1):
                        click.echo(f"  {i}. {data[:200]}{'...' if len(data) > 200 else ''}")
                
                if results["screenshots"]:
                    click.echo("\n📸 Screenshots saved:")
                    for path in results["screenshots"]:
                        click.echo(f"  • {Path(path).absolute()}")
                
                click.echo("\n✅ Task completed!")
                
        except ValueError as e:
            click.echo(f"❌ Configuration error: {e}")
        except Exception as e:
            click.echo(f"❌ Error: {e}")
    
    asyncio.run(execute())


@cli.command(name="list-models")
def list_models():
    """List configured models."""
    cfg = Config.load()
    
    if not cfg.models:
        click.echo("No models configured.")
        click.echo("Run: surfai config --model <name> --key <key>")
        return
    
    click.echo("Configured models:")
    for name in cfg.models:
        marker = " (default)" if name == cfg.default_model else ""
        click.echo(f"  • {name}{marker}")


@cli.command()
@click.option("--host", "-h", default="0.0.0.0", help="Host to bind to")
@click.option("--port", "-p", default=8000, help="Port to bind to")
def server(host: str, port: int):
    """Start the extension API server."""
    click.echo("🚀 Starting SurfAI Extension API Server...")
    click.echo(f"   Host: {host}")
    click.echo(f"   Port: {port}")
    click.echo("")
    click.echo("📱 Chrome Extension will connect to:")
    click.echo(f"   http://localhost:{port}")
    click.echo("")
    click.echo("Press Ctrl+C to stop")
    click.echo("-" * 60)
    
    try:
        from .extension_api import start_server
        start_server(host=host, port=port)
    except ImportError as e:
        click.echo(f"❌ Error: {e}")
        click.echo("Please install required dependencies:")
        click.echo("  pip install fastapi uvicorn")
    except KeyboardInterrupt:
        click.echo("\n\n⏹️  Server stopped")


@cli.command()
def status():
    """Show SurfAI status and configuration."""
    cfg = Config.load()
    
    click.echo("SurfAI Status")
    click.echo("=" * 40)
    click.echo(f"Default model: {cfg.default_model}")
    click.echo(f"Configured models: {', '.join(cfg.models.keys()) or 'None'}")
    click.echo(f"Config path: {Config.get_config_path()}")


# Alias for convenience
@cli.command()
@click.argument("instruction")
@click.option("--model", "-m", help="Model to use")
@click.option("--visible", "-v", is_flag=True, help="Show browser window")
def do(instruction: str, model: str | None, visible: bool):
    """Quick alias for 'surfai run'."""
    ctx = click.get_current_context()
    ctx.invoke(run, instruction=instruction, model=model, headless=not visible, visible=visible)


def main():
    """Entry point for the CLI."""
    cli()


if __name__ == "__main__":
    main()
