"""NanoWiki CLI - Main entry point."""

import asyncio
from pathlib import Path
from typing import Optional

import typer
from rich.console import Console
from rich.panel import Panel

app = typer.Typer(
    name="nanowiki",
    help="AI-powered project documentation generator using Claude Agent SDK",
    add_completion=False,
)

console = Console()


@app.command()
def analyze(
    project_path: Path = typer.Argument(
        ...,
        help="Path to the project to analyze",
        exists=True,
        dir_okay=True,
        file_okay=False,
    ),
    force: bool = typer.Option(
        False,
        "--force",
        "-f",
        help="Re-analyze even if .wiki folder already exists",
    ),
    output_dir: Optional[Path] = typer.Option(
        None,
        "--output",
        "-o",
        help="Custom output directory (default: <project_path>/.wiki)",
    ),
) -> None:
    """Analyze a project and generate wiki documentation.

    Example:
        nanowiki analyze ./my-project
        nanowiki analyze ./my-project --force
    """
    console.print(
        Panel(
            f"[bold cyan]NanoWiki[/bold cyan] - Analyzing [bold green]{project_path}[/bold green]",
            title="🔍 Analysis",
            border_style="cyan",
        )
    )

    # Run async analysis
    asyncio.run(_analyze_project(project_path, force, output_dir))


async def _analyze_project(
    project_path: Path,
    force: bool,
    output_dir: Optional[Path],
) -> None:
    """Run the project analysis."""
    wiki_dir = output_dir or (project_path / ".wiki")

    if wiki_dir.exists() and not force:
        console.print(
            f"[yellow]Wiki already exists at {wiki_dir}[/yellow]\n"
            f"Use --force to re-analyze"
        )
        return

    # Import analyzer
    from .agents.analyzer import ProjectAnalyzer

    analyzer = ProjectAnalyzer(project_path)

    # Run analysis
    page_paths = await analyzer.analyze(force=force, wiki_dir=output_dir)

    # Print summary
    wiki_location = output_dir or (project_path / ".wiki")
    console.print(
        f"\n[bold green]✓[/bold green] Generated "
        f"[cyan]{len(page_paths)}[/cyan] wiki pages at [cyan]{wiki_location}[/cyan]"
    )


@app.command()
def serve(
    project_path: Path = typer.Argument(
        ...,
        help="Path to the project with .wiki folder",
        exists=True,
        dir_okay=True,
        file_okay=False,
    ),
    host: str = typer.Option(
        "127.0.0.1",
        "--host",
        "-h",
        help="Host to bind to",
    ),
    port: int = typer.Option(
        8000,
        "--port",
        "-p",
        help="Port to bind to",
    ),
    reload: bool = typer.Option(
        False,
        "--reload",
        help="Enable auto-reload on file changes",
    ),
) -> None:
    """Start the wiki web server.

    Example:
        nanowiki serve ./my-project
        nanowiki serve ./my-project --port 3000
    """
    wiki_dir = project_path / ".wiki"

    if not wiki_dir.exists():
        console.print(
            f"[bold red]Error:[/bold red] No .wiki folder found at {project_path}\n"
            f"Run 'nanowiki analyze {project_path}' first"
        )
        raise typer.Exit(1)

    console.print(
        Panel(
            f"[bold cyan]Starting server...[/bold cyan]\n\n"
            f"Project: [bold green]{project_path}[/bold green]\n"
            f"Wiki: [cyan]{wiki_dir}[/cyan]\n\n"
            f"URL: [bold yellow]http://{host}:{port}[/bold yellow]",
            title="🚀 Serve",
            border_style="cyan",
        )
    )

    # Import here to avoid circular dependency
    from .web.app import start_server

    # Start the server
    start_server(wiki_dir, project_path, host, port, reload)


@app.callback()
def version(
    version: bool = typer.Option(
        False,
        "--version",
        "-v",
        help="Show version and exit",
    ),
) -> None:
    """Show version information."""
    if version:
        from . import __version__

        console.print(f"nanowiki v{__version__}")
        raise typer.Exit()


def main() -> None:
    """Entry point for the CLI."""
    app()


if __name__ == "__main__":
    main()
