from armorer.core import _claim_host_core_singleton, _release_owned_pid_file


def test_claim_host_core_singleton_writes_and_releases_pid_file(tmp_path, monkeypatch):
    config_dir = tmp_path / "armorer-config"
    config_dir.mkdir(parents=True)
    owner_pid = 42424

    monkeypatch.setattr("armorer.core._list_running_host_core_pids", lambda exclude_pid=None: [])
    monkeypatch.setattr("armorer.core._is_pid_alive", lambda pid: pid == owner_pid)

    assert _claim_host_core_singleton(config_dir, pid=owner_pid) is True

    pid_file = config_dir / "core-host.pid"
    assert pid_file.read_text().strip() == str(owner_pid)

    _release_owned_pid_file(pid_file, owner_pid)

    assert not pid_file.exists()


def test_claim_host_core_singleton_reuses_existing_running_pid(tmp_path, monkeypatch):
    config_dir = tmp_path / "armorer-config"
    config_dir.mkdir(parents=True)
    pid_file = config_dir / "core-host.pid"
    pid_file.write_text("51515")

    monkeypatch.setattr("armorer.core._is_pid_alive", lambda pid: pid == 51515)

    assert _claim_host_core_singleton(config_dir, pid=42424) is False
    assert pid_file.read_text().strip() == "51515"


def test_claim_host_core_singleton_reuses_live_process_when_pid_file_missing(tmp_path, monkeypatch):
    config_dir = tmp_path / "armorer-config"
    config_dir.mkdir(parents=True)

    monkeypatch.setattr("armorer.core._list_running_host_core_pids", lambda exclude_pid=None: [61616])
    monkeypatch.setattr("armorer.core._is_pid_alive", lambda pid: False)

    assert _claim_host_core_singleton(config_dir, pid=42424) is False
    assert (config_dir / "core-host.pid").read_text().strip() == "61616"
