#!/usr/bin/env bash
# Pre-flight validation for LLMHosts releases
set -euo pipefail

echo "=== LLMHosts Release Pre-Flight Checklist ==="
echo ""

ERRORS=0

# 1. Check version consistency
VERSION=$(python -c "from llmhosts import __version__; print(__version__)")
echo "Version: $VERSION"

# 2. Check CHANGELOG has entry
if ! grep -q "\[$VERSION\]" CHANGELOG.md; then
  echo "ERROR: CHANGELOG.md missing entry for [$VERSION]"
  ERRORS=$((ERRORS + 1))
else
  echo "OK: CHANGELOG.md has entry for [$VERSION]"
fi

# 3. Check on main branch
BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$BRANCH" != "main" ]; then
  echo "WARNING: Not on main branch (current: $BRANCH)"
else
  echo "OK: On main branch"
fi

# 4. Check clean working tree
if ! git diff --quiet; then
  echo "ERROR: Working tree has uncommitted changes"
  ERRORS=$((ERRORS + 1))
else
  echo "OK: Working tree clean"
fi

# 5. Check tests pass
echo ""
echo "Running quick test suite..."
if pytest tests/ -x -q --tb=line 2>/dev/null; then
  echo "OK: Tests pass"
else
  echo "ERROR: Tests failing"
  ERRORS=$((ERRORS + 1))
fi

# 6. Check wheel builds
echo ""
echo "Building wheel..."
if python -m build --wheel --outdir /tmp/llmhosts-release-check/ 2>/dev/null; then
  echo "OK: Wheel builds successfully"
  ls -la /tmp/llmhosts-release-check/*.whl
  rm -rf /tmp/llmhosts-release-check/
else
  echo "ERROR: Wheel build failed"
  ERRORS=$((ERRORS + 1))
fi

echo ""
if [ $ERRORS -eq 0 ]; then
  echo "=== ALL CHECKS PASSED ==="
  echo ""
  echo "Ready to release. Run:"
  echo "  git tag -a v$VERSION -m \"v$VERSION\""
  echo "  git push origin v$VERSION"
else
  echo "=== $ERRORS CHECK(S) FAILED ==="
  echo "Fix issues before releasing."
  exit 1
fi
