from __future__ import annotations

from types import SimpleNamespace

import pytest

from worai import cli as mod
from worai.errors import WoraError


def test_truthy_and_should_check_updates(monkeypatch: pytest.MonkeyPatch) -> None:
    assert mod._is_truthy("true")
    assert mod._is_truthy("1")
    assert not mod._is_truthy("0")
    assert not mod._is_truthy(None)

    ctx = SimpleNamespace(obj={"quiet": False})
    monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)
    monkeypatch.delenv("WORAI_DISABLE_UPDATE_CHECK", raising=False)
    monkeypatch.setattr(mod.sys, "argv", ["worai", "graph"])
    assert mod._should_check_updates(ctx)

    monkeypatch.setenv("WORAI_DISABLE_UPDATE_CHECK", "1")
    assert not mod._should_check_updates(ctx)


def test_emit_update_notice_and_run_error(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(mod, "_should_check_updates", lambda _ctx: True)
    monkeypatch.setattr(mod, "check_for_update", lambda *_a, **_k: SimpleNamespace(update_available=True, latest_version="9.9.9", current_version="1.0.0", upgrade_command=["pip", "install", "-U", "worai"]))
    seen = {}
    monkeypatch.setattr(mod.typer, "secho", lambda msg, **_k: seen.setdefault("msg", msg))
    mod._emit_update_notice(SimpleNamespace(obj={}))
    assert "Update available for worai" in seen["msg"]

    monkeypatch.setattr(mod, "_should_check_updates", lambda _ctx: False)
    mod._emit_update_notice(SimpleNamespace(obj={}))

    monkeypatch.setattr(mod, "app", lambda: (_ for _ in ()).throw(WoraError("boom", exit_code=7)))
    with pytest.raises(SystemExit) as exc:
        mod.run()
    assert exc.value.code == 7
