"""Help screens and argparse utilities for the CLI.

This module is imported at CLI startup to wire `-h` actions into the
argparse tree.  It must stay lightweight — no SDK or langchain imports.
"""

from rich.markup import escape

from deepagents_cli._version import DOCS_URL, __version__
from deepagents_cli.config import (
    COLORS,
    _get_editable_install_path,
    _is_editable_install,
    console,
)

_JSON_OPTION_LINE = "  --json                  Emit machine-readable JSON"
_HELP_OPTION_LINE = "  -h, --help              Show this help message"


def _print_option_section(*lines: str, title: str = "Options") -> None:
    """Print a help-screen options section with shared JSON/help flags.

    Args:
        *lines: Command-specific option lines to print before the shared flags.
        title: Section title to display.
    """
    console.print(f"[bold]{title}:[/bold]", style=COLORS["primary"])
    for line in lines:
        console.print(line)
    console.print(_JSON_OPTION_LINE)
    console.print(_HELP_OPTION_LINE)


def show_help() -> None:
    """Show top-level help information for the deepagents CLI."""
    editable_path = _get_editable_install_path()
    install_type = f" (local: {escape(editable_path)})" if editable_path else ""
    banner_color = (
        COLORS["primary_dev"] if _is_editable_install() else COLORS["primary"]
    )
    console.print()
    console.print(
        f"[bold {banner_color}]cxcoast-agent[/bold {banner_color}]"
        f" v{__version__}{install_type}"
    )
    console.print()
    console.print(
        f"Docs: [link={DOCS_URL}]{DOCS_URL}[/link]",
        style=COLORS["dim"],
    )
    console.print()

    console.print("[bold]Getting Started:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent login                            Login with your CXCoast account")
    console.print("  cxcoast-agent status                           Check connection status")
    console.print("  cxcoast-agent logout                           Logout and revoke API key")
    console.print()

    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print(
        "  cxcoast-agent [OPTIONS]                        Start interactive session"
    )
    console.print(
        "  cxcoast-agent list                             List all available agents"
    )
    console.print(
        "  cxcoast-agent reset --agent AGENT [--target SRC]  Reset an agent's prompt"
    )
    console.print(
        "  cxcoast-agent skills <list|create|info|delete>    Manage agent skills"
    )
    console.print(
        "  cxcoast-agent threads <list|delete>                Manage conversation threads"
    )
    console.print()

    console.print("[bold]Options:[/bold]", style=COLORS["primary"])
    console.print(
        "  -r, --resume [ID]          Resume thread: -r for most recent, -r ID for specific"  # noqa: E501
    )
    console.print("  -a, --agent NAME           Agent to use")
    console.print("  -M, --model MODEL          Model to use (e.g., openai:gpt-4o)")
    console.print(
        "  --model-params JSON        Extra model kwargs (e.g., '{\"temperature\": 0.7}')"  # noqa: E501
    )
    console.print("  -m, --message TEXT         Initial prompt to auto-submit on start")
    console.print(
        "  -y, --auto-approve         Auto-approve all tool calls (toggle: Shift+Tab)"
    )
    console.print(
        "  --mcp-config PATH          Load MCP tools from config file"
    )
    console.print("  --no-mcp                   Disable all MCP tool loading")
    console.print("  -n, --non-interactive MSG  Run a single task and exit")
    console.print("  -q, --quiet                Clean output for piping (needs -n)")
    console.print(
        "  -S, --shell-allow-list CMDS  Comma-separated cmds, 'recommended', or 'all'"
    )
    console.print("  --default-model [MODEL]    Set, show, or manage the default model")
    console.print(
        "  --update                   Check for and install updates, then exit"
    )
    console.print("  -v, --version              Show cxcoast-agent and SDK versions")
    console.print("  -h, --help                 Show this help message and exit")
    console.print()

    console.print("[bold]Non-Interactive Mode:[/bold]", style=COLORS["primary"])
    console.print(
        "  cxcoast-agent -n 'Search refund policy'        # Single query",
        style=COLORS["dim"],
    )
    console.print(
        "  cxcoast-agent -n 'List all articles' -q         # Pipe-friendly output",
        style=COLORS["dim"],
    )
    console.print()


def show_list_help() -> None:
    """Show help information for the `list` subcommand.

    Invoked via the `-h` argparse action or directly from `cli_main`.
    """
    console.print()
    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent list [options]")
    console.print()
    console.print(
        "List all agents found in ~/.cxcoast/. Each agent has its own",
    )
    console.print(
        "AGENTS.md system prompt and separate thread history.",
    )
    console.print()
    _print_option_section()
    console.print()


def show_reset_help() -> None:
    """Show help information for the `reset` subcommand."""
    console.print()
    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent reset --agent NAME [--target SRC]")
    console.print()
    console.print(
        "Restore an agent's AGENTS.md to the built-in default, or copy",
    )
    console.print(
        "another agent's AGENTS.md. This deletes the agent's directory",
    )
    console.print(
        "and recreates it with the new prompt.",
    )
    console.print()
    _print_option_section(
        "  --agent NAME            Agent to reset (required)",
        "  --target SRC            Copy AGENTS.md from another agent instead",
    )
    console.print()
    console.print("[bold]Examples:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent reset --agent coder")
    console.print("  cxcoast-agent reset --agent coder --target researcher")
    console.print()


def show_skills_help() -> None:
    """Show help information for the `skills` subcommand.

    Invoked via the `-h` argparse action or directly from
    `execute_skills_command` when no subcommand is given.
    """
    console.print()
    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent skills <command> [options]")
    console.print()
    console.print("[bold]Commands:[/bold]", style=COLORS["primary"])
    console.print("  list|ls           List all available skills")
    console.print("  create <name>     Create a new skill")
    console.print("  info <name>       Show detailed information about a skill")
    console.print("  delete <name>     Delete a skill")
    console.print()
    _print_option_section(
        "  --agent <name>    Specify agent identifier (default: agent)",
        "  --project         Use project-level skills instead of user-level",
        title="Common options",
    )
    console.print()
    console.print("[bold]Examples:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent skills list")
    console.print("  cxcoast-agent skills list --project")
    console.print("  cxcoast-agent skills create my-skill")
    console.print("  cxcoast-agent skills create my-skill --agent myagent")
    console.print("  cxcoast-agent skills info my-skill")
    console.print("  cxcoast-agent skills delete my-skill")
    console.print("  cxcoast-agent skills delete my-skill --force --project")
    console.print("  cxcoast-agent skills delete -h")
    console.print()
    console.print(
        "[bold]Skill directories (highest precedence first):[/bold]",
        style=COLORS["primary"],
    )
    console.print(
        "  1. .agents/skills/                 project skills\n"
        "  2. .cxcoast/skills/             project skills (alias)\n"
        "  3. ~/.agents/skills/               user skills\n"
        "  4. ~/.cxcoast/<agent>/skills/   user skills (alias)\n"
        "  5. <package>/built_in_skills/      built-in skills",
    )
    console.print()


def show_skills_list_help() -> None:
    """Show help information for the `skills list` subcommand."""
    console.print()
    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent skills list [options]")
    console.print()
    _print_option_section(
        "  --agent NAME            Agent identifier (default: agent)",
        "  --project               Show only project-level skills",
    )
    console.print()


def show_skills_create_help() -> None:
    """Show help information for the `skills create` subcommand."""
    console.print()
    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent skills create <name> [options]")
    console.print()
    _print_option_section(
        "  --agent NAME            Agent identifier (default: agent)",
        "  --project               Create in project directory "
        "instead of user directory",
    )
    console.print()
    console.print("[bold]Examples:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent skills create web-research")
    console.print("  cxcoast-agent skills create my-skill --project")
    console.print()


def show_skills_info_help() -> None:
    """Show help information for the `skills info` subcommand."""
    console.print()
    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent skills info <name> [options]")
    console.print()
    _print_option_section(
        "  --agent NAME            Agent identifier (default: agent)",
        "  --project               Search only in project skills",
    )
    console.print()


def show_skills_delete_help() -> None:
    """Show help information for the `skills delete` subcommand."""
    console.print()
    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent skills delete <name> [options]")
    console.print()
    _print_option_section(
        "  --agent NAME            Agent identifier (default: agent)",
        "  --project               Search only in project skills",
        "  -f, --force             Skip confirmation prompt",
    )
    console.print()
    console.print("[bold]Examples:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent skills delete old-skill")
    console.print("  cxcoast-agent skills delete old-skill --force")
    console.print("  cxcoast-agent skills delete old-skill --project")
    console.print()


def show_threads_help() -> None:
    """Show help information for the `threads` subcommand.

    Invoked via the `-h` argparse action or directly from `cli_main`
    when no threads subcommand is given.
    """
    console.print()
    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent threads <command> [options]")
    console.print()
    console.print("[bold]Commands:[/bold]", style=COLORS["primary"])
    console.print("  list|ls           List all threads")
    console.print("  delete <ID>       Delete a thread")
    console.print()
    _print_option_section()
    console.print()
    console.print("[bold]Examples:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent threads list")
    console.print("  cxcoast-agent threads list -n 10")
    console.print("  cxcoast-agent threads list --agent mybot")
    console.print("  cxcoast-agent threads delete abc123")
    console.print()


def show_threads_delete_help() -> None:
    """Show help information for the `threads delete` subcommand."""
    console.print()
    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent threads delete <ID> [options]")
    console.print()
    _print_option_section()
    console.print()
    console.print("[bold]Examples:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent threads delete abc123")
    console.print()


def show_threads_list_help() -> None:
    """Show help information for the `threads list` subcommand."""
    console.print()
    console.print("[bold]Usage:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent threads list [options]")
    console.print()
    _print_option_section(
        "  --agent NAME              Filter by agent name",
        "  --branch TEXT             Filter by git branch name",
        "  --sort {created,updated}  Sort order (default: from config, or updated)",
        "  -n, --limit N             Maximum threads to display (default: 20)",
        "  -v, --verbose             Show all columns (branch, created, prompt)",
        "  -r, --relative/--no-relative"
        "  Show relative timestamps (default: from config)",
    )
    console.print()
    console.print("[bold]Examples:[/bold]", style=COLORS["primary"])
    console.print("  cxcoast-agent threads list")
    console.print("  cxcoast-agent threads list -n 10")
    console.print("  cxcoast-agent threads list --agent mybot")
    console.print("  cxcoast-agent threads list --branch main -v")
    console.print("  cxcoast-agent threads list --sort created --limit 50")
    console.print("  cxcoast-agent threads list -r")
    console.print()
