from __future__ import annotations

from cf_ontology import pipeline_state_runtime as runtime


def test_find_pipeline_exe_prefers_env_override(monkeypatch) -> None:
    monkeypatch.setenv("CF_PIPELINE_V2_EXE", "C:/custom/cf_pipeline_v2.exe")
    monkeypatch.setattr(runtime, "_find_packaged_pipeline_exe", lambda: "C:/pkg/cf_pipeline_v2.exe")
    monkeypatch.setattr(runtime.shutil, "which", lambda _name: "C:/path/cf_pipeline_v2.exe")
    monkeypatch.setattr(
        runtime,
        "_find_repo_build_pipeline_exe",
        lambda: "C:/repo/build/cf_pipeline_v2.exe",
    )

    assert runtime._find_pipeline_exe() == "C:/custom/cf_pipeline_v2.exe"


def test_find_pipeline_exe_prefers_packaged_path_before_path(monkeypatch) -> None:
    monkeypatch.delenv("CF_PIPELINE_V2_EXE", raising=False)
    monkeypatch.setattr(runtime, "_find_packaged_pipeline_exe", lambda: "C:/pkg/cf_pipeline_v2.exe")
    monkeypatch.setattr(runtime.shutil, "which", lambda _name: "C:/path/cf_pipeline_v2.exe")
    monkeypatch.setattr(
        runtime,
        "_find_repo_build_pipeline_exe",
        lambda: "C:/repo/build/cf_pipeline_v2.exe",
    )

    assert runtime._find_pipeline_exe() == "C:/pkg/cf_pipeline_v2.exe"


def test_find_pipeline_exe_uses_path_before_repo_fallback(monkeypatch) -> None:
    monkeypatch.delenv("CF_PIPELINE_V2_EXE", raising=False)
    monkeypatch.setattr(runtime, "_find_packaged_pipeline_exe", lambda: None)
    monkeypatch.setattr(runtime.shutil, "which", lambda _name: "C:/path/cf_pipeline_v2.exe")
    monkeypatch.setattr(
        runtime,
        "_find_repo_build_pipeline_exe",
        lambda: "C:/repo/build/cf_pipeline_v2.exe",
    )

    assert runtime._find_pipeline_exe() == "C:/path/cf_pipeline_v2.exe"


def test_find_pipeline_exe_uses_repo_fallback_when_path_missing(monkeypatch) -> None:
    monkeypatch.delenv("CF_PIPELINE_V2_EXE", raising=False)
    monkeypatch.setattr(runtime, "_find_packaged_pipeline_exe", lambda: None)
    monkeypatch.setattr(runtime.shutil, "which", lambda _name: None)
    monkeypatch.setattr(
        runtime,
        "_find_repo_build_pipeline_exe",
        lambda: "C:/repo/build/cf_pipeline_v2.exe",
    )

    assert runtime._find_pipeline_exe() == "C:/repo/build/cf_pipeline_v2.exe"


def test_find_pipeline_exe_falls_back_to_binary_name(monkeypatch) -> None:
    monkeypatch.delenv("CF_PIPELINE_V2_EXE", raising=False)
    monkeypatch.setattr(runtime, "_find_packaged_pipeline_exe", lambda: None)
    monkeypatch.setattr(runtime.shutil, "which", lambda _name: None)
    monkeypatch.setattr(runtime, "_find_repo_build_pipeline_exe", lambda: None)

    assert runtime._find_pipeline_exe() == "cf_pipeline_v2"
