#!/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)
if ! git rev-parse "v$VERSION" &>/dev/null; then
    echo "  ⚠ Tag v$VERSION not found — run release:version first"
    exit 1
fi

echo "→ Pushing tag v$VERSION..."
if git push origin "v$VERSION" 2>&1; then
    echo "  ✓ Tag v$VERSION pushed"
else
    # Distinguish "already on remote" from real failures
    if git ls-remote --tags origin "refs/tags/v$VERSION" | grep -q "v$VERSION"; then
        echo "  ✓ Tag v$VERSION already on remote"
    else
        echo "  ✗ Failed to push tag v$VERSION"
        exit 1
    fi
fi

echo "→ Pushing main..."
if git push origin main 2>&1; then
    echo "  ✓ main pushed"
else
    echo "  ✗ Failed to push main"
    exit 1
fi

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