import time

from bubblecam import events


def test_log_appends_timestamped_lines(sim_env, monkeypatch, tmp_path):
    log_path = tmp_path / "events.log"
    monkeypatch.setenv("BUBBLECAM_EVENTS_LOG", str(log_path))

    events.log("camera", "recording confirmed -- writing seg1.mjpeg")
    events.log("switch", "switch OFF -- stopping recording")

    lines = log_path.read_text().splitlines()
    assert len(lines) == 2
    assert lines[0].endswith("recording confirmed -- writing seg1.mjpeg")
    assert "[camera" in lines[0]
    assert "Z  [" in lines[0]  # UTC-stamped
    assert "[switch" in lines[1]


def test_log_creates_parent_directory(sim_env, monkeypatch, tmp_path):
    log_path = tmp_path / "deep" / "nested" / "events.log"
    monkeypatch.setenv("BUBBLECAM_EVENTS_LOG", str(log_path))
    events.log("watchdog", "system up")
    assert log_path.exists()


def test_log_never_raises_when_storage_hangs(sim_env, monkeypatch, tmp_path):
    """The event log must not be able to wedge the service reporting a
    storage failure -- the card may be the thing that died."""
    monkeypatch.setenv("BUBBLECAM_EVENTS_LOG", str(tmp_path / "events.log"))
    monkeypatch.setattr(events.bounded_io, "DEFAULT_TIMEOUT_SECONDS", 0.1)

    def hang(*args, **kwargs):
        time.sleep(30)

    monkeypatch.setattr("builtins.open", hang)
    started = time.monotonic()
    events.log("watchdog", "STORAGE PROBE FAILED")  # must return, not hang
    assert time.monotonic() - started < 6.0


def test_log_never_raises_on_unwritable_path(sim_env, monkeypatch):
    monkeypatch.setenv("BUBBLECAM_EVENTS_LOG", "/nonexistent-root/events.log")
    events.log("camera", "must not raise")  # swallowed by bounded_io
