import json
import time

from fenrirscreenreader.core import remoteInstanceRegistry


def test_write_instance_prunes_stale_registry_files(tmp_path, monkeypatch):
    monkeypatch.setattr(
        remoteInstanceRegistry, "get_registry_dir", lambda: str(tmp_path)
    )
    monkeypatch.setattr(
        remoteInstanceRegistry,
        "process_exists",
        lambda pid: pid == 456,
    )

    stale_instance = tmp_path / "123.json"
    stale_instance.write_text(
        json.dumps(
            {
                "pid": 123,
                "updated_at": time.time(),
            }
        )
        + "\n",
        encoding="utf-8",
    )
    invalid_instance = tmp_path / "invalid.json"
    invalid_instance.write_text("not json\n", encoding="utf-8")

    remoteInstanceRegistry.write_instance({"pid": 456})

    assert not stale_instance.exists()
    assert not invalid_instance.exists()
    assert (tmp_path / "456.json").exists()
