"""Client pairing CLI command"""

import os
import secrets
from typing import Optional

import typer
from rich import print as rprint
from rich.table import Table


def _generate_api_key() -> str:
    """Generate a unique API key with prefix"""
    return f"ak_live_{secrets.token_hex(24)}"


def _load_clients(config_dir: str) -> dict:
    """Load clients.yaml from config directory"""
    import yaml
    clients_path = os.path.join(config_dir, "clients.yaml")
    if os.path.exists(clients_path):
        with open(clients_path, encoding="utf-8") as f:
            return yaml.safe_load(f) or {}
    return {}


def _save_clients(config_dir: str, clients: dict) -> None:
    """Save clients.yaml to config directory"""
    import yaml
    os.makedirs(config_dir, exist_ok=True)
    clients_path = os.path.join(config_dir, "clients.yaml")
    with open(clients_path, "w", encoding="utf-8") as f:
        yaml.dump(clients, f, default_flow_style=False, allow_unicode=True)


def pair(
    name: Optional[str] = typer.Option(None, "--name", "-n", help="Client name (e.g., geo-backend)"),
    skills_dir: Optional[str] = typer.Option(None, "--skills-dir", help="Custom skills directory for this client"),
    config_dir: str = typer.Option(".", "--config-dir", help="AgentKit config directory"),
    list_clients: bool = typer.Option(False, "--list", "-l", help="List all paired clients"),
    revoke: Optional[str] = typer.Option(None, "--revoke", "-r", help="Revoke a client by name"),
    server_url: str = typer.Option("http://localhost:8001", "--server-url", help="AgentKit server URL for connection instructions"),
):
    """Pair a business system with AgentKit (generate API key + register client)"""
    config_dir = os.path.abspath(config_dir)

    # List mode
    if list_clients:
        clients = _load_clients(config_dir)
        if not clients:
            rprint("[dim]No paired clients[/dim]")
            return
        table = Table(title="Paired Clients")
        table.add_column("Name", style="cyan")
        table.add_column("API Key (prefix)")
        table.add_column("Skills Dir")
        table.add_column("Created")
        for client_name, info in clients.items():
            key_prefix = info.get("api_key", "")[:16] + "..."
            table.add_row(
                client_name,
                key_prefix,
                info.get("skills_dir", "default"),
                info.get("created_at", "N/A"),
            )
        rprint(table)
        return

    # Revoke mode
    if revoke:
        clients = _load_clients(config_dir)
        if revoke not in clients:
            rprint(f"[red]Client '{revoke}' not found[/red]")
            raise typer.Exit(code=1)
        del clients[revoke]
        _save_clients(config_dir, clients)
        rprint(f"[green]Client '{revoke}' revoked[/green]")
        return

    # Pair mode
    if not name:
        rprint("[red]Error: --name is required for pairing[/red]")
        raise typer.Exit(code=1)

    clients = _load_clients(config_dir)
    if name in clients:
        rprint(f"[red]Client '{name}' already paired. Use --revoke first to re-pair.[/red]")
        raise typer.Exit(code=1)

    # Generate API key
    api_key = _generate_api_key()

    # Save client registration
    from datetime import datetime, timezone
    client_info = {
        "api_key": api_key,
        "created_at": datetime.now(timezone.utc).isoformat(),
    }
    if skills_dir:
        client_info["skills_dir"] = os.path.abspath(skills_dir)

    clients[name] = client_info
    _save_clients(config_dir, clients)

    # Print results
    rprint(f"[bold green]Client paired successfully![/bold green]")
    rprint(f"\n  Client: [cyan]{name}[/cyan]")
    rprint(f"  API Key: [bold]{api_key}[/bold]")
    if skills_dir:
        rprint(f"  Skills Dir: {skills_dir}")
    rprint(f"\n[bold]Connection instructions for {name}:[/bold]")
    rprint(f"  Set these environment variables in your business system:")
    rprint(f"  [cyan]AGENTKIT_SERVER_URL={server_url}[/cyan]")
    rprint(f"  [cyan]AGENTKIT_API_KEY={api_key}[/cyan]")
    rprint(f"\n  Or add to your .env file:")
    rprint(f"  AGENTKIT_SERVER_URL={server_url}")
    rprint(f"  AGENTKIT_API_KEY={api_key}")
    rprint(f"\n[dim]API key will not be shown again. Store it securely.[/dim]")
