from __future__ import annotations

from importlib import metadata
from pathlib import Path
import os
import subprocess
import sys

import cf_pipeline_engine


def test_distribution_metadata_matches_module_version() -> None:
    assert metadata.version("cf-pipeline-engine") == cf_pipeline_engine.__version__


def test_packaged_native_assets_are_present() -> None:
    include_dir = Path(cf_pipeline_engine.cf_engine_include_path())
    assert include_dir.is_dir()
    assert (include_dir / "cf_step_abi.h").is_file()
    assert (include_dir / "cf_step_utils.h").is_file()
    assert (include_dir / "cf_plugin_table.h").is_file()

    assert Path(cf_pipeline_engine.cf_siggen_path()).is_file()
    assert Path(cf_pipeline_engine.cf_pipeline_v2_path()).is_file()
    assert Path(cf_pipeline_engine.cf_type_registry_path()).is_file()


def test_packaged_binaries_respond() -> None:
    siggen = Path(cf_pipeline_engine.cf_siggen_path())
    siggen_result = subprocess.run([str(siggen)], capture_output=True, text=True, check=False)
    siggen_output = f"{siggen_result.stdout}\n{siggen_result.stderr}"
    assert siggen_result.returncode != 0
    assert "Usage: cf_siggen" in siggen_output

    engine = Path(cf_pipeline_engine.cf_pipeline_v2_path())
    env = os.environ.copy()
    env["CF_ALLOW_DIRECT_ENGINE"] = "1"
    engine_result = subprocess.run([str(engine)], env=env, capture_output=True, text=True, check=False)
    engine_output = f"{engine_result.stdout}\n{engine_result.stderr}"
    assert engine_result.returncode == 2
    assert "Usage: cf_pipeline_v2" in engine_output


def test_resolve_executable_prefers_env_override(monkeypatch) -> None:
    monkeypatch.setenv("CF_PIPELINE_V2_EXE", "C:/custom/cf_pipeline_v2.exe")
    assert cf_pipeline_engine.resolve_cf_pipeline_v2_executable() == "C:/custom/cf_pipeline_v2.exe"


def test_cli_module_help_surface() -> None:
    cli_result = subprocess.run(
        [sys.executable, "-m", "cf_pipeline_engine.cli", "--help"],
        capture_output=True,
        text=True,
        check=False,
    )
    output = f"{cli_result.stdout}\n{cli_result.stderr}"
    assert cli_result.returncode == 0
    assert "Run a pipeline using the C++ v2 backend." in output
