import json
import os
import signal

from neurovault.daemon import stop_running_daemon


def test_stop_running_daemon_respects_owner_uid(monkeypatch, tmp_path):
    pid_file = tmp_path / "neurovault.pid"
    pid_file.write_text(json.dumps({"pid": 4242, "uid": 999999}))

    called = {"kill": False}

    def fake_kill(_pid: int, _sig: int):
        called["kill"] = True

    import neurovault.daemon as daemon_module

    monkeypatch.setattr(daemon_module, "_pid_file_path", lambda: pid_file)
    monkeypatch.setattr(daemon_module, "_current_uid", lambda: 111111)
    monkeypatch.setattr(daemon_module.os, "kill", fake_kill)

    assert stop_running_daemon() is False
    assert called["kill"] is False


def test_stop_running_daemon_supports_legacy_pid_file(monkeypatch, tmp_path):
    pid_file = tmp_path / "neurovault.pid"
    pid_file.write_text("31337")

    calls: list[tuple[int, int]] = []

    def fake_kill(pid: int, sig: int):
        calls.append((pid, sig))

    import neurovault.daemon as daemon_module

    monkeypatch.setattr(daemon_module, "_pid_file_path", lambda: pid_file)
    monkeypatch.setattr(daemon_module.os, "kill", fake_kill)

    assert stop_running_daemon() is True
    assert calls == [(31337, signal.SIGTERM)]


def test_engine_status_ignores_pid_file_with_foreign_uid(monkeypatch, tmp_path):
    from neurovault.engine import NeurovaultEngine

    vault = NeurovaultEngine.init("test", no_embedding=True, base_dir=str(tmp_path))
    vault.ingest("status pid probe", source="user")

    pid_file = tmp_path / "neurovault.pid"
    pid_file.write_text(json.dumps({"pid": os.getpid(), "uid": 999999}))

    monkeypatch.setattr(NeurovaultEngine, "_pid_file_path", staticmethod(lambda: pid_file))
    status = vault.status
    assert status.daemon_running is False
    assert status.daemon_pid is None
