"""koan init — scaffold a new KOAN project."""

from __future__ import annotations

from pathlib import Path

import typer
from rich.console import Console

console = Console()

_ENV_TEMPLATE = """\
# KOAN Environment Configuration
# Copy this file to .env and fill in your API keys.

# LLM Providers (at least one required)
OPENAI_API_KEY=
ANTHROPIC_API_KEY=

# Graph Database (optional)
# GRAPH_PROVIDER=neo4j
# GRAPH_URI=bolt://localhost:7687
# GRAPH_USERNAME=neo4j
# GRAPH_PASSWORD=koan-dev-password
"""

_AGENT_TEMPLATE = """\
\"\"\"Example KOAN agent.\"\"\"

from koan.agents import AgentConfig, ReactAgent
from koan.llm.client import LLMClient
from koan.llm.config import LLMConfig


async def main() -> None:
    config = LLMConfig(provider="openai", model="gpt-4o-mini")
    client = LLMClient(config)
    agent = ReactAgent("my-agent", client=client, config=AgentConfig())

    result = await agent.run("Hello, world!")
    print(result.output)


if __name__ == "__main__":
    import asyncio
    asyncio.run(main())
"""


def init_command(
    path: str = typer.Argument(".", help="Directory to initialize (default: current)"),
) -> None:
    """Scaffold a new KOAN project with recommended directory structure."""
    root = Path(path).resolve()

    dirs = [
        root / "agents",
        root / "tools",
        root / "prompts",
    ]

    for d in dirs:
        d.mkdir(parents=True, exist_ok=True)

    # Create .env.example
    env_file = root / ".env.example"
    if not env_file.exists():
        env_file.write_text(_ENV_TEMPLATE)
        console.print(f"  [green]Created[/green] {env_file.relative_to(root)}")

    # Create example agent
    agent_file = root / "agents" / "example_agent.py"
    if not agent_file.exists():
        agent_file.write_text(_AGENT_TEMPLATE)
        console.print(f"  [green]Created[/green] {agent_file.relative_to(root)}")

    # Create __init__.py files
    for d in dirs:
        init_file = d / "__init__.py"
        if not init_file.exists():
            init_file.write_text("")

    console.print(f"\n[bold green]KOAN project initialized in {root}[/bold green]")
    console.print("Next steps:")
    console.print("  1. Copy .env.example to .env and add your API keys")
    console.print("  2. Run [bold]koan verify[/bold] to check your setup")
