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

PACKAGE_NAME=fast-kalman
VERSION=0.2.3
PUBLIC_UPLOAD_URL=https://upload.pypi.org/legacy/
PUBLIC_JSON_URL=https://pypi.org/pypi/${PACKAGE_NAME}/json
PUBLIC_SIMPLE_URL=https://pypi.org/simple

load_pypi_token() {
  export TWINE_USERNAME=__token__
  export TWINE_PASSWORD
  TWINE_PASSWORD="$(
    python3 - <<'PY'
import configparser
from pathlib import Path

path = Path.home() / ".pypirc"
config = configparser.RawConfigParser()
read = config.read(path)
if not read:
    raise SystemExit(f"{path} was not found")

section = "pypi" if config.has_section("pypi") else "server-login"
if not config.has_option(section, "password"):
    raise SystemExit(f"{path} does not contain a password in [{section}]")

print(config.get(section, "password"))
PY
  )"
}

check_public_pypi() {
  python3 - "$PACKAGE_NAME" "$VERSION" "$PUBLIC_JSON_URL" <<'PY'
import json
import sys
import time
import urllib.error
import urllib.request

package_name, version, url = sys.argv[1:]
last_error = None

for attempt in range(12):
    try:
        with urllib.request.urlopen(url, timeout=20) as response:
            data = json.load(response)
        versions = set(data.get("releases", {}))
        if version in versions:
            print(f"{package_name} {version} is visible on public PyPI: {url}")
            raise SystemExit(0)
        last_error = f"project exists, but version {version} is missing; available={sorted(versions)}"
    except urllib.error.HTTPError as exc:
        last_error = f"HTTP {exc.code} from {url}"
    except urllib.error.URLError as exc:
        last_error = str(exc)

    if attempt != 11:
        time.sleep(10)

print(f"{package_name} {version} is not visible on public PyPI after upload: {last_error}", file=sys.stderr)
raise SystemExit(1)
PY
}

load_pypi_token

python3 -m pip install --upgrade build twine
rm -rf dist
python3 -m build --sdist
python3 -m twine check dist/*
python3 -m twine upload --non-interactive --verbose --repository-url "$PUBLIC_UPLOAD_URL" "dist/fast_kalman-${VERSION}.tar.gz"
check_public_pypi
python3 -m pip index versions "$PACKAGE_NAME" -i "$PUBLIC_SIMPLE_URL"

python3 -m pip install --upgrade cibuildwheel twine
rm -rf wheelhouse
CIBW_CONTAINER_ENGINE=podman python3 -m cibuildwheel --platform linux --output-dir wheelhouse
ls -lh wheelhouse
python3 -m twine check wheelhouse/*
python3 -m twine upload --non-interactive --verbose --repository-url "$PUBLIC_UPLOAD_URL" wheelhouse/*
check_public_pypi
python3 -m pip index versions "$PACKAGE_NAME" -i "$PUBLIC_SIMPLE_URL"
