"""Tests for fliiq.runtime.update_check."""

import json
import time

from fliiq.runtime import update_check


def test_is_newer():
    assert update_check._is_newer("1.2.0", "1.1.0") is True
    assert update_check._is_newer("1.1.0", "1.1.0") is False
    assert update_check._is_newer("1.0.0", "1.1.0") is False
    assert update_check._is_newer("2.0.0", "1.9.9") is True


def test_is_newer_invalid():
    assert update_check._is_newer("abc", "1.0.0") is False
    assert update_check._is_newer(None, "1.0.0") is False


def test_check_update_cached_no_file(tmp_path, monkeypatch):
    monkeypatch.setattr(update_check, "CACHE_PATH", tmp_path / ".update_cache")
    assert update_check.check_update_cached() is None


def test_check_update_cached_with_update(tmp_path, monkeypatch):
    cache = tmp_path / ".update_cache"
    cache.write_text(json.dumps({"checked_at": time.time(), "latest_version": "9.9.9"}))
    monkeypatch.setattr(update_check, "CACHE_PATH", cache)
    result = update_check.check_update_cached()
    assert result is not None
    assert "9.9.9" in result
    assert "pip install --upgrade fliiq" in result


def test_check_update_cached_no_update(tmp_path, monkeypatch):
    current = update_check.get_current_version()
    cache = tmp_path / ".update_cache"
    cache.write_text(json.dumps({"checked_at": time.time(), "latest_version": current}))
    monkeypatch.setattr(update_check, "CACHE_PATH", cache)
    assert update_check.check_update_cached() is None


def test_check_update_cached_corrupt_file(tmp_path, monkeypatch):
    cache = tmp_path / ".update_cache"
    cache.write_text("not json")
    monkeypatch.setattr(update_check, "CACHE_PATH", cache)
    assert update_check.check_update_cached() is None


def test_trigger_respects_env_var(monkeypatch, tmp_path):
    monkeypatch.setenv("FLIIQ_NO_UPDATE_CHECK", "1")
    monkeypatch.setattr(update_check, "CACHE_PATH", tmp_path / ".update_cache")
    # Should not create any cache file
    update_check.trigger_update_check()
    assert not (tmp_path / ".update_cache").exists()


def test_trigger_skips_fresh_cache(tmp_path, monkeypatch):
    cache = tmp_path / ".update_cache"
    cache.write_text(json.dumps({"checked_at": time.time(), "latest_version": "1.0.0"}))
    monkeypatch.setattr(update_check, "CACHE_PATH", cache)
    monkeypatch.delenv("FLIIQ_NO_UPDATE_CHECK", raising=False)

    fetch_called = []
    monkeypatch.setattr(update_check, "_fetch_latest_version", lambda: fetch_called.append(1) or "1.0.0")

    update_check.trigger_update_check()
    # Fresh cache = no fetch, no thread spawned
    assert len(fetch_called) == 0


def test_cache_is_fresh_stale(tmp_path, monkeypatch):
    cache = tmp_path / ".update_cache"
    cache.write_text(json.dumps({"checked_at": time.time() - 90000, "latest_version": "1.0.0"}))
    monkeypatch.setattr(update_check, "CACHE_PATH", cache)
    assert update_check._cache_is_fresh() is False
