#!/bin/zsh
# refresh.sh — Auto-discover and refresh Windsurf chat history archive
# Safe to run repeatedly (idempotent). Discovers new repos automatically.
#
# Usage:
#   ./refresh.sh              # normal run
#   ./refresh.sh --quiet      # suppress output (for scheduled runs)
#   ./refresh.sh --dry-run    # show what would happen without doing it
#
# Scheduled via: ~/Library/LaunchAgents/com.sd9235.windsurf-archive-refresh.plist
# Manual via:    Windsurf workflow /refresh-chat-history

set -eo pipefail

# ── Config ──────────────────────────────────────────────────────────────────
ARCHIVE_DIR="$(cd "$(dirname "$0")" && pwd)"
REPOS_ROOT="/Users/sd9235/code/mygh"
CODEIUM_DIR="$HOME/.codeium/windsurf"
APP_SUPPORT_DIR="$HOME/Library/Application Support/Windsurf"
LOG_FILE="$ARCHIVE_DIR/.last-refresh.log"

QUIET=false
DRY_RUN=false
for arg in "$@"; do
  case "$arg" in
    --quiet) QUIET=true ;;
    --dry-run) DRY_RUN=true ;;
  esac
done

log() {
  if [ "$QUIET" = false ]; then
    echo "$1"
  fi
}

run() {
  if [ "$DRY_RUN" = true ]; then
    log "[dry-run] $*"
  else
    "$@"
  fi
}

STATS_CASCADE=0
STATS_MEMORIES=0
STATS_IMPLICIT=0
STATS_REPOS_DOCS=0
STATS_REPOS_WORKFLOWS=0
STATS_NEW_REPOS=0

# ── 1. Codeium data symlinks ───────────────────────────────────────────────
log "=== Refreshing Codeium data symlinks ==="

link_if_exists() {
  local name="$1" target="$2"
  if [ -d "$target" ] || [ -f "$target" ]; then
    run ln -sfn "$target" "$ARCHIVE_DIR/$name"
    log "  ✓ $name → $target"
  else
    log "  ⚠ $name: target not found ($target)"
  fi
}

link_if_exists "cascade_conversations" "$CODEIUM_DIR/cascade"
link_if_exists "memories"              "$CODEIUM_DIR/memories"
link_if_exists "implicit_context"      "$CODEIUM_DIR/implicit"
link_if_exists "code_tracker"          "$CODEIUM_DIR/code_tracker"
link_if_exists "codemaps"              "$CODEIUM_DIR/codemaps"
link_if_exists "database"              "$CODEIUM_DIR/database"

# Single files
for file in user_settings.pb installation_id; do
  if [ -e "$CODEIUM_DIR/$file" ]; then
    run ln -sfn "$CODEIUM_DIR/$file" "$ARCHIVE_DIR/$file"
    log "  ✓ $file"
  fi
done

# ── 2. App Support symlinks ────────────────────────────────────────────────
log "=== Refreshing App Support symlinks ==="

run ln -sfn "$APP_SUPPORT_DIR" "$ARCHIVE_DIR/app_data"
log "  ✓ app_data"

if [ -d "$APP_SUPPORT_DIR/User/History" ]; then
  run ln -sfn "$APP_SUPPORT_DIR/User/History" "$ARCHIVE_DIR/file_edit_history"
  log "  ✓ file_edit_history"
fi
if [ -d "$APP_SUPPORT_DIR/User/workspaceStorage" ]; then
  run ln -sfn "$APP_SUPPORT_DIR/User/workspaceStorage" "$ARCHIVE_DIR/workspace_storage"
  log "  ✓ workspace_storage"
fi
if [ -d "$APP_SUPPORT_DIR/User/globalStorage" ]; then
  run ln -sfn "$APP_SUPPORT_DIR/User/globalStorage" "$ARCHIVE_DIR/global_storage"
  log "  ✓ global_storage"
fi

# ── 3. Auto-discover repos and copy docs/workflows ────────────────────────
log "=== Scanning repos for docs/WINDSURF and .windsurf/workflows ==="

run mkdir -p "$ARCHIVE_DIR/repo_docs"
run mkdir -p "$ARCHIVE_DIR/repo_workflows"

for repo_path in "$REPOS_ROOT"/*/; do
  repo_name="$(basename "$repo_path")"

  # Copy docs/WINDSURF/ if it exists
  if [ -d "$repo_path/docs/WINDSURF" ] && [ "$(ls -A "$repo_path/docs/WINDSURF" 2>/dev/null)" ]; then
    run mkdir -p "$ARCHIVE_DIR/repo_docs/$repo_name"
    run cp -a "$repo_path/docs/WINDSURF/"* "$ARCHIVE_DIR/repo_docs/$repo_name/"
    count=$(ls -1 "$repo_path/docs/WINDSURF/" 2>/dev/null | wc -l | tr -d ' ')
    log "  ✓ repo_docs/$repo_name ($count files)"
    STATS_REPOS_DOCS=$((STATS_REPOS_DOCS + count))
  fi

  # Copy .windsurf/workflows/ if it exists
  if [ -d "$repo_path/.windsurf/workflows" ] && [ "$(ls -A "$repo_path/.windsurf/workflows" 2>/dev/null)" ]; then
    run mkdir -p "$ARCHIVE_DIR/repo_workflows/$repo_name"
    run cp -a "$repo_path/.windsurf/workflows/"* "$ARCHIVE_DIR/repo_workflows/$repo_name/"
    count=$(ls -1 "$repo_path/.windsurf/workflows/" 2>/dev/null | wc -l | tr -d ' ')
    log "  ✓ repo_workflows/$repo_name ($count workflows)"
    STATS_REPOS_WORKFLOWS=$((STATS_REPOS_WORKFLOWS + count))
  fi
done

# Clean up repo_docs/repo_workflows dirs for repos that no longer have content
for dir in "$ARCHIVE_DIR/repo_docs"/*/; do
  [ -d "$dir" ] || continue
  repo_name="$(basename "$dir")"
  if [ ! -d "$REPOS_ROOT/$repo_name/docs/WINDSURF" ]; then
    log "  🗑 Removing stale repo_docs/$repo_name"
    [ "$DRY_RUN" = false ] && rm -rf "$dir"
  fi
done
for dir in "$ARCHIVE_DIR/repo_workflows"/*/; do
  [ -d "$dir" ] || continue
  repo_name="$(basename "$dir")"
  if [ ! -d "$REPOS_ROOT/$repo_name/.windsurf/workflows" ]; then
    log "  🗑 Removing stale repo_workflows/$repo_name"
    [ "$DRY_RUN" = false ] && rm -rf "$dir"
  fi
done

# ── 4. Gather stats ───────────────────────────────────────────────────────
if [ "$DRY_RUN" = false ]; then
  STATS_CASCADE=$(ls -1 "$CODEIUM_DIR/cascade/"*.pb 2>/dev/null | wc -l | tr -d ' ')
  STATS_MEMORIES=$(ls -1 "$CODEIUM_DIR/memories/"*.pb 2>/dev/null | wc -l | tr -d ' ')
  STATS_IMPLICIT=$(ls -1 "$CODEIUM_DIR/implicit/"*.pb 2>/dev/null | wc -l | tr -d ' ')
  CASCADE_SIZE=$(du -sh "$CODEIUM_DIR/cascade/" 2>/dev/null | cut -f1 | tr -d ' ')
  TRACKER_DIRS=$(ls -1 "$CODEIUM_DIR/code_tracker/active/" 2>/dev/null | wc -l | tr -d ' ')
  HISTORY_DIRS=$(ls -1 "$APP_SUPPORT_DIR/User/History/" 2>/dev/null | wc -l | tr -d ' ')
  WORKSPACE_DIRS=$(ls -1 "$APP_SUPPORT_DIR/User/workspaceStorage/" 2>/dev/null | wc -l | tr -d ' ')
  REPO_DOC_REPOS=$(ls -1 "$ARCHIVE_DIR/repo_docs/" 2>/dev/null | wc -l | tr -d ' ')
  REPO_WF_REPOS=$(ls -1 "$ARCHIVE_DIR/repo_workflows/" 2>/dev/null | wc -l | tr -d ' ')
fi

# ── 5. Write refresh log ──────────────────────────────────────────────────
if [ "$DRY_RUN" = false ]; then
  cat > "$LOG_FILE" <<EOF
Last refresh: $(date -u '+%Y-%m-%dT%H:%M:%SZ') ($(date '+%Y-%m-%d %H:%M:%S %Z'))
Cascade conversations: $STATS_CASCADE ($CASCADE_SIZE)
Memories: $STATS_MEMORIES
Implicit context: $STATS_IMPLICIT
Code tracker dirs: $TRACKER_DIRS
File edit history: $HISTORY_DIRS entries
Workspace storage: $WORKSPACE_DIRS workspaces
Repo docs: $STATS_REPOS_DOCS files across $REPO_DOC_REPOS repos
Repo workflows: $STATS_REPOS_WORKFLOWS files across $REPO_WF_REPOS repos
EOF
fi

# ── 6. Summary ────────────────────────────────────────────────────────────
log ""
log "=== Refresh complete ==="
if [ "$DRY_RUN" = false ]; then
  log "  Cascade conversations: $STATS_CASCADE ($CASCADE_SIZE)"
  log "  Memories: $STATS_MEMORIES"
  log "  Implicit context: $STATS_IMPLICIT"
  log "  Code tracker: $TRACKER_DIRS dirs"
  log "  File edit history: $HISTORY_DIRS entries"
  log "  Repo docs: $STATS_REPOS_DOCS files ($REPO_DOC_REPOS repos)"
  log "  Repo workflows: $STATS_REPOS_WORKFLOWS files ($REPO_WF_REPOS repos)"
  log ""
  log "  Log: $LOG_FILE"
fi
