#!/bin/bash
# GitHub Backup Script - Backs up Remix Sniper code to GitHub
# This backs up code only (not data/configs) for version control

set -e

REPO_DIR="$HOME/projects/remix-sniper"
GITHUB_USERNAME="${1:-jakeshore}"
REPO_NAME="${2:-remix-sniper}"

if [[ ! -d "$REPO_DIR" ]]; then
  echo "ERROR: Remix Sniper directory not found: $REPO_DIR"
  exit 1
fi

cd "$REPO_DIR"

echo "=========================================="
echo "GITHUB BACKUP FOR REMIX SNIPER"
echo "=========================================="
echo "Repository: https://github.com/$GITHUB_USERNAME/$REPO_NAME"
echo ""

# Initialize git if not already
if [[ ! -d ".git" ]]; then
  echo "[1/4] Initializing git repository..."
  git init
  git branch -M main
else
  echo "[1/4] Git repository already initialized"
fi

# Create .gitignore if not exists
echo "[2/4] Setting up .gitignore..."

cat > .gitignore <<'EOF'
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
*.egg-info/
dist/
build/
.venv/
venv/
.venv311/

# Environment variables
.env
.env.local
.env.*.local

# Database dumps
*.sql
*.db
*.sqlite

# Logs
*.log
bot.log
bot_error.log
daily_scan.log
stats_update.log
weekly_report.log

# IDE
.vscode/
.idea/
*.swp
*.swo
*~

# macOS
.DS_Store
.AppleDouble
.LSOverride
._*

# Backup files
backup-*
backup-*
*.bak

# Tracking data (JSON files - should be backed up separately)
.tracking/
EOF

echo "   ✓ Created .gitignore"

# Add all files
echo "[3/4] Adding files to git..."
git add .

# Check if there are changes
if git diff --staged --quiet; then
  echo "   ✓ No changes to commit"
  echo ""
  echo "Repository is up to date."
  exit 0
fi

# Commit
echo ""
echo "[4/4] Committing changes..."
COMMIT_MESSAGE="Backup on $(date +%Y-%m-%d at %H:%M)"
git commit -m "$COMMIT_MESSAGE"
echo "   ✓ Committed changes"

# Check if remote exists
if git remote | grep -q "^origin$"; then
  echo ""
  echo "Remote 'origin' already exists"
  echo "  URL: $(git remote get-url origin)"
else
  echo ""
  echo "Setting up remote repository..."
  echo ""
  echo "To complete GitHub setup:"
  echo "  1. Create a new repository at: https://github.com/new"
  echo "  2. Name it: $REPO_NAME"
  echo "  3. Don't initialize with README, .gitignore, or license"
  echo "  4. Run: git remote add origin https://github.com/$GITHUB_USERNAME/$REPO_NAME.git"
  echo "  5. Run: git push -u origin main"
  echo ""
  exit 0
fi

# Push to GitHub
echo ""
echo "Pushing to GitHub..."
git push -u origin main

echo ""
echo "=========================================="
echo "BACKUP COMPLETE"
echo "=========================================="
echo ""
echo "Repository: https://github.com/$GITHUB_USERNAME/$REPO_NAME"
echo ""
echo "To push future changes:"
echo "  cd ~/projects/remix-sniper"
echo "  git add ."
echo "  git commit -m 'Your message'"
echo "  git push"
echo ""
