from __future__ import annotations

from pathlib import Path

from cf_ontology import pipeline_state_runtime as runtime


class _Proc:
    def __init__(self, returncode: int = 0) -> None:
        self.returncode = returncode


def test_run_engine_does_not_set_direct_override_env_by_default(monkeypatch) -> None:
    captured: dict[str, object] = {}

    def _fake_run(cmd, check=False, env=None):  # noqa: ANN001, ANN202
        captured["cmd"] = cmd
        captured["check"] = check
        captured["env"] = env
        return _Proc(0)

    monkeypatch.setattr(runtime.subprocess, "run", _fake_run)
    code = runtime._run_engine(
        Path("demo.jsonld"),
        steps_paths=[],
        plugin_paths=[],
        exe="cf_pipeline_v2",
    )

    assert code == 0
    assert captured["check"] is False
    assert captured["env"] is None


def test_run_engine_applies_explicit_env_override(monkeypatch) -> None:
    captured: dict[str, object] = {}

    def _fake_run(cmd, check=False, env=None):  # noqa: ANN001, ANN202
        captured["cmd"] = cmd
        captured["check"] = check
        captured["env"] = env
        return _Proc(0)

    monkeypatch.setattr(runtime.subprocess, "run", _fake_run)
    code = runtime._run_engine(
        Path("demo.jsonld"),
        steps_paths=[],
        plugin_paths=[],
        exe="cf_pipeline_v2",
        env_overrides={"CF_ALLOW_DIRECT_ENGINE": "1"},
    )

    assert code == 0
    assert captured["check"] is False
    assert isinstance(captured["env"], dict)
    assert captured["env"]["CF_ALLOW_DIRECT_ENGINE"] == "1"
