"""Initialize command for HexDAG CLI."""

from pathlib import Path
from typing import Annotated, Any

import typer
from rich.console import Console
from rich.prompt import Confirm

app = typer.Typer()
console = Console()


@app.callback(invoke_without_command=True)
def init(
    ctx: typer.Context,
    with_adapters: Annotated[
        str | None,
        typer.Option(
            "--with",
            help="Comma-separated list of adapters to include (e.g., openai,anthropic,local)",
        ),
    ] = None,
    force: Annotated[
        bool,
        typer.Option(
            "--force",
            "-f",
            help="Overwrite existing configuration",
        ),
    ] = False,
    path: Annotated[
        Path | None,
        typer.Argument(
            help="Directory to initialize (defaults to current directory)",
        ),
    ] = None,
) -> None:
    """Initialize a new HexDAG project with configuration."""
    if ctx.invoked_subcommand is not None:
        return

    if path is None:
        path = Path.cwd()

    config_path = path / "hexdag.toml"

    if (
        config_path.exists()
        and not force
        and not Confirm.ask(f"[yellow]hexdag.toml already exists in {path}. Overwrite?[/yellow]")
    ):
        console.print("[red]Initialization cancelled.[/red]")
        raise typer.Exit(1)

    # Parse adapters
    adapters = []
    if with_adapters:
        adapters = [a.strip() for a in with_adapters.split(",")]

    # Generate configuration
    config_content = _generate_config(adapters)

    # Ensure directory exists
    path.mkdir(parents=True, exist_ok=True)

    # Write configuration
    config_path.write_text(config_content)
    console.print(f"[green]✓[/green] Created hexdag.toml in {path}")

    # Show next steps
    console.print("\n[bold]Next steps:[/bold]")
    console.print("1. Review and customize hexdag.toml")
    console.print("2. Set any required environment variables")

    if adapters:
        console.print("\n[bold]Adapters configured:[/bold]")
        for adapter in adapters:
            _print_adapter_info(adapter)


def _generate_config(adapters: list[str]) -> str:
    """Generate hexdag.toml configuration."""
    lines = [
        "# HexDAG Configuration",
        "# Generated by: hexdag init",
        "",
        "# Core modules to load",
        "modules = [",
        '    "hexdag.core.ports",',
        '    "hexdag.builtin.nodes",',
        "]",
        "",
        "# Plugins to load",
        "plugins = [",
        '    "hexdag.builtin.adapters.local",  # Local in-process adapters',
    ]

    lines.append('    "hexdag.adapters.mock",   # Mock adapters for testing')

    if "openai" in adapters:
        lines.append('    # "hexdag.adapters.openai",  # OpenAI adapter (requires api key)')
    if "anthropic" in adapters:
        lines.append('    # "hexdag.adapters.anthropic",  # Anthropic adapter (requires api key)')

    lines.extend([
        "]",
        "",
        "# Development mode",
        "dev_mode = true",
        "",
        "[settings]",
        'log_level = "INFO"',
        "enable_metrics = true",
    ])

    if "openai" in adapters:
        lines.extend([
            "",
            "[adapters.openai]",
            "# Set via environment variable or directly",
            'api_key = "${OPENAI_API_KEY}"',
            'model = "gpt-4"',
            "temperature = 0.7",
            "max_tokens = 2000",
        ])

    if "anthropic" in adapters:
        lines.extend([
            "",
            "[adapters.anthropic]",
            "# Set via environment variable or directly",
            'api_key = "${ANTHROPIC_API_KEY}"',
            'model = "claude-3-opus-20240229"',
            "temperature = 0.7",
            "max_tokens = 2000",
        ])

    if "local" in adapters or not adapters:
        lines.extend([
            "",
            "[adapters.local]",
            "# Local adapter settings",
            "memory_max_size = 1000",
            "cache_ttl = 3600",
        ])

    return "\n".join(lines) + "\n"


def _print_adapter_info(adapter: str) -> None:
    """Print information about an adapter."""
    import shutil

    # Detect if uv is available
    has_uv = shutil.which("uv") is not None
    prefix = "uv pip install" if has_uv else "pip install"

    info: dict[str, dict[str, Any]] = {
        "openai": {
            "name": "OpenAI",
            "install": f"{prefix} hexdag[adapters-openai]",
            "env": "OPENAI_API_KEY",
        },
        "anthropic": {
            "name": "Anthropic Claude",
            "install": f"{prefix} hexdag[adapters-anthropic]",
            "env": "ANTHROPIC_API_KEY",
        },
        "mock": {
            "name": "Mock Adapters",
            "install": "Included in core",
            "env": None,
        },
        "local": {
            "name": "Local Adapters",
            "install": "Included in core",
            "env": None,
        },
    }

    if adapter in info:
        details = info[adapter]
        console.print(f"  • [cyan]{details['name']}[/cyan]")
        if details["install"] != "Included in core":
            console.print(f"    Install: [yellow]{details['install']}[/yellow]")
        if details["env"]:
            console.print(f"    Required: [yellow]{details['env']}[/yellow] environment variable")
