#!/usr/bin/env bash
# LFS migration for all product repos with remotes
# Converts HTTPS → SSH remotes, adds .gitattributes with LFS tracking rules, commits, pushes
# Does NOT rewrite history (git lfs migrate import) — forward-only

PRODUCTS_DIR="/home/aria/products"
LOG_FILE="/tmp/lfs-migrate-$(date +%Y%m%d-%H%M%S).log"
SUCCESS=0
SKIPPED=0
FAILED=0

LFS_ATTRS='# Git LFS — track binary/asset files
*.png filter=lfs diff=lfs merge=lfs -text
*.jpg filter=lfs diff=lfs merge=lfs -text
*.jpeg filter=lfs diff=lfs merge=lfs -text
*.gif filter=lfs diff=lfs merge=lfs -text
*.webp filter=lfs diff=lfs merge=lfs -text
*.svg filter=lfs diff=lfs merge=lfs -text
*.ico filter=lfs diff=lfs merge=lfs -text
*.mp4 filter=lfs diff=lfs merge=lfs -text
*.mov filter=lfs diff=lfs merge=lfs -text
*.webm filter=lfs diff=lfs merge=lfs -text
*.avi filter=lfs diff=lfs merge=lfs -text
*.mp3 filter=lfs diff=lfs merge=lfs -text
*.wav filter=lfs diff=lfs merge=lfs -text
*.pdf filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.tar.gz filter=lfs diff=lfs merge=lfs -text
*.ttf filter=lfs diff=lfs merge=lfs -text
*.otf filter=lfs diff=lfs merge=lfs -text
*.woff filter=lfs diff=lfs merge=lfs -text
*.woff2 filter=lfs diff=lfs merge=lfs -text
*.psd filter=lfs diff=lfs merge=lfs -text
*.ai filter=lfs diff=lfs merge=lfs -text
*.sketch filter=lfs diff=lfs merge=lfs -text
*.fig filter=lfs diff=lfs merge=lfs -text
'

log() { echo "[$(date -u +%H:%M:%S)] $*" | tee -a "$LOG_FILE"; }

# Convert HTTPS GitHub URL to SSH
to_ssh() {
  local url="$1"
  # https://github.com/org/repo.git → git@github.com:org/repo.git
  echo "$url" | sed 's|https://github.com/|git@github.com:|'
}

log "=== Git LFS migration for product repos ==="
log "Log: $LOG_FILE"

for d in "$PRODUCTS_DIR"/*/; do
  slug=$(basename "$d")

  # Skip if no git repo
  if [ ! -d "$d/.git" ]; then
    continue
  fi

  # Skip if no remote
  remote=$(cd "$d" && git remote get-url origin 2>/dev/null || echo "")
  if [ -z "$remote" ]; then
    ((SKIPPED++))
    continue
  fi

  log "--- Processing: $slug"

  cd "$d"

  # Convert HTTPS → SSH if needed
  if [[ "$remote" == https://github.com/* ]]; then
    ssh_remote=$(to_ssh "$remote")
    git remote set-url origin "$ssh_remote"
    log "  Converted remote: $remote → $ssh_remote"
    remote="$ssh_remote"
  fi

  # Init LFS hooks
  git lfs install --local >> "$LOG_FILE" 2>&1 || true

  # Check if .gitattributes already has LFS config
  if [ -f ".gitattributes" ] && grep -q "filter=lfs" .gitattributes; then
    # Already has LFS — check for missing patterns and add them
    CHANGED=false
    while IFS= read -r line; do
      [[ "$line" =~ ^# ]] && continue
      [[ -z "$line" ]] && continue
      pattern=$(echo "$line" | awk '{print $1}')
      if ! grep -qF "$pattern" .gitattributes 2>/dev/null; then
        echo "$line" >> .gitattributes
        CHANGED=true
      fi
    done <<< "$LFS_ATTRS"
    if [ "$CHANGED" = false ]; then
      log "  .gitattributes already complete"
    else
      log "  Updated .gitattributes with missing patterns"
    fi
  else
    # Write .gitattributes (append or create)
    if [ -f ".gitattributes" ]; then
      echo "" >> .gitattributes
      printf '%s' "$LFS_ATTRS" >> .gitattributes
    else
      printf '%s' "$LFS_ATTRS" > .gitattributes
    fi
    log "  Created/updated .gitattributes"
  fi

  # Stage and commit if dirty
  if [ -n "$(git status --porcelain .gitattributes 2>/dev/null)" ]; then
    git add .gitattributes
    git commit -m "chore: add Git LFS tracking for binary/asset files" >> "$LOG_FILE" 2>&1
    log "  Committed .gitattributes"
  else
    log "  No changes to commit"
  fi

  # Push
  branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "main")
  if git push origin "$branch" >> "$LOG_FILE" 2>&1; then
    log "  ✅ Pushed → $remote"
    ((SUCCESS++))
  else
    log "  ❌ Push FAILED for $slug"
    ((FAILED++))
  fi

  cd "$PRODUCTS_DIR"
done

log ""
log "=== Done ==="
log "✅ Success: $SUCCESS"
log "⏭ Skipped (no remote): $SKIPPED"
log "❌ Failed: $FAILED"
log "Full log: $LOG_FILE"

# Emit system event when done
openclaw system event --text "Done: Git LFS migration complete — $SUCCESS repos updated, $FAILED failed. Log: $LOG_FILE" --mode now
