import sys
import threading

from a2a_agent.updater import auto_update_interval_seconds
from a2a_agent.updater import auto_update_enabled
from a2a_agent.updater import is_newer_version
from a2a_agent.updater import maybe_schedule_auto_update
from a2a_agent.updater import restart_args
from a2a_agent.updater import run_runtime_update_check
from a2a_agent.updater import start_runtime_auto_update_monitor


def test_is_newer_version_compares_numeric_parts() -> None:
    assert is_newer_version("0.1.10", "0.1.9")
    assert not is_newer_version("0.1.4", "0.1.4")
    assert not is_newer_version("0.1.4", "0.1.5")


def test_auto_update_enabled_can_be_disabled(monkeypatch) -> None:
    monkeypatch.setenv("A2A_AUTO_UPDATE", "0")

    assert not auto_update_enabled()


def test_restart_args_uses_module_entrypoint() -> None:
    assert restart_args(["a2a-agent", "run"]) == [
        sys.executable,
        "-m",
        "a2a_agent.cli",
        "run",
    ]


def test_maybe_schedule_auto_update_spawns_when_newer(monkeypatch) -> None:
    monkeypatch.delenv("A2A_AUTO_UPDATE", raising=False)
    monkeypatch.delenv("A2A_UPDATE_RESTARTED", raising=False)
    spawned: list[list[str]] = []

    scheduled = maybe_schedule_auto_update(
        ["a2a-agent", "run"],
        current_version="0.1.4",
        fetch_latest=lambda: "0.1.5",
        editable_install=lambda: False,
        spawn_update=lambda command: spawned.append(list(command)),
    )

    assert scheduled
    assert spawned == [[sys.executable, "-m", "a2a_agent.cli", "run"]]


def test_maybe_schedule_auto_update_skips_after_restart(monkeypatch) -> None:
    monkeypatch.setenv("A2A_UPDATE_RESTARTED", "1")

    assert not maybe_schedule_auto_update(
        ["a2a-agent", "run"],
        current_version="0.1.4",
        fetch_latest=lambda: "0.1.5",
        editable_install=lambda: False,
        spawn_update=lambda command: None,
    )


def test_runtime_update_check_allows_restarted_process(monkeypatch) -> None:
    monkeypatch.delenv("A2A_AUTO_UPDATE", raising=False)
    monkeypatch.setenv("A2A_UPDATE_RESTARTED", "1")
    spawned: list[list[str]] = []
    stop = threading.Event()

    scheduled = run_runtime_update_check(
        stop,
        ["a2a-agent", "run"],
        current_version="0.1.6",
        fetch_latest=lambda: "0.1.7",
        editable_install=lambda: False,
        spawn_update=lambda command: spawned.append(list(command)),
    )

    assert scheduled
    assert stop.is_set()
    assert spawned == [[sys.executable, "-m", "a2a_agent.cli", "run"]]


def test_auto_update_interval_can_disable_runtime_monitor(monkeypatch) -> None:
    monkeypatch.delenv("A2A_AUTO_UPDATE", raising=False)
    monkeypatch.setenv("A2A_UPDATE_INTERVAL_SECONDS", "0")

    assert auto_update_interval_seconds() == 0
    assert start_runtime_auto_update_monitor(threading.Event()) is None
