import importlib.util
import sys
from pathlib import Path

import pytest

REPO_ROOT = Path(__file__).resolve().parent.parent
BUBBLECAM_LIB = REPO_ROOT / "opt" / "bubblecam"

if str(BUBBLECAM_LIB) not in sys.path:
    sys.path.insert(0, str(BUBBLECAM_LIB))


@pytest.fixture
def sim_env(tmp_path, monkeypatch):
    """Point every BubbleCam module at an isolated tmp_path and simulate mode.

    state_lib/reboot_guard read their target paths fresh on every call
    (not a module-level constant), so this works with a plain monkeypatch
    -- no importlib.reload dance needed, and no cross-test leakage.
    """
    state_dir = tmp_path / "run"
    data_dir = tmp_path / "data"
    monkeypatch.setenv("BUBBLECAM_SIM", "1")
    monkeypatch.setenv("BUBBLECAM_STATE_DIR", str(state_dir))
    monkeypatch.setenv("BUBBLECAM_REBOOT_COUNTER", str(data_dir / "reboot_attempts.count"))
    monkeypatch.setenv("BUBBLECAM_CONFIG", str(tmp_path / "nonexistent-bubblecam.toml"))
    monkeypatch.setenv("BUBBLECAM_EVENTS_LOG", str(data_dir / "events.log"))
    return {"tmp_path": tmp_path, "state_dir": state_dir, "data_dir": data_dir}


def load_bin_module(name: str):
    """Import one of opt/bubblecam/bin/*.py by path (they're entry-point
    scripts, not a package, so they aren't importable via `import` directly)."""
    path = BUBBLECAM_LIB / "bin" / f"{name}.py"
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module
