#!/usr/bin/env bash
set -euo pipefail

if [[ "$(uname -s)" == "Linux" && "$(uname -m)" == "x86_64" ]]; then
  export CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=/usr/bin/cc
  export CC_x86_64_unknown_linux_gnu=/usr/bin/cc
  export CXX_x86_64_unknown_linux_gnu=/usr/bin/c++
fi

if [[ $# -ne 2 ]]; then
  echo "usage: scripts/smoke-dist ARTIFACT_DIRECTORY VERSION" >&2
  exit 2
fi

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
artifact_dir="$(cd "$1" && pwd)"
version="$2"
wheel="$(
  uv run --no-project --with packaging==26.2 python - "$artifact_dir" <<'PY'
import sys
from pathlib import Path

from packaging.tags import sys_tags
from packaging.utils import parse_wheel_filename

artifact_dir = Path(sys.argv[1])
compatible_tags = set(sys_tags())
compatible_wheels = []
for wheel in artifact_dir.glob("*.whl"):
    _name, _version, _build, tags = parse_wheel_filename(wheel.name)
    if tags & compatible_tags:
        compatible_wheels.append(wheel)
if len(compatible_wheels) != 1:
    raise SystemExit(
        f"expected one wheel compatible with this host, found {len(compatible_wheels)}"
    )
print(compatible_wheels[0])
PY
)"
sdist="$(find "$artifact_dir" -maxdepth 1 -type f -name '*.tar.gz' -print -quit)"
if [[ -z "$wheel" || -z "$sdist" ]]; then
  echo "artifact directory must contain a wheel and source distribution" >&2
  exit 2
fi

smoke_root="$(mktemp -d)"
trap 'rm -rf "$smoke_root"' EXIT
mkdir "$smoke_root/run"

for python_version in 3.10 3.11 3.12 3.13 3.14; do
  wheel_env="$smoke_root/wheel-$python_version"
  uv venv --python "$python_version" "$wheel_env"
  wheel_python="$wheel_env/bin/python"
  uv pip install --python "$wheel_python" "$wheel"
  (
    cd "$smoke_root/run"
    "$wheel_python" -I "$repo_root/scripts/smoke_installed.py" "$version"
    "$wheel_env/bin/foamwiki" --help >/dev/null
    "$wheel_python" -I -m foamwiki --help >/dev/null
  )
done

uv venv --python 3.14 "$smoke_root/sdist-env"
sdist_python="$smoke_root/sdist-env/bin/python"
uv pip install --python "$sdist_python" "$sdist"
(
  cd "$smoke_root/run"
  "$sdist_python" -I "$repo_root/scripts/smoke_installed.py" "$version"
  "$smoke_root/sdist-env/bin/foamwiki" --help >/dev/null
)
