#!/bin/bash

# Build and publish script for the "integrate-ui" package (web UI bundled in the wheel)
# Usage: ./pypi_build_script
#
# Needs uv and node/npm. Uses `uv` for building and publishing so it never touches the
# system Python (avoids PEP 668 "externally-managed-environment").
# After `pip install integrate-ui`, the command `integrate-ui` serves the web GUI.

set -euo pipefail
cd "$(dirname "$0")"

MODULE_NAME="integrate-ui"
VERSION=$(grep -m1 '^version' pyproject.toml | sed -E 's/.*"([^"]+)".*/\1/')

if [[ "$VERSION" == "0.0.0" ]]; then
    echo "Set a real version in pyproject.toml first." >&2
    exit 1
fi
if [[ -n "$(git status --porcelain --untracked-files=no)" ]]; then
    echo "Uncommitted changes: commit them first, so the release matches a commit." >&2
    exit 1
fi
# The app version is part of the API contract (openapi.json info.version)
uv sync -q
if ! uv run python tools/gen_api.py --check; then
    echo "src/web/openapi.json is out of date (version bump?): run 'uv run python tools/gen_api.py' and commit." >&2
    exit 1
fi

echo "=== Building $MODULE_NAME v$VERSION ==="

# 1. The web app: type-checks, then vite builds it into src/web/dist
echo "Building the web app..."
npm --prefix src/web ci
npm --prefix src/web run build

# 2. Optional quick checks (as CI runs them, without the slow tests)
read -p "Run lint and tests first? [Y/n] " run_tests
if [[ ! ${run_tests:-} =~ ^[Nn]$ ]]; then
    uv run ruff check .
    uv run ruff format --check .
    uv run pytest -q -m "not slow"
    npm --prefix src/web run test
fi

# 3. sdist and wheel are built separately: a plain `uv build` makes the wheel from the sdist,
#    which never contains the git-ignored src/web/dist, so the wheel would have no UI.
#    INTEGRATE_UI_REQUIRE_WEB_DIST=1 makes the build fail instead (tools/hatch_build.py).
#    --no-sources: build against PyPI's integrate_module, not the ../integrate_module checkout.
echo "Cleaning up old build artifacts..."
rm -rf dist/ build/
echo "Building distribution packages..."
uv build --no-sources --sdist
INTEGRATE_UI_REQUIRE_WEB_DIST=1 uv build --no-sources --wheel

# 4. The wheel must contain the UI; then a smoke test in a clean, throwaway environment
WHEEL=$(ls dist/*.whl)
if ! unzip -l "$WHEEL" | grep -q 'integrate_ui/web_dist/index.html'; then
    echo "The wheel has no web UI (integrate_ui/web_dist/index.html missing)." >&2
    exit 1
fi
echo "Smoke test: installing the wheel in a clean environment..."
uv run --isolated --no-project --with "$WHEEL" integrate-ui --version

echo "=== Build complete ==="
echo "Distribution files created:"
ls -l dist/

# Prompt for an API token, preferring an existing env var.
# Usage: get_token <env-var-name> <human-readable-label>
# Sets the global TOKEN variable on success.
get_token() {
    local env_var="$1" label="$2"
    TOKEN="${!env_var:-}"
    if [[ -n "$TOKEN" ]]; then
        echo "Using $label token from \$$env_var"
        return 0
    fi
    read -rsp "Enter $label API token (input hidden): " TOKEN
    echo
    if [[ -z "$TOKEN" ]]; then
        echo "No token provided; skipping upload." >&2
        return 1
    fi
}

# Upload to TestPyPI first
echo -e "\n=== TestPyPI Upload ==="
read -p "Upload to TestPyPI for verification? [y/N] " test_upload
if [[ ${test_upload:-} =~ ^[Yy]$ ]]; then
    if get_token UV_PUBLISH_TOKEN_TEST "TestPyPI"; then
        uv publish --publish-url https://test.pypi.org/legacy/ --token "$TOKEN" dist/*
        echo -e "\nTestPyPI upload complete!"
        echo "You can install and test with:"
        echo "pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ $MODULE_NAME==$VERSION"
        echo "integrate-ui"
        echo "This uses TestPyPI for $MODULE_NAME but regular PyPI for dependencies."
    fi
fi

# Upload to PyPI when ready
echo -e "\n=== PyPI Upload ==="
read -p "Upload to PyPI for production release? [y/N] " prod_upload
if [[ ${prod_upload:-} =~ ^[Yy]$ ]] && get_token UV_PUBLISH_TOKEN "PyPI"; then
    uv publish --token "$TOKEN" dist/*
    echo -e "\nPyPI upload complete!"
    echo "Your package is now available via:"
    echo "pip install $MODULE_NAME"
    echo "integrate-ui            # serves the web GUI on http://127.0.0.1:<port>"
    git tag -a "v$VERSION" -m "$MODULE_NAME $VERSION"
    echo "Tagged v$VERSION (push with: git push origin v$VERSION)"
else
    echo -e "\nSkipped PyPI upload. When ready for the real release, run:"
    echo "uv publish dist/*"
fi
