"""Click wrappers: keys group — API key management CLI."""
from __future__ import annotations

import click
import secrets
from pathlib import Path


def generate_key() -> str:
    """Generate a new local API key."""
    token = secrets.token_hex(32)
    return f"sk-proxy-{token}"


def update_env_file(env_path: Path, new_key: str) -> bool:
    """Update the .env file with the new key."""
    if not env_path.exists():
        click.echo(f"Error: {env_path} not found", err=True)
        return False

    content = env_path.read_text()
    lines = content.split('\n')

    # Update or add the master key
    updated = False
    for i, line in enumerate(lines):
        if line.startswith('AI_PROXY_MASTER_KEY='):
            lines[i] = f'AI_PROXY_MASTER_KEY={new_key}'
            updated = True
            break

    if not updated:
        lines.append(f'AI_PROXY_MASTER_KEY={new_key}')

    # Write back
    env_path.write_text('\n'.join(lines))
    return True


@click.group(name="keys")
def keys():
    """Manage local API keys for dashboard authentication."""
    pass


@keys.command(name="generate")
@click.option(
    "--env-file",
    type=click.Path(path_type=Path, exists=False),
    default=Path(".env"),
    help="Path to .env file to update (default: .env)"
)
@click.option(
    "--print-only",
    is_flag=True,
    help="Print the key without updating .env file"
)
def generate_cmd(env_file: Path, print_only: bool):
    """Generate a new local API key."""
    new_key = generate_key()

    if print_only:
        click.echo(new_key)
        return

    if update_env_file(env_file, new_key):
        click.echo(f"✓ Generated new local API key")
        click.echo(f"  Key: {new_key}")
        click.echo(f"  Updated: {env_file}")
        click.echo()
        click.echo("Restart proxym to apply the new key.")
    else:
        click.echo("✗ Failed to update .env file", err=True)
        raise click.Abort()


@keys.command(name="ensure")
@click.option(
    "--env-file",
    type=click.Path(path_type=Path, exists=False),
    default=Path(".env"),
    help="Path to .env file to check/update (default: .env)"
)
def ensure_cmd(env_file: Path):
    """Ensure a valid local API key exists in .env file."""
    if not env_file.exists():
        click.echo(f"Error: {env_file} not found", err=True)
        raise click.Abort()

    content = env_file.read_text()
    current_key = None

    for line in content.split('\n'):
        if line.startswith('AI_PROXY_MASTER_KEY='):
            current_key = line.split('=', 1)[1].strip()
            break

    # Check if key is valid
    if current_key and current_key.startswith('sk-proxy-'):
        click.echo(f"✓ Local API key is valid: {current_key[:20]}...")
        return

    # Generate new key if invalid or missing
    new_key = generate_key()

    if update_env_file(env_file, new_key):
        click.echo(f"✓ Generated new local API key")
        click.echo(f"  Key: {new_key}")
        click.echo(f"  Updated: {env_file}")
        click.echo()
        click.echo("Restart proxym to apply the new key.")
    else:
        click.echo("✗ Failed to update .env file", err=True)
        raise click.Abort()


@keys.command(name="show")
@click.option(
    "--env-file",
    type=click.Path(path_type=Path, exists=False),
    default=Path(".env"),
    help="Path to .env file to read (default: .env)"
)
@click.option(
    "--full",
    is_flag=True,
    help="Show the full key (default: truncated)"
)
def show_cmd(env_file: Path, full: bool):
    """Show the current local API key from .env file."""
    if not env_file.exists():
        click.echo(f"Error: {env_file} not found", err=True)
        raise click.Abort()

    content = env_file.read_text()
    current_key = None

    for line in content.split('\n'):
        if line.startswith('AI_PROXY_MASTER_KEY='):
            current_key = line.split('=', 1)[1].strip()
            break

    if not current_key:
        click.echo("✗ No AI_PROXY_MASTER_KEY found in .env file", err=True)
        raise click.Abort()

    # Determine key type
    if current_key.startswith('sk-proxy-'):
        key_type = "local"
        status_icon = "✓"
    elif current_key.startswith('sk-or-'):
        key_type = "OpenRouter (external)"
        status_icon = "⚠"
    else:
        key_type = "unknown"
        status_icon = "?"

    display_key = current_key if full else f"{current_key[:20]}..."

    click.echo(f"{status_icon} Current API key ({key_type}):")
    click.echo(f"  {display_key}")

    if key_type == "OpenRouter (external)":
        click.echo()
        click.echo("Note: External keys may not work with dashboard SSE streams.")
        click.echo("      Run 'proxym keys ensure' to generate a local key.")


@keys.command(name="init")
@click.option(
    "--env-file",
    type=click.Path(path_type=Path, exists=False),
    default=Path(".env"),
    help="Path to .env file (default: .env)"
)
def init_cmd(env_file: Path):
    """Initialize development environment with valid local API key."""
    click.echo("🚀 Initializing proxym development environment...")
    click.echo()

    # Check current key
    if not env_file.exists():
        click.echo(f"Error: {env_file} not found", err=True)
        raise click.Abort()

    content = env_file.read_text()
    current_key = None

    for line in content.split('\n'):
        if line.startswith('AI_PROXY_MASTER_KEY='):
            current_key = line.split('=', 1)[1].strip()
            break

    # Ensure valid key
    if current_key and current_key.startswith('sk-proxy-'):
        click.echo(f"✓ Local API key is valid: {current_key[:20]}...")
    else:
        new_key = generate_key()
        if update_env_file(env_file, new_key):
            click.echo(f"✓ Generated new local API key: {new_key[:20]}...")
        else:
            click.echo("✗ Failed to update .env file", err=True)
            raise click.Abort()

    click.echo()
    click.echo("✅ Development environment ready!")
    click.echo()
    click.echo("Next steps:")
    click.echo("  1. Run 'proxym serve' to start the server")
    click.echo("  2. Open http://localhost:4000/dashboard-ui")
    click.echo("  3. Use 'proxym keys generate' to generate a new key anytime")
