"""CLI utility functions shared across commands."""

from __future__ import annotations

import sys
from typing import TYPE_CHECKING

import click

from .constants import CLAUDE_INSTALL_URL

if TYPE_CHECKING:
    from .registry import ModuleStatus, Registry


def require_module(path: str, registry: "Registry") -> "ModuleStatus":
    """Get a module from registry or exit with error.

    Args:
        path: Module path to look up.
        registry: Registry to search.

    Returns:
        ModuleStatus if found.

    Exits with code 1 if module not found.
    """
    module = registry.get(path)
    if module:
        return module

    click.secho(f"Error: {path} not in registry.", fg="red")
    click.echo()

    # Show some available modules to help the user
    available = sorted(registry.modules.keys())
    if available:
        click.echo("Available modules:")
        for mod_path in available[:10]:
            click.echo(f"  {mod_path}")
        if len(available) > 10:
            click.echo(f"  ... and {len(available) - 10} more")
        click.echo()
        click.echo("Run 'glreview sync' to update the registry.")

    sys.exit(1)


def print_dry_run_prompt(prompt: str, title: str = "PROMPT") -> None:
    """Print a prompt in dry-run format.

    Args:
        prompt: The prompt content to display.
        title: Title to show in the header.
    """
    click.echo("=" * 60)
    click.echo(f"{title} (dry-run mode):")
    click.echo("=" * 60)
    click.echo(prompt)
    click.echo("=" * 60)


def require_claude_cli(dry_run: bool = False) -> bool:
    """Check claude CLI is available or exit with helpful message.

    Args:
        dry_run: If True, skip the check (dry-run doesn't need CLI).

    Returns:
        True if available or dry_run=True.

    Exits with code 1 if not available.
    """
    if dry_run:
        return True

    from .claude import claude_available

    if claude_available():
        return True

    click.secho("Error: claude CLI not found.", fg="red")
    click.echo()
    click.echo(f"Install Claude Code from: {CLAUDE_INSTALL_URL}")
    sys.exit(1)
