#!/bin/bash
#
# Autonomous AI Agent — Update Script
# Checks for and installs updates from the deployed site.
#
# Usage: ./update.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

# Fix Windows line endings if present
if cat -v "$0" | head -1 | grep -q '\^M'; then
  for f in "$SCRIPT_DIR"/*.sh "$SCRIPT_DIR"/scripts/*.sh; do
    [ -f "$f" ] || continue
    tr -d '\r' < "$f" > "$f.tmp" && mv "$f.tmp" "$f" && chmod +x "$f"
  done
  exec bash "$0" "$@"
fi

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
BOLD='\033[1m'
NC='\033[0m'

# Update source — the deployed site
UPDATE_URL="${UPDATE_URL:-https://ai-do-site.pages.dev}"
VERSION_URL="${UPDATE_URL}/version.json"
ZIP_URL="${UPDATE_URL}/agent.zip"

echo ""
echo -e "${BOLD}Autonomous AI Agent — Update Check${NC}"
echo ""

# ── Get local version ─────────────────────────────────────────

LOCAL_VERSION="0.0.0"
if [ -f version.json ]; then
  LOCAL_VERSION=$(node -e "console.log(JSON.parse(require('fs').readFileSync('version.json','utf-8')).version || '0.0.0')" 2>/dev/null || echo "0.0.0")
fi
echo -e "  Local version:  ${BOLD}${LOCAL_VERSION}${NC}"

# ── Fetch remote version ─────────────────────────────────────

echo -n "  Checking for updates... "

REMOTE_JSON=$(curl -fsSL "$VERSION_URL" 2>/dev/null || echo "")
if [ -z "$REMOTE_JSON" ]; then
  echo -e "${YELLOW}could not reach update server${NC}"
  echo ""
  echo "  URL: $VERSION_URL"
  echo "  Check your internet connection or update URL."
  echo ""
  exit 1
fi

REMOTE_VERSION=$(echo "$REMOTE_JSON" | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>console.log(JSON.parse(d).version||'0.0.0'))" 2>/dev/null || echo "0.0.0")
echo -e "${GREEN}done${NC}"
echo -e "  Remote version: ${BOLD}${REMOTE_VERSION}${NC}"

# ── Compare versions ──────────────────────────────────────────

NEEDS_UPDATE=$(node -e "
  const l = '${LOCAL_VERSION}'.split('.').map(Number);
  const r = '${REMOTE_VERSION}'.split('.').map(Number);
  for (let i = 0; i < 3; i++) {
    if ((r[i]||0) > (l[i]||0)) { console.log('yes'); process.exit(0); }
    if ((r[i]||0) < (l[i]||0)) { console.log('no'); process.exit(0); }
  }
  console.log('no');
" 2>/dev/null)

if [ "$NEEDS_UPDATE" != "yes" ]; then
  echo ""
  echo -e "  ${GREEN}✓ You're up to date!${NC}"
  echo ""
  exit 0
fi

echo ""
echo -e "  ${BLUE}Update available: ${LOCAL_VERSION} → ${REMOTE_VERSION}${NC}"
echo ""

# Show changelog if available
REMOTE_CHANGELOG=$(echo "$REMOTE_JSON" | node -e "process.stdin.resume();let d='';process.stdin.on('data',c=>d+=c);process.stdin.on('end',()=>{const j=JSON.parse(d);if(j.changelog)console.log(j.changelog);})" 2>/dev/null || echo "")
if [ -n "$REMOTE_CHANGELOG" ]; then
  echo -e "  ${BOLD}What's new:${NC}"
  echo "$REMOTE_CHANGELOG" | sed 's/^/    /'
  echo ""
fi

read -p "  Install update? (Y/n): " CONFIRM
CONFIRM=${CONFIRM:-Y}
if [[ ! "$CONFIRM" =~ ^[Yy] ]]; then
  echo "  Update cancelled."
  exit 0
fi

# ── Stop agent if running ─────────────────────────────────────

AGENT_PID=$(pgrep -f "node.*agent.mjs" 2>/dev/null | head -1 || true)
if [ -n "$AGENT_PID" ]; then
  echo -e "  Stopping agent (PID: $AGENT_PID)..."
  kill "$AGENT_PID" 2>/dev/null || true
  sleep 2
fi

# ── Download and apply update ─────────────────────────────────

echo -n "  Downloading update... "
TMPDIR=$(mktemp -d)
curl -fsSL "$ZIP_URL" -o "$TMPDIR/agent.zip"
echo -e "${GREEN}done${NC}"

echo -n "  Extracting... "
unzip -qo "$TMPDIR/agent.zip" -d "$TMPDIR/agent"
echo -e "${GREEN}done${NC}"

# ── Apply update (preserve user data) ─────────────────────────

echo -n "  Applying update... "

# Files to update (code only — never overwrite user data)
UPDATE_FILES=(
  agent.mjs config.mjs db.mjs server.mjs skills.mjs memory.mjs
  workspace.mjs workspace-manager.mjs task-scheduler.mjs
  llm.mjs json-utils.mjs evolution.mjs voice-activation.mjs
  knowledge-graph.mjs entity-extraction.mjs semantic-search.mjs
  ingestion.mjs fetch-utils.mjs file-watcher.mjs
  persona.mjs vector-cache.mjs
  session-store.mjs chat-session.mjs background-queue.mjs askuser-bridge.mjs
  personality.md tools.md
  watchdog.sh reset.sh reset.bat setup.sh setup.bat update.sh update.bat install.sh
)

# Source directory in the extracted zip
SRC_DIR="$TMPDIR/agent"
# If the zip has a single top-level directory, go into it
if [ "$(ls -1 "$SRC_DIR" | wc -l)" -eq 1 ] && [ -d "$SRC_DIR/$(ls "$SRC_DIR")" ]; then
  SRC_DIR="$SRC_DIR/$(ls "$SRC_DIR")"
fi

for f in "${UPDATE_FILES[@]}"; do
  if [ -f "$SRC_DIR/$f" ]; then
    cp "$SRC_DIR/$f" "$SCRIPT_DIR/$f"
  fi
done

# Update directories (skills, adapters, agentic-tools, scripts, public, cognitive, multimodal, electron)
for dir in adapters agentic-tools skills scripts public cognitive multimodal electron; do
  if [ -d "$SRC_DIR/$dir" ]; then
    mkdir -p "$SCRIPT_DIR/$dir"
    cp -R "$SRC_DIR/$dir/." "$SCRIPT_DIR/$dir/"
  fi
done

# Update version.json
if [ -f "$SRC_DIR/version.json" ]; then
  cp "$SRC_DIR/version.json" "$SCRIPT_DIR/version.json"
fi

# Update .claude/settings.json (tool policies)
if [ -f "$SRC_DIR/.claude/settings.json" ]; then
  mkdir -p "$SCRIPT_DIR/.claude"
  cp "$SRC_DIR/.claude/settings.json" "$SCRIPT_DIR/.claude/settings.json"
fi

# Update package.json dependencies (merge, don't overwrite agent name)
if [ -f "$SRC_DIR/package.json" ]; then
  node -e "
    const fs = require('fs');
    const local = JSON.parse(fs.readFileSync('$SCRIPT_DIR/package.json', 'utf-8'));
    const remote = JSON.parse(fs.readFileSync('$SRC_DIR/package.json', 'utf-8'));
    local.dependencies = { ...local.dependencies, ...remote.dependencies };
    fs.writeFileSync('$SCRIPT_DIR/package.json', JSON.stringify(local, null, 2) + '\n');
  "
fi

echo -e "${GREEN}done${NC}"

# ── Reinstall dependencies ────────────────────────────────────

echo -n "  Updating dependencies... "
npm install --silent 2>/dev/null
echo -e "${GREEN}done${NC}"

# Create directories that may be new in this version
mkdir -p "$SCRIPT_DIR/workspaces/default" "$SCRIPT_DIR/data/wake-words" "$SCRIPT_DIR/data/wake-word-models" 2>/dev/null || true

# Make scripts executable
chmod +x setup.sh reset.sh watchdog.sh update.sh 2>/dev/null || true

# Cleanup
rm -rf "$TMPDIR"

echo ""
echo -e "  ${GREEN}${BOLD}✓ Updated to version ${REMOTE_VERSION}!${NC}"
echo ""
echo "  Restart your agent with: npm start"
echo ""
