"""CLI command handlers for GuardRail."""

import sys
from pathlib import Path

import click

from guardrail.cli.processor import run_guardrail_checks
from guardrail.config import GuardRailConfig


@click.command()
@click.option(
    "--root",
    type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
    default=None,
    help="Project root directory (defaults to current directory)",
)
def init(root):
    """Initialize GuardRail in the current directory."""
    config = GuardRailConfig(root=root)
    
    if config.ensure_initialized():
        click.echo("GuardRail is already initialized in this directory.")
        click.echo(f"Config: {config.config_file}")
        click.echo(f"Cache: {config.cache_file}")
        
        # Check if API key is set
        api_key = config.get_openai_api_key()
        if not api_key:
            click.echo("\n⚠️  OpenAI API key not configured.")
            if click.confirm("Would you like to set it now?"):
                api_key = click.prompt(
                    "Please paste your OpenAI API key",
                    hide_input=True,
                    type=str,
                )
                config.initialize(openai_api_key=api_key)
                click.echo("✅ API key saved to config.")
        return

    click.echo("Initializing GuardRail...")
    click.echo("\nTo generate tests, GuardRail needs an OpenAI API key.")
    click.echo("You can get one from: https://platform.openai.com/api-keys")
    
    api_key = click.prompt(
        "Please paste your OpenAI API key",
        hide_input=True,
        type=str,
    )
    
    config.initialize(openai_api_key=api_key)
    click.echo("✅ GuardRail initialized successfully!")
    click.echo(f"📁 Config: {config.config_file}")
    click.echo(f"💾 Cache: {config.cache_file}")
    click.echo("🔑 OpenAI API key saved to config.")


@click.command()
@click.option(
    "--root",
    type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
    default=None,
    help="Project root directory (defaults to current directory)",
)
def check(root):
    """
    Check changed functions and generate tests without executing a command.
    
    Useful for pre-commit hooks or manual verification.
    """
    success = run_guardrail_checks(root=root, execute_command=False)
    if not success:
        sys.exit(1)


@click.command(context_settings={"ignore_unknown_options": True, "allow_extra_args": True})
@click.argument("command", nargs=-1, required=True)
@click.option(
    "--root",
    type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
    default=None,
    help="Project root directory (defaults to current directory)",
)
def run(command, root):
    """
    Run a command with GuardRail protection.
    
    Use '--' to separate guardrail options from your command:
    
    \b
        guardrail run -- pytest
        guardrail run -- python main.py
        guardrail run -- uvicorn app:app
    """
    success = run_guardrail_checks(root=root, execute_command=True, command=command)
    if not success:
        sys.exit(1)

