#!/bin/bash
# File: scripts/sync-git-safe.sh
# Purpose: Safely sync main branch from GitHub, respecting Dropbox sync state
# Context: Used by VS Code tasks and manual triggers. Ensures GitHub is SSOT.

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOCK_FILE="$SCRIPT_DIR/.dropbox/DEVICE_LOCK"
SYNC_MARKER="$SCRIPT_DIR/.dropbox/LAST_GIT_SYNC"

# Detect device name
DEVICE_NAME=$(hostname 2>/dev/null || echo "unknown-device")
CURRENT_BRANCH=$(git -C "$SCRIPT_DIR" symbolic-ref --short HEAD 2>/dev/null || echo "unknown")

echo "=================================================="
echo "🔄 Safe Git Sync: GitHub → main"
echo "=================================================="
echo "Device:    $DEVICE_NAME"
echo "Branch:    $CURRENT_BRANCH"
echo "Timestamp: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo ""

# Step 1: Set device lock
echo "📍 Step 1: Setting device lock..."
mkdir -p "$SCRIPT_DIR/.dropbox"
echo "$DEVICE_NAME" > "$LOCK_FILE"
echo "✅ Device lock set: $LOCK_FILE"
echo ""

# Step 2: Verify Dropbox sync is complete (wait up to 5 seconds)
echo "📍 Step 2: Checking Dropbox sync completion..."
sync_wait_count=0
max_sync_wait=50  # 5 seconds (50 * 0.1s)

while [ $sync_wait_count -lt $max_sync_wait ]; do
  # Check if .dropbox folder was modified recently (within last 10 seconds)
  if [ -d "$SCRIPT_DIR/.dropbox" ]; then
    last_mod=$(stat -c %Y "$SCRIPT_DIR/.dropbox" 2>/dev/null || stat -f %m "$SCRIPT_DIR/.dropbox" 2>/dev/null || echo 0)
    current_time=$(date +%s)
    mod_age=$((current_time - last_mod))

    if [ $mod_age -lt 10 ]; then
      echo "✅ Dropbox sync detected (modified $mod_age seconds ago)"
      break
    fi
  fi

  sync_wait_count=$((sync_wait_count + 1))
  if [ $((sync_wait_count % 10)) -eq 0 ]; then
    echo "⏳ Waiting for Dropbox sync... ($((sync_wait_count / 10))s)"
  fi
  sleep 0.1
done

echo ""

# Step 3: Fetch from GitHub (GitHub is SSOT)
echo "📍 Step 3: Fetching from GitHub..."
if git -C "$SCRIPT_DIR" fetch origin main:main --quiet 2>/dev/null; then
  echo "✅ Fetched origin/main successfully"
else
  echo "⚠️  Fetch failed - check network connection"
  exit 1
fi
echo ""

# Step 4: Switch to main and pull (if not already on main)
echo "📍 Step 4: Updating main branch..."
if [ "$CURRENT_BRANCH" != "main" ]; then
  echo "Switching to main..."
  git -C "$SCRIPT_DIR" checkout main --quiet 2>/dev/null || {
    echo "⚠️  Failed to switch to main"
    exit 1
  }
fi

if git -C "$SCRIPT_DIR" pull origin main --quiet 2>/dev/null; then
  echo "✅ main branch updated from GitHub"
else
  echo "⚠️  Pull failed - attempting merge"
  git -C "$SCRIPT_DIR" merge --ff-only origin/main 2>/dev/null || {
    echo "⚠️  Merge conflict detected. Please resolve manually."
    exit 1
  }
fi
echo ""

# Step 5: Switch back to dev
if [ "$CURRENT_BRANCH" = "dev" ] || [ "$CURRENT_BRANCH" = "main" ]; then
  echo "📍 Step 5: Switching back to dev..."
  git -C "$SCRIPT_DIR" checkout dev --quiet 2>/dev/null || {
    echo "⚠️  Failed to switch to dev"
    exit 1
  }
  echo "✅ Switched to dev branch"
fi
echo ""

# Step 6: Update sync marker
echo "📍 Step 6: Recording sync timestamp..."
echo "main:$(git -C "$SCRIPT_DIR" rev-parse origin/main 2>/dev/null):$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$SYNC_MARKER"
echo "✅ Sync marker updated"
echo ""

echo "=================================================="
echo "✅ Safe sync completed successfully!"
echo "=================================================="
echo "main is now synchronized with GitHub"
echo "Your working branch (dev) is ready for development"
