#!/bin/bash

# HuggingFace Spaces Deployment Script
# This script builds the project and deploys to HuggingFace Spaces

echo "🚀 Starting HuggingFace Spaces deployment..."

# Step 1: Build the project
echo "📦 Building production bundle..."
npx vite build

if [ $? -ne 0 ]; then
  echo "❌ Build failed!"
  exit 1
fi

echo "✅ Build successful!"

# Step 2: Create a temporary deployment branch
echo "🔀 Creating deployment branch..."
git checkout -b hf-deploy 2>/dev/null || git checkout hf-deploy

# Step 3: Remove everything except dist/ and .git/
echo "🧹 Cleaning up for deployment..."
find . -maxdepth 1 ! -name 'dist' ! -name '.git' ! -name '.' ! -name '..' -exec rm -rf {} +

# Step 4: Move dist/ contents to root
echo "📁 Moving dist/ contents to root..."
mv dist/* . 2>/dev/null || true
mv dist/.* . 2>/dev/null || true
rmdir dist 2>/dev/null || true

# Step 5: Copy README.md for HF Spaces
echo "📄 Copying README.md..."
git checkout main -- README.md

# Step 6: Commit changes
echo "💾 Committing changes..."
git add -A
git commit -m "Deploy to HuggingFace Spaces - $(date +'%Y-%m-%d %H:%M:%S')"

# Step 7: Push to HuggingFace
echo "⬆️  Pushing to HuggingFace Spaces..."
git push huggingface hf-deploy:main --force

if [ $? -ne 0 ]; then
  echo "❌ Push failed! You may need to authenticate with HuggingFace."
  echo "Run: git config credential.helper store"
  echo "Then try again."
  git checkout main
  exit 1
fi

# Step 8: Return to main branch
echo "🔙 Returning to main branch..."
git checkout main

echo "✅ Deployment complete!"
echo "🌐 Your Space: https://huggingface.co/spaces/Chunte/Thumbnail_miniCrafter"
