"""One-time first-run onboarding for bare `armorer` invocations."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Callable

from armorer.config import ConfigManager, resolve_armorer_config_dir

MARKER_FILENAME = "first_run_setup_completed.json"


def first_run_marker_path(config_dir: Path | None = None) -> Path:
    base = Path(config_dir) if config_dir is not None else resolve_armorer_config_dir()
    return base / MARKER_FILENAME


def is_first_run_setup_complete(config_dir: Path | None = None) -> bool:
    path = first_run_marker_path(config_dir)
    if not path.is_file():
        return False
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
        return bool(data.get("completed"))
    except Exception:
        return False


def mark_first_run_setup_complete(config_dir: Path | None = None) -> None:
    base = Path(config_dir) if config_dir is not None else resolve_armorer_config_dir()
    base.mkdir(parents=True, exist_ok=True)
    path = base / MARKER_FILENAME
    path.write_text(json.dumps({"completed": True}, indent=2), encoding="utf-8")


def run_first_run_onboarding(
    *,
    config_impl: Callable[[], None],
    config_dir: Path | None = None,
) -> bool:
    """Run interactive onboarding; return True if user completed required steps.

    Required completion: MODEL_PROVIDER must be set after config flow returns.
    """
    from armorer.cli import common as cli_common

    cli_common.console.print(
        "[bold]Welcome to Armorer.[/bold] Complete initial setup (model provider) to continue."
    )
    try:
        config_impl()
    except KeyboardInterrupt:
        return False

    cm = ConfigManager()
    if not (cm.get_key("MODEL_PROVIDER") or "").strip():
        cli_common.console.print(
            "[yellow]Initial setup incomplete: choose [bold]Change Model[/bold] and a provider to finish.[/yellow]"
        )
        return False

    mark_first_run_setup_complete(config_dir)
    return True
