#!/bin/bash
set -e

echo "Working directory: $(pwd)"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${YELLOW}==> Reading version from pyproject.toml...${NC}"
VERSION=$(grep -m1 'version = ' pyproject.toml | cut -d'"' -f2)
echo -e "${GREEN}Version: $VERSION${NC}"

echo -e "${YELLOW}==> Building package...${NC}"
rm -rf dist/
uv build

echo -e "${YELLOW}==> Publishing to PyPI...${NC}"
uv publish

echo -e "${YELLOW}==> Waiting for PyPI to confirm version $VERSION...${NC}"
MAX_ATTEMPTS=30
ATTEMPT=0
while true; do
    ATTEMPT=$((ATTEMPT + 1))
    AVAILABLE=$(curl -s "https://pypi.org/pypi/htd-silo/json" | python3 -c "import sys,json; print(json.load(sys.stdin)['info']['version'])" 2>/dev/null || echo "error")

    if [ "$AVAILABLE" = "$VERSION" ]; then
        echo -e "${GREEN}Version $VERSION confirmed on PyPI!${NC}"
        break
    fi

    if [ $ATTEMPT -ge $MAX_ATTEMPTS ]; then
        echo -e "${RED}Timeout waiting for PyPI (max $MAX_ATTEMPTS attempts). Current version: $AVAILABLE${NC}"
        exit 1
    fi

    echo -e "${YELLOW}  Attempt $ATTEMPT/$MAX_ATTEMPTS: PyPI shows $AVAILABLE, waiting for $VERSION...${NC}"
    sleep 5
done

echo -e "${YELLOW}==> Installing htd-silo==$VERSION from PyPI...${NC}"
uv pip install "htd-silo==$VERSION" --force-reinstall --refresh

echo -e "${YELLOW}==> Regenerating Homebrew formula...${NC}"
PYTHONWARNINGS="ignore::UserWarning" .venv/bin/poet -f htd-silo > "Formula/htd-silo.rb"

echo -e "${YELLOW}==> Formula URL:${NC}"
grep "url" "Formula/htd-silo.rb" | head -1

echo -e "${YELLOW}==> Checking for changes...${NC}"
if [[ -n $(git status --porcelain) ]]; then
    echo -e "${GREEN}Changes detected, committing...${NC}"
    git add .
    git commit -m "Release: update package and formula"
else
    echo -e "${GREEN}No changes to commit${NC}"
fi

echo -e "${YELLOW}==> Pushing to remote main branch...${NC}"
git push origin main

echo -e "${YELLOW}==> Reinstalling htd-silo...${NC}"
brew uninstall htd-silo
brew untap karolkaminskihtd/htd-silo
brew cleanup -s
brew tap karolkaminskihtd/htd-silo git@github.com:HTD-Health/silo.git
brew install htd-silo

echo -e "${GREEN}==> Release complete!${NC}"
silo --help
