from __future__ import annotations

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

import cf_pipeline_report


def _script_path(name: str) -> Path:
    python_dir = Path(sys.executable).resolve().parent
    candidate_dirs = (
        python_dir,
        python_dir / "Scripts",
        python_dir.parent / "Scripts",
    )
    candidates = (
        f"{name}.exe",
        f"{name}.cmd",
        f"{name}-script.py",
        name,
    )
    for scripts_dir in candidate_dirs:
        for candidate in candidates:
            path = scripts_dir / candidate
            if path.is_file():
                return path
    raise FileNotFoundError(
        f"{name} console script not found near interpreter {Path(sys.executable).resolve()}"
    )


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


def test_installed_render_console_script_help_surface() -> None:
    result = subprocess.run(
        [str(_script_path("cf-pipeline-report")), "--help"],
        check=False,
        capture_output=True,
        text=True,
    )

    combined_output = f"{result.stdout}\n{result.stderr}"
    assert result.returncode == 0, combined_output
    assert "Render a Cogniflow pipeline report to HTML." in combined_output


def test_installed_server_console_script_help_surface() -> None:
    result = subprocess.run(
        [str(_script_path("cf-pipeline-report-serve")), "--help"],
        check=False,
        capture_output=True,
        text=True,
    )

    combined_output = f"{result.stdout}\n{result.stderr}"
    assert result.returncode == 0, combined_output
    assert "Serve live Cogniflow reports backed by DuckDB." in combined_output
