from __future__ import annotations

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

import cf_opcua_server


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


def test_distribution_metadata_matches_module_version() -> None:
    assert metadata.version("cf-opcua-server") == cf_opcua_server.__version__


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

    combined_output = f"{result.stdout}\n{result.stderr}"
    assert result.returncode == 0, combined_output
    assert "Cogniflow virtual OPC-UA server" in combined_output
