"""Tests for one-time setup hint in CLI main module."""

from __future__ import annotations

import importlib
from pathlib import Path

main_mod = importlib.import_module("sagellm.cli.main")


class _TTYStdout:
    def isatty(self) -> bool:
        return True


def test_setup_hint_shows_once_and_writes_marker(
    monkeypatch,
    tmp_path: Path,
    capsys,
) -> None:
    marker = tmp_path / ".setup_hint_shown"
    monkeypatch.setattr(main_mod, "SETUP_HINT_MARKER", marker)
    monkeypatch.setattr(main_mod.sys, "stdout", _TTYStdout())
    monkeypatch.delenv("SAGELLM_DISABLE_SETUP_HINT", raising=False)

    main_mod._maybe_show_setup_hint(invoked_subcommand=None)

    assert marker.exists()
    captured = capsys.readouterr()
    assert "sagellm setup" in captured.err


def test_setup_hint_not_shown_when_marker_exists(
    monkeypatch,
    tmp_path: Path,
    capsys,
) -> None:
    marker = tmp_path / ".setup_hint_shown"
    marker.write_text("shown\n", encoding="utf-8")

    monkeypatch.setattr(main_mod, "SETUP_HINT_MARKER", marker)
    monkeypatch.setattr(main_mod.sys, "stdout", _TTYStdout())
    monkeypatch.delenv("SAGELLM_DISABLE_SETUP_HINT", raising=False)

    main_mod._maybe_show_setup_hint(invoked_subcommand=None)

    captured = capsys.readouterr()
    assert captured.err == ""


def test_setup_hint_not_shown_for_setup_subcommand(
    monkeypatch,
    tmp_path: Path,
    capsys,
) -> None:
    marker = tmp_path / ".setup_hint_shown"

    monkeypatch.setattr(main_mod, "SETUP_HINT_MARKER", marker)
    monkeypatch.setattr(main_mod.sys, "stdout", _TTYStdout())
    monkeypatch.delenv("SAGELLM_DISABLE_SETUP_HINT", raising=False)

    main_mod._maybe_show_setup_hint(invoked_subcommand="setup")

    assert not marker.exists()
    captured = capsys.readouterr()
    assert captured.err == ""
