"""Interactive CLI setup wizard using questionary.

When the user runs ``staso setup`` without flags, this module presents
a beautiful arrow-key-driven experience for selecting the target agent
and entering configuration values.
"""
from __future__ import annotations

import os
import sys
from typing import Any

import questionary
from questionary import Style

# -- theme ---------------------------------------------------------------------

STASO_STYLE = Style([
    ("qmark", "fg:ansicyan bold"),
    ("question", "bold"),
    ("answer", "fg:ansicyan bold"),
    ("pointer", "fg:ansicyan bold"),
    ("highlighted", "fg:ansicyan bold"),
    ("selected", "fg:ansicyan"),
    ("separator", "fg:ansibrightblack"),
    ("instruction", "fg:ansibrightblack"),
    ("text", ""),
    ("disabled", "fg:ansibrightblack italic"),
])


# -- agent registry for interactive display ------------------------------------

# Each entry: (display_name, cli_name, description, available)
# This is the single place to add new integrations — the wizard auto-discovers.
AGENT_CHOICES: list[dict[str, Any]] = [
    {
        "name": "Claude Code  —  Anthropic's CLI coding agent",
        "value": "claude-code",
    },
    {
        "name": "Codex        —  OpenAI's CLI coding agent",
        "value": "codex",
    },
]


# -- validators ----------------------------------------------------------------


def _validate_api_key(text: str) -> bool | str:
    text = text.strip()
    if not text:
        return "API key is required. Get yours at https://staso.ai"
    if not text.startswith("ak_"):
        return "API key must start with 'ak_'"
    if len(text) < 10:
        return "API key is too short"
    return True


def _validate_optional(_text: str) -> bool:
    return True


# -- wizard --------------------------------------------------------------------


def interactive_setup() -> dict[str, str] | None:
    """Run the interactive setup wizard.

    Returns a dict with keys: target, api_key, workspace, environment,
    agent_id, scope, auto_sync.  Returns None if the user cancels (Ctrl-C).
    """
    print()
    print("  \033[1m\033[96mStaso\033[0m — setup wizard")
    print("  \033[90mConfigure tracing for your CLI AI agent.\033[0m")
    print()

    # 1. Select agent
    target = questionary.select(
        "Which agent do you want to trace?",
        choices=AGENT_CHOICES,
        style=STASO_STYLE,
        qmark="→",
        instruction="(use arrow keys)",
    ).ask()

    if target is None:
        return None

    # 2. API key (required)
    env_key = os.environ.get("STASO_API_KEY", "")
    api_key = questionary.text(
        "Staso API key",
        default=env_key,
        validate=_validate_api_key,
        style=STASO_STYLE,
        qmark="→",
        instruction="(required — get yours at staso.ai)",
    ).ask()

    if api_key is None:
        return None

    # 3. Workspace
    workspace = questionary.text(
        "Workspace slug",
        default="default",
        validate=_validate_optional,
        style=STASO_STYLE,
        qmark="→",
        instruction="(default: default)",
    ).ask()

    if workspace is None:
        return None

    # 4. Environment
    environment = questionary.text(
        "Environment",
        default="default",
        validate=_validate_optional,
        style=STASO_STYLE,
        qmark="→",
        instruction="(default: default)",
    ).ask()

    if environment is None:
        return None

    # 5. Agent ID (optional)
    default_agent_id = target  # use agent name as default
    agent_id = questionary.text(
        "Agent ID",
        default=default_agent_id,
        validate=_validate_optional,
        style=STASO_STYLE,
        qmark="→",
        instruction="(optional — shown on dashboard)",
    ).ask()

    if agent_id is None:
        return None

    # 6. Scope
    scope = questionary.select(
        "Scope",
        choices=[
            {"name": "Global   —  trace all sessions on this machine", "value": "global"},
            {"name": "Project  —  trace only in the current directory", "value": "project"},
        ],
        style=STASO_STYLE,
        qmark="→",
        instruction="(use arrow keys)",
    ).ask()

    if scope is None:
        return None

    # 7. Auto-sync
    auto_sync = questionary.confirm(
        "Enable auto-sync?",
        default=True,
        style=STASO_STYLE,
        qmark="→",
        instruction="(auto-update hooks on each session start)",
    ).ask()

    if auto_sync is None:
        return None

    return {
        "target": target,
        "api_key": api_key.strip(),
        "workspace": workspace.strip(),
        "environment": environment.strip(),
        "agent_id": agent_id.strip(),
        "scope": scope,
        "auto_sync": auto_sync,
    }
