"""Post-install getting-started guidance panel."""

from __future__ import annotations

from dataclasses import dataclass

from ilum.cli.output import _SYM_CHECK, IlumConsole
from ilum.core.modules import MODULE_REGISTRY


@dataclass(frozen=True)
class GuidanceContext:
    """Data needed to render the getting-started panel."""

    modules: list[str]
    release: str
    namespace: str
    command: str  # "quickstart" | "install" | "connect"


# Modules to suggest for ``ilum access open`` examples, in priority order.
_WEB_PRIORITY: tuple[str, ...] = ("jupyter", "airflow", "grafana", "superset", "mlflow")

# Interesting modules to suggest enabling when not yet active.
_SUGGEST_ENABLE: tuple[str, ...] = (
    "jupyter",
    "airflow",
    "monitoring",
    "superset",
    "mlflow",
    "trino",
)

_DOCS_URL = "https://ilum.cloud/docs/cli/overview/"

_MODULE_MAP = {m.name: m for m in MODULE_REGISTRY}


def show_getting_started(console: IlumConsole, ctx: GuidanceContext) -> None:
    """Build and display a Rich panel with contextual getting-started guidance."""
    if console.output_format != "table":
        return

    lines: list[str] = []
    enabled = set(ctx.modules)

    # Header
    if ctx.command == "connect":
        lines.append(
            f"[bold]Connected to release '{ctx.release}' with {len(ctx.modules)} modules[/bold]"
        )
    else:
        lines.append(f"[bold]Ilum is running with {len(ctx.modules)} modules[/bold]")

    lines.append("")

    # Open the UI
    lines.append(f"  {_SYM_CHECK} Open the UI:           [bold]ilum access open[/bold]")

    # Web services (show up to 2 from priority list)
    web_modules = [m for m in _WEB_PRIORITY if m in enabled and _MODULE_MAP.get(m)]
    shown = 0
    for mod_name in web_modules:
        mod = _MODULE_MAP[mod_name]
        if mod.console_path and shown < 2:
            lines.append(f"    [dim]{mod.description} available at UI[/dim]")
            shown += 1

    # Check health
    lines.append(f"  {_SYM_CHECK} Check health:          [bold]ilum status[/bold]")
    lines.append("    [dim]Run diagnostics:       ilum doctor[/dim]")

    # Manage modules
    lines.append(f"  {_SYM_CHECK} Manage modules:        [bold]ilum module list[/bold]")
    suggestion = _suggest_module(enabled)
    if suggestion:
        lines.append(f"    [dim]Try:                   ilum module enable {suggestion}[/dim]")

    # View logs
    lines.append(f"  {_SYM_CHECK} View logs:             [bold]ilum logs core[/bold]")

    # Docs link
    lines.append("")
    lines.append(f"  [dim]Docs: {_DOCS_URL}[/dim]")

    console.panel("\n".join(lines), title="Getting Started")


def _suggest_module(enabled: set[str]) -> str:
    """Return a single interesting module name that is not yet enabled."""
    for name in _SUGGEST_ENABLE:
        if name not in enabled:
            return name
    return ""
