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

repo="${1:-pypi}"
tag="${2:-${RELEASE_TAG:-}}"
if [ -z "$tag" ]; then
  echo "usage: scripts/release/build <pypi|testpypi> vX.Y.Z" >&2
  exit 1
fi

version="${tag#v}"
if [ "$version" = "$tag" ]; then
  echo "expected v-prefixed tag, got: $tag" >&2
  exit 1
fi

if ! git rev-parse -q --verify "refs/tags/$tag" >/dev/null; then
  echo "missing git tag: $tag" >&2
  exit 1
fi

if [ "$(git rev-list -n1 "$tag")" != "$(git rev-parse HEAD)" ]; then
  echo "HEAD is not checked out at tag $tag" >&2
  exit 1
fi

if [ -n "$(git status --porcelain=v1 --untracked-files=all)" ]; then
  echo "working tree must be clean before building release artifacts" >&2
  exit 1
fi

PYTHON_BIN="${PYTHON_BIN:-python3}"
export PYTHON_BIN

"$PYTHON_BIN" -m pip install --upgrade pip
"$PYTHON_BIN" -m pip install build twine

staging="$(mktemp -d)"
trap 'rm -rf "$staging"' EXIT

"$PYTHON_BIN" - <<'PY' "$staging"
from pathlib import Path
import shutil
import sys

src = Path(".").resolve()
dst = Path(sys.argv[1])
exclude_names = {
    ".git",
    ".venv",
    "__pycache__",
    ".pytest_cache",
    ".mypy_cache",
    "artifacts",
    "build",
    "dist",
}
for child in src.iterdir():
    if child.name in exclude_names or child.name.endswith(".egg-info"):
        continue
    target = dst / child.name
    if child.is_dir():
        shutil.copytree(child, target)
    else:
        shutil.copy2(child, target)
PY

if [ "$repo" = "testpypi" ]; then
  "$PYTHON_BIN" - <<'PY' "$staging/pyproject.toml"
from pathlib import Path
import re
import sys

p = Path(sys.argv[1])
s = p.read_text(encoding="utf-8")
s2 = re.sub(r'(?m)^name\s*=\s*"GlavnaQt"\s*$', 'name = "TestGlavnaQt"', s)
if s2 == s:
    raise SystemExit('expected name = "GlavnaQt" in pyproject.toml')
p.write_text(s2, encoding="utf-8")
PY
elif [ "$repo" != "pypi" ]; then
  echo "unknown repository: $repo" >&2
  exit 1
fi

release_dir="$PWD/artifacts/release/$repo"
rm -rf "$release_dir"
mkdir -p "$release_dir"

(
  cd "$staging"
  rm -rf dist
  SETUPTOOLS_SCM_PRETEND_VERSION="$version" "$PYTHON_BIN" -m build
  "$PYTHON_BIN" -m twine check dist/*

  mapfile -t built_files < <(find dist -maxdepth 1 -type f \( -name '*.whl' -o -name '*.tar.gz' \) | sort)
  if [ "${#built_files[@]}" -ne 2 ]; then
    echo "expected exactly 2 built distribution files, found ${#built_files[@]}" >&2
    printf 'built files:\n%s\n' "${built_files[*]:-}" >&2
    exit 1
  fi

  cp -f "${built_files[@]}" "$release_dir/"
)

echo "Built artifacts under $release_dir"
