from __future__ import annotations

from io import StringIO
from pathlib import Path

from openclaw_lite.config import ConfigManager
from openclaw_lite.interfaces.onboarding import run_terminal_onboarding


def test_run_terminal_onboarding_saves_and_requests_launch(tmp_path: Path) -> None:
    config_path = tmp_path / "config.yaml"
    outputs = StringIO()
    answers = iter([
        "42",
        "-10022",
        "gemini",
        "gemini-2.5-flash",
        "",
    ])
    secrets = iter([
        "123456:TESTTOKEN",
        "gm-key",
    ])

    launched = run_terminal_onboarding(
        str(config_path),
        input_fn=lambda prompt: next(answers),
        secret_fn=lambda prompt: next(secrets),
        stream=outputs,
    )

    reloaded = ConfigManager(config_path)
    assert launched is True
    assert reloaded.get("telegram.bot_token") == "123456:TESTTOKEN"
    assert reloaded.get("telegram.owner_user_ids") == [42]
    assert reloaded.get("telegram.allowed_chat_ids") == [-10022]
    assert reloaded.get("providers.default") == "gemini"
    assert reloaded.get("providers.items.gemini.api_key") == "gm-key"
    assert "LiteClaw onboard" in outputs.getvalue()


def test_run_terminal_onboarding_can_cancel_without_saving(tmp_path: Path) -> None:
    config_path = tmp_path / "config.yaml"
    outputs = StringIO()
    answers = iter([
        "",
        "",
        "",
        "",
        "n",
    ])
    secrets = iter([
        "123456:TESTTOKEN",
        "sk-openai",
    ])

    launched = run_terminal_onboarding(
        str(config_path),
        input_fn=lambda prompt: next(answers),
        secret_fn=lambda prompt: next(secrets),
        stream=outputs,
    )

    reloaded = ConfigManager(config_path)
    assert launched is False
    assert reloaded.get("telegram.bot_token") == ""
    assert reloaded.get("providers.items.openai.api_key") == ""
    assert "cancelled" in outputs.getvalue().lower()
