#!/usr/bin/env bash
#MISE description="Phase 3 of 4: Build wheel+sdist locally and push git tag + main to GitHub. PyPI publish is handled separately by release:pypi."
set -euo pipefail

echo "═══════════════════════════════════════════════════════════"
echo "  Phase 3: SYNC (build + push)"
echo "═══════════════════════════════════════════════════════════"

# Get version from pyproject.toml
VERSION=$(grep '^version' pyproject.toml | head -1 | sed 's/.*"\(.*\)".*/\1/')
echo "Syncing version: v$VERSION"

# Step 1: Build locally to verify package integrity
echo "→ Building package..."
uv build
echo "  ✓ Built wheel + sdist in dist/"

# Step 2: Verify the built package
echo "→ Verifying package..."
WHEEL=$(find dist -name "*.whl" 2>/dev/null | head -1)
if [[ -n "$WHEEL" ]]; then
    echo "  ✓ Wheel: $(basename "$WHEEL")"
else
    echo "  ✗ No wheel found in dist/"
    exit 1
fi

# Step 3: Push tag and main branch (creates GitHub release via semantic-release's @semantic-release/github)
echo "→ Pushing tag v$VERSION and main..."
if git rev-parse "v$VERSION" &>/dev/null; then
    git push origin "v$VERSION" 2>/dev/null || echo "  ⚠ Tag already pushed"
    git push origin main 2>/dev/null || echo "  ⚠ main already up to date"
    echo "  ✓ Tag v$VERSION pushed"
else
    echo "  ⚠ Tag v$VERSION not found — run release:version first"
    exit 1
fi

echo ""
echo "✓ Sync phase complete (PyPI publish next via release:pypi)"
echo ""
