from __future__ import annotations

import json
import os
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from chekan.store import Run, is_pid_alive


def test_is_pid_alive_current() -> None:
    assert is_pid_alive(os.getpid()) is True
    assert is_pid_alive(-1) is False
    assert is_pid_alive(99999999) is False


def test_state_backup_and_recovery(tmp_path: Path) -> None:
    run = Run.create(tmp_path, "Прогон для теста бэкапа", "auto", "T1")
    bak_path = run.state_path.with_suffix(".json.bak")

    # Mutate to trigger backup creation
    with run.mutate() as st:
        st["mode"] = "normal"

    assert bak_path.is_file()
    bak_data = json.loads(bak_path.read_text(encoding="utf-8"))
    assert bak_data["title"] == "Прогон для теста бэкапа"

    # Corrupt state.json and test recovery from .bak
    run.state_path.write_text("corrupted json content", encoding="utf-8")
    run._state = None
    loaded_state = run.state
    assert loaded_state["title"] == "Прогон для теста бэкапа"


def test_stale_lock_recovery(tmp_path: Path) -> None:
    run = Run.create(tmp_path, "Тест stale замка", "auto", "T1")
    lock_file = run.dir / ".lock"
    # Write a non-existent PID to lock file
    lock_file.write_text("99999999\n", encoding="utf-8")

    # Should safely acquire lock despite stale pid
    with run.mutate() as st:
        st["mode"] = "normal"

    assert run.state["mode"] == "normal"
