"""koan verify — check API keys and test provider connectivity."""

from __future__ import annotations

import os

import typer
from rich.console import Console
from rich.table import Table

console = Console()


def verify_command() -> None:
    """Check API keys and report provider availability."""
    table = Table(title="KOAN Environment Check")
    table.add_column("Check", style="cyan")
    table.add_column("Status", style="bold")
    table.add_column("Detail")

    # Check OpenAI
    openai_key = os.environ.get("OPENAI_API_KEY", "")
    if openai_key:
        table.add_row("OpenAI API Key", "[green]Found[/green]", f"...{openai_key[-4:]}")
    else:
        table.add_row("OpenAI API Key", "[red]Missing[/red]", "Set OPENAI_API_KEY")

    # Check Anthropic
    anthropic_key = os.environ.get("ANTHROPIC_API_KEY", "")
    if anthropic_key:
        table.add_row("Anthropic API Key", "[green]Found[/green]", f"...{anthropic_key[-4:]}")
    else:
        table.add_row("Anthropic API Key", "[red]Missing[/red]", "Set ANTHROPIC_API_KEY")

    # Check optional packages
    _check_package(table, "openai", "OpenAI SDK")
    _check_package(table, "anthropic", "Anthropic SDK")
    _check_package(table, "mcp", "MCP SDK")
    _check_package(table, "neo4j", "Neo4j Driver")
    _check_package(table, "chromadb", "ChromaDB")

    console.print(table)

    if not openai_key and not anthropic_key:
        console.print(
            "\n[yellow]Warning:[/yellow] No API keys found. "
            "Set OPENAI_API_KEY or ANTHROPIC_API_KEY to use LLM features."
        )
        raise typer.Exit(code=1)


def _check_package(table: Table, module_name: str, display_name: str) -> None:
    """Check if a Python package is importable."""
    try:
        __import__(module_name)
        table.add_row(display_name, "[green]Installed[/green]", "")
    except ImportError:
        table.add_row(display_name, "[dim]Not installed[/dim]", "Optional")
