"""Typer CLI entry point for cde-onboard."""

from __future__ import annotations

from typing import Annotated

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

from cde_onboard.constants import APP_NAME, APP_VERSION, TOTAL_LESSONS
from cde_onboard.progress import ProgressManager

app = typer.Typer(
    name=APP_NAME,
    help="Interactive TUI tutorials for onboarding onto ONA Environments.",
    invoke_without_command=True,
    no_args_is_help=False,
)


def version_callback(value: bool) -> None:
    if value:
        typer.echo(f"{APP_NAME} v{APP_VERSION}")
        raise typer.Exit()


@app.callback()
def main(
    lesson: Annotated[
        int | None,
        typer.Option("--lesson", "-l", help="Jump directly to lesson N (0-6)."),
    ] = None,
    list_lessons: Annotated[
        bool,
        typer.Option("--list", help="Print a table of lessons with progress."),
    ] = False,
    reset: Annotated[
        bool,
        typer.Option("--reset", help="Clear all progress and start fresh."),
    ] = False,
    version: Annotated[
        bool,
        typer.Option("--version", "-v", callback=version_callback, is_eager=True),
    ] = False,
) -> None:
    """Launch the ONA onboarding TUI."""
    if reset:
        _handle_reset()
        return

    if list_lessons:
        _handle_list()
        return

    # Validate lesson number if provided
    if lesson is not None and not (0 <= lesson <= TOTAL_LESSONS - 1):
        console = Console()
        console.print(f"[red]Error:[/red] Lesson must be between 0 and {TOTAL_LESSONS - 1}.")
        raise typer.Exit(1)

    # Launch the Textual TUI
    from cde_onboard.app import OnboardApp

    tui = OnboardApp(start_lesson=lesson)
    tui.run()


def _handle_reset() -> None:
    """Clear progress and confirm."""
    console = Console()
    progress = ProgressManager()
    completed = progress.data.total_completed
    progress.reset()
    if completed > 0:
        console.print(f"[green]✓[/green] Cleared progress ({completed} lesson(s) reset).")
    else:
        console.print("[dim]No progress to clear.[/dim]")


def _handle_list() -> None:
    """Print a Rich table of lessons with progress indicators."""
    from cde_onboard.lessons import get_all_lessons

    console = Console()
    progress = ProgressManager()

    table = Table(title="ONA Onboarding Lessons", show_lines=True)
    table.add_column("#", style="bold cyan", width=3)
    table.add_column("Title", style="bold")
    table.add_column("Description")
    table.add_column("Status", justify="center", width=10)

    for cls in get_all_lessons():
        meta = cls.meta()
        done = progress.is_completed(meta.id)
        status = "[green]✓ Done[/green]" if done else "[dim]—[/dim]"
        table.add_row(str(meta.number), meta.title, meta.description, status)

    console.print(table)
    console.print(
        f"\n[bold]{progress.data.total_completed}/{TOTAL_LESSONS}[/bold] lessons completed."
    )
