#!/usr/bin/env bash
set -euo pipefail

# Engram data migration: ~/engram/ → ~/.local/share/engram/
# Run once manually. Moves data files, leaves code in place.

SRC="$HOME/engram"
DST="$HOME/.local/share/engram"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "════════════════════════════════════════════════════════════"
echo "  Engram Data Migration"
echo "  From: $SRC"
echo "  To:   $DST"
echo "════════════════════════════════════════════════════════════"
echo ""

# Pre-flight: stop engram service if running
if systemctl is-active --quiet engram-server 2>/dev/null; then
    echo -e "${YELLOW}WARNING: engram-server is running. Stop it first:${NC}"
    echo "  sudo systemctl stop engram-server"
    echo ""
    read -p "Continue anyway? (y/N) " -r
    [[ $REPLY =~ ^[Yy]$ ]] || exit 1
fi

# Create destination
mkdir -p "$DST"

# Items to move (directories)
DIRS=(entities logs telemetry synapse_data agent_memory .encryption hyperloop engram.db)

# Items to move (files)
FILES=(vault_index.sqlite memory_store.db workers.sqlite
       librarian_state.json segregation_state.json
       PRUNED_DICTIONARY.md MASTER_PROFILE.md SELF_MODEL.md
       credentials.json)

moved=0
skipped=0
failed=0

move_item() {
    local name="$1"
    local src_path="$SRC/$name"
    local dst_path="$DST/$name"

    if [ ! -e "$src_path" ]; then
        echo -e "  ${YELLOW}SKIP${NC} $name (not found in source)"
        skipped=$((skipped + 1))
        return
    fi

    if [ -e "$dst_path" ]; then
        echo -e "  ${YELLOW}SKIP${NC} $name (already exists at destination)"
        skipped=$((skipped + 1))
        return
    fi

    if ! mv "$src_path" "$dst_path" 2>/dev/null; then
        echo -e "  ${RED}PERM${NC} $name (needs sudo — run: sudo mv $src_path $dst_path)"
        failed=$((failed + 1))
        return
    fi
    if [ -e "$dst_path" ]; then
        echo -e "  ${GREEN}MOVED${NC} $name"
        moved=$((moved + 1))
    else
        echo -e "  ${RED}FAILED${NC} $name"
        failed=$((failed + 1))
    fi
}

echo "Moving directories..."
for d in "${DIRS[@]}"; do
    move_item "$d"
done

echo ""
echo "Moving files..."
for f in "${FILES[@]}"; do
    move_item "$f"
done

echo ""
echo "════════════════════════════════════════════════════════════"
echo "  Results: $moved moved, $skipped skipped, $failed failed"
echo "════════════════════════════════════════════════════════════"

# Verify
echo ""
echo "Destination contents:"
ls -la "$DST/" 2>/dev/null || echo "(empty)"

echo ""
if [ -d "$DST/entities" ]; then
    entity_count=$(find "$DST/entities" -name "*.md" 2>/dev/null | wc -l)
    echo "Entities: $entity_count markdown files"
fi

if [ -f "$DST/vault_index.sqlite" ]; then
    idx_size=$(du -h "$DST/vault_index.sqlite" | cut -f1)
    echo "Index: $idx_size"
fi

echo ""
echo "Remaining data in source repo:"
for item in "${DIRS[@]}" "${FILES[@]}"; do
    [ -e "$SRC/$item" ] && echo "  ⚠ $item still in $SRC"
done

if [ $failed -eq 0 ]; then
    echo ""
    echo -e "${GREEN}Migration complete.${NC} Restart engram-server when ready:"
    echo "  sudo systemctl start engram-server"
else
    echo ""
    echo -e "${RED}Some items failed to move. Check errors above.${NC}"
    exit 1
fi
