"""Project initialization CLI command"""

import os
from typing import Optional

import typer
from rich import print as rprint

from agentkit.cli.templates import AGENTKIT_YAML, ENV_EXAMPLE, DOCKER_COMPOSE, EXAMPLE_SKILL


def _write_file(path: str, content: str, force: bool = False) -> bool:
    """Write content to file, respecting existing files unless force=True"""
    if os.path.exists(path) and not force:
        rprint(f"[yellow]Skipping (already exists):[/yellow] {path}")
        return False
    os.makedirs(os.path.dirname(path) if os.path.dirname(path) else ".", exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(content)
    rprint(f"[green]Created:[/green] {path}")
    return True


def init(
    output_dir: str = typer.Option(".", "--output-dir", "-o", help="Output directory"),
    non_interactive: bool = typer.Option(False, "--non-interactive", "-y", help="Skip prompts, use defaults"),
    force: bool = typer.Option(False, "--force", "-f", help="Overwrite existing files"),
):
    """Initialize an AgentKit project with default configuration"""
    output_dir = os.path.abspath(output_dir)
    os.makedirs(output_dir, exist_ok=True)

    rprint(f"[bold]Initializing AgentKit project in {output_dir}[/bold]")

    # Generate agentkit.yaml
    _write_file(os.path.join(output_dir, "agentkit.yaml"), AGENTKIT_YAML, force=force)

    # Generate .env.example
    _write_file(os.path.join(output_dir, ".env.example"), ENV_EXAMPLE, force=force)

    # Generate docker-compose.yaml
    _write_file(os.path.join(output_dir, "docker-compose.yaml"), DOCKER_COMPOSE, force=force)

    # Generate skills directory with example
    skills_dir = os.path.join(output_dir, "skills")
    os.makedirs(skills_dir, exist_ok=True)
    _write_file(os.path.join(skills_dir, "example_skill.yaml"), EXAMPLE_SKILL, force=force)

    rprint("\n[bold green]AgentKit project initialized![/bold green]")
    rprint("\nNext steps:")
    rprint("  1. Copy [cyan].env.example[/cyan] to [cyan].env[/cyan] and fill in your API keys")
    rprint("  2. Edit [cyan]agentkit.yaml[/cyan] to configure your agents")
    rprint("  3. Run [cyan]agentkit serve[/cyan] to start the server")
    rprint("  4. Run [cyan]agentkit task submit --skill example_skill --input '{\"message\": \"Hello\"}' --server-url http://localhost:8001[/cyan]")
