"""Tests for the single-instance EngineLock."""

from __future__ import annotations

import os
from pathlib import Path

import pytest

from cerbero_bite.runtime.lockfile import EngineLock, LockError


def test_acquire_writes_pid(tmp_path: Path) -> None:
    target = tmp_path / "lockfile"
    with EngineLock(target):
        assert target.exists()
        content = target.read_text(encoding="utf-8").strip()
        assert int(content) == os.getpid()


def test_release_after_with_block(tmp_path: Path) -> None:
    target = tmp_path / "lockfile"
    lock = EngineLock(target)
    with lock:
        pass
    # second acquire must succeed because the previous one was released
    with EngineLock(target):
        pass


def test_second_acquire_blocks(tmp_path: Path) -> None:
    target = tmp_path / "lockfile"
    first = EngineLock(target)
    first.acquire()
    try:
        second = EngineLock(target)
        with pytest.raises(LockError, match="another Cerbero Bite instance"):
            second.acquire()
    finally:
        first.release()


def test_lockfile_directory_is_created(tmp_path: Path) -> None:
    nested = tmp_path / "data" / "nested" / "lockfile"
    with EngineLock(nested):
        assert nested.exists()


def test_release_is_idempotent(tmp_path: Path) -> None:
    target = tmp_path / "lockfile"
    lock = EngineLock(target)
    lock.acquire()
    lock.release()
    lock.release()  # must be a no-op
