import pytest
from pathlib import Path

from notilens.state import get_state_file, read_state, write_state, update_state, delete_state


@pytest.fixture
def sf(tmp_path):
    return tmp_path / "notilens_test_agent_task_001.json"


def test_read_missing_returns_empty(sf):
    assert read_state(sf) == {}


def test_write_and_read(sf):
    write_state(sf, {"start_time": 1000, "retry_count": 0})
    state = read_state(sf)
    assert state["start_time"] == 1000
    assert state["retry_count"] == 0


def test_update_state_merges(sf):
    write_state(sf, {"start_time": 1000, "retry_count": 0})
    update_state(sf, {"retry_count": 1, "loop_count": 2})
    state = read_state(sf)
    assert state["start_time"] == 1000   # preserved
    assert state["retry_count"] == 1     # updated
    assert state["loop_count"] == 2      # new key


def test_delete_state(sf):
    write_state(sf, {"x": 1})
    delete_state(sf)
    assert not sf.exists()


def test_delete_state_missing_file(sf):
    delete_state(sf)  # should not raise


def test_get_state_file_no_crash_in_ci(monkeypatch):
    monkeypatch.setenv("USER", "testuser")
    import unittest.mock as mock
    with mock.patch("os.getlogin", side_effect=OSError("no tty")):
        sf = get_state_file("agent", "task")
    assert "notilens" in sf.name
    assert "testuser" in sf.name


def test_read_corrupt_file(sf):
    sf.write_text("not valid json{{")
    assert read_state(sf) == {}
