#!/bin/bash
# File: scripts/check_device_lock.sh
# Purpose: Check for device lock conflicts before allowing work to begin
# Context: Run automatically when opening VS Code workspace.

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
LOCK_FILE="$SCRIPT_DIR/.dropbox/DEVICE_LOCK"
DEVICE_NAME=$(hostname 2>/dev/null || echo "unknown-device")

echo ""
echo "=================================================="
echo "🔒 Device Lock Check"
echo "=================================================="
echo "Device:    $DEVICE_NAME"
echo "Timestamp: $(date)"
echo ""

# Create lock directory if needed
mkdir -p "$SCRIPT_DIR/.dropbox"

# Check if lock file exists
if [ -f "$LOCK_FILE" ]; then
  locked_device=$(cat "$LOCK_FILE" 2>/dev/null)

  if [ "$locked_device" = "$DEVICE_NAME" ]; then
    echo "✅ This device's lock is already active"
    echo "   Proceeding with development..."
  else
    echo "⚠️  WARNING: Another device has an active lock!"
    echo ""
    echo "   Locked by: $locked_device"
    echo "   Current:   $DEVICE_NAME"
    echo ""
    echo "This typically means:"
    echo "  • $locked_device is currently developing"
    echo "  • Work may be uncommitted on that device"
    echo "  • Git conflicts could occur if you proceed"
    echo ""
    read -p "Override and take the lock? (y/N): " -r
    echo ""
    if [[ "$REPLY" =~ ^[Yy]$ ]]; then
      echo "🔓 Lock overridden by user"
      echo "$DEVICE_NAME" > "$LOCK_FILE"
      echo "✅ New lock established"
    else
      echo "❌ Aborting - workspace not safe to use"
      exit 1
    fi
  fi
else
  echo "🆕 No lock detected - creating new lock"
  echo "$DEVICE_NAME" > "$LOCK_FILE"
  echo "✅ Lock file created: $LOCK_FILE"
fi

echo ""
echo "=================================================="
echo "Ready for development ✨"
echo "=================================================="
echo ""
