"""Linux cron replacement watcher contracts."""

from __future__ import annotations

import os
from pathlib import Path

import pytest

from scripts.nutricoach_v150_r71b_cron_watch import (
    CronJobsEventWatcher,
    CronWatchError,
)


def _replace(path: Path, payload: bytes) -> None:
    temporary = path.with_suffix(".next")
    _ = temporary.write_bytes(payload)
    os.replace(temporary, path)


def test_watcher_subscribes_before_jobs_replacement(tmp_path: Path) -> None:
    # Given
    cron = tmp_path / "cron"
    jobs = cron / "jobs.json"
    cron.mkdir(exist_ok=True)
    _ = jobs.write_bytes(b'{"jobs":[]}\n')

    # When
    with CronJobsEventWatcher(cron) as watcher:
        watcher.arm()
        _replace(jobs, b'{"jobs":[{"id":"r71b"}]}\n')
        event = watcher.wait(timeout_seconds=1)

    # Then
    assert event.name == "jobs.json"
    assert event.replacement is True


def test_watcher_rejects_wrong_cron_event(tmp_path: Path) -> None:
    # Given
    cron = tmp_path / "cron"
    cron.mkdir(exist_ok=True)

    # When / Then
    with CronJobsEventWatcher(cron) as watcher:
        watcher.arm()
        _replace(cron / "another.json", b"{}\n")
        with pytest.raises(CronWatchError, match="wrong_event"):
            watcher.wait(timeout_seconds=1)
