"""koan graph — context graph management commands."""

from __future__ import annotations

from pathlib import Path

import typer
from rich.console import Console

console = Console()

graph_app = typer.Typer(help="Context graph management.", no_args_is_help=True)

_SCHEMA_FILE = Path(__file__).resolve().parents[3] / "schema" / "init.cypher"


@graph_app.command("init")
def graph_init_command(
    uri: str = typer.Option(
        "bolt://localhost:7687", "--uri", "-u", help="Graph database URI"
    ),
    username: str = typer.Option("neo4j", "--username", help="Database username"),
    password: str = typer.Option("", "--password", help="Database password"),
    database: str = typer.Option("neo4j", "--database", "-d", help="Database name"),
) -> None:
    """Initialize graph database schema from schema/init.cypher."""
    if not _SCHEMA_FILE.exists():
        console.print(f"[red]Error:[/red] Schema file not found: {_SCHEMA_FILE}")
        raise typer.Exit(code=1)

    schema_text = _SCHEMA_FILE.read_text()
    statements = _parse_cypher_statements(schema_text)

    if not statements:
        console.print("[yellow]No statements found in schema file.[/yellow]")
        raise typer.Exit(code=1)

    try:
        import neo4j  # noqa: PLC0415
    except ImportError:
        console.print(
            "[red]Error:[/red] neo4j driver not installed. "
            "Install with: [bold]pip install koan[graph][/bold]"
        )
        raise typer.Exit(code=1) from None

    console.print(f"[cyan]Connecting to[/cyan] {uri} (database: {database})")

    auth = (username, password) if password else None
    driver = neo4j.GraphDatabase.driver(uri, auth=auth)

    try:
        with driver.session(database=database) as session:
            for stmt in statements:
                session.run(stmt)
                console.print(f"  [green]\u2713[/green] {stmt[:80]}")
    except Exception as exc:
        console.print(f"[red]Error:[/red] {exc}")
        raise typer.Exit(code=1) from None
    finally:
        driver.close()

    console.print(
        f"\n[bold green]Schema initialized successfully "
        f"({len(statements)} statements).[/bold green]"
    )


def _parse_cypher_statements(text: str) -> list[str]:
    """Parse Cypher statements from a file, ignoring comments and blank lines."""
    statements: list[str] = []
    for line in text.splitlines():
        stripped = line.strip()
        if stripped and not stripped.startswith("//"):
            # Remove trailing semicolons for driver compatibility
            statements.append(stripped.rstrip(";"))
    return statements
