"""SecAgent configuration — first-run setup wizard and persistent config."""

from __future__ import annotations

import json
import os
from pathlib import Path

from rich.align import Align
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt
from rich.text import Text

from secagent.llm.grok_client import _DEFAULT_FAST_MODEL as DEFAULT_FAST_MODEL
from secagent.llm.grok_client import _DEFAULT_MODEL as DEFAULT_MODEL

# ── ASCII banner ──────────────────────────────────────────────────────────────

_BANNER_ART = """\
 ███████╗███████╗ ██████╗ █████╗  ██████╗ ███████╗███╗  ██╗████████╗
 ██╔════╝██╔════╝██╔════╝██╔══██╗██╔════╝ ██╔════╝████╗ ██║╚══██╔══╝
 ███████╗█████╗  ██║     ███████║██║  ███╗█████╗  ██╔██╗██║   ██║
 ╚════██║██╔══╝  ██║     ██╔══██║██║   ██║██╔══╝  ██║╚████║   ██║
 ███████║███████╗╚██████╗██║  ██║╚██████╔╝███████╗██║ ╚███║   ██║
 ╚══════╝╚══════╝ ╚═════╝╚═╝  ╚═╝ ╚═════╝ ╚══════╝╚═╝  ╚══╝   ╚═╝  """

# ── Config path ───────────────────────────────────────────────────────────────


def get_config_path() -> Path:
    """Return the path for the config file (~/.secagent/config.json on all platforms)."""
    return Path.home() / ".secagent" / "config.json"


# ── Config I/O ────────────────────────────────────────────────────────────────


def load_config() -> dict | None:
    """Return parsed config dict, or ``None`` if the config file does not exist."""
    path = get_config_path()
    if not path.is_file():
        return None
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError):
        return None


def save_config(
    api_key: str,
    model: str = DEFAULT_MODEL,
    fast_model: str = DEFAULT_FAST_MODEL,
) -> Path:
    """Write config to disk and return the path written to."""
    path = get_config_path()
    path.parent.mkdir(parents=True, exist_ok=True)
    config = {
        "grok_api_key": api_key,
        "grok_model": model,
        "grok_fast_model": fast_model,
    }
    path.write_text(json.dumps(config, indent=2), encoding="utf-8")
    return path


def apply_config_to_env(config: dict) -> None:
    """Inject config values into ``os.environ`` so existing code stays unchanged."""
    if "grok_api_key" in config:
        os.environ.setdefault("GROK_API_KEY", config["grok_api_key"])
    if "grok_model" in config:
        os.environ.setdefault("GROK_MODEL", config["grok_model"])
    if "grok_fast_model" in config:
        os.environ.setdefault("GROK_FAST_MODEL", config["grok_fast_model"])


def is_first_run() -> bool:
    """Return ``True`` if no config file exists yet."""
    return not get_config_path().is_file()


# ── Welcome banner ────────────────────────────────────────────────────────────


def show_welcome_banner(console: Console) -> None:
    """Render the first-run welcome banner."""
    from secagent import __version__

    art = Text(_BANNER_ART, style="bold magenta")
    meta = Text.assemble(
        "\n",
        ("  Autonomous AI Security Agent", "bold white"),
        ("  ", ""),
        (f"v{__version__}", "dim"),
        "\n",
        ("  Scans, verifies, and auto-fixes security vulnerabilities\n", "dim"),
        ("                  Powered by xAI Grok\n", "cyan"),
    )
    content = Align.center(Text.assemble(art, meta))
    console.print()
    console.print(Panel(content, border_style="bold magenta", padding=(1, 2)))
    console.rule("[bold magenta]First-Time Setup[/]")
    console.print()


# ── Setup wizard ──────────────────────────────────────────────────────────────


def run_setup_wizard(console: Console) -> dict:
    """Interactively collect the Grok API key, save config, and return it."""
    show_welcome_banner(console)

    console.print("[bold]Welcome to SecAgent![/]")
    console.print(
        "To get started, enter your [bold cyan]xAI Grok API key[/].\n"
        "[dim]Get one at: https://console.x.ai/[/]\n"
    )

    while True:
        key = Prompt.ask("[cyan]Grok API Key[/]", password=True)
        if not key:
            console.print("[bold red]API key cannot be empty. Please try again.[/]\n")
            continue
        if not key.startswith("xai-"):
            console.print(
                "[bold red]Invalid key — must start with 'xai-'. Please try again.[/]\n"
            )
            continue
        break

    config_path = save_config(key)
    console.print(
        f"\n[bold green]Setup complete![/] "
        f"Config saved to: [dim]{config_path}[/]\n"
    )

    config = load_config()
    assert config is not None  # we just wrote it
    return config
