#!/bin/bash
# Restore test script
# Usage: ./restore_test.sh <timestamp>

set -e

TIMESTAMP=$1
if [ -z "$TIMESTAMP" ]; then
    echo "Usage: $0 <timestamp>"
    exit 1
fi

BACKUP_DIR="/opt/microdao-daarion/data/backups"
METADATA="$BACKUP_DIR/backup_$TIMESTAMP.metadata.json"

if [ ! -f "$METADATA" ]; then
    echo "❌ Metadata file not found: $METADATA"
    exit 1
fi

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║              RESTORE TEST                                     ║"
echo "╚══════════════════════════════════════════════════════════════╝"
echo "Backup timestamp: $TIMESTAMP"
echo ""

# Load metadata
PG_BACKUP=$(cat "$METADATA" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['postgres']['backup_file'])" 2>/dev/null)
PG_COUNTS_ORIG=$(cat "$METADATA" | python3 -c "import sys,json; d=json.load(sys.stdin); print(json.dumps(d['postgres']['counts']))" 2>/dev/null)

echo "=== 1. Postgres Restore Test ==="
if [ -f "$PG_BACKUP" ]; then
    echo "Restoring to test database..."
    # Create test database
    docker exec dagi-postgres psql -U daarion -c "DROP DATABASE IF EXISTS daarion_test;" 2>/dev/null || true
    docker exec dagi-postgres psql -U daarion -c "CREATE DATABASE daarion_test;" 2>/dev/null || true
    
    # Restore
    cat "$PG_BACKUP" | docker exec -i dagi-postgres psql -U daarion daarion_test >/dev/null 2>&1
    
    # Verify counts
    PG_COUNTS_RESTORED=$(docker exec dagi-postgres psql -U daarion -d daarion_test -t -c "
    SELECT 
        '\"sessions\":' || COUNT(*) || ',' ||
        '\"facts\":' || (SELECT COUNT(*) FROM facts) || ',' ||
        '\"audit_log\":' || (SELECT COUNT(*) FROM audit_log) || ',' ||
        '\"helion_mentors\":' || (SELECT COUNT(*) FROM helion_mentors)
    FROM sessions;
    " 2>/dev/null || echo '{"sessions":0,"facts":0,"audit_log":0,"helion_mentors":0}')
    
    echo "Original: $PG_COUNTS_ORIG"
    echo "Restored: $PG_COUNTS_RESTORED"
    
    if [ "$PG_COUNTS_ORIG" = "$PG_COUNTS_RESTORED" ]; then
        echo "✅ Postgres restore: PASSED"
    else
        echo "⚠️ Postgres restore: Counts differ (may be OK if data changed)"
    fi
    
    # Cleanup
    docker exec dagi-postgres psql -U daarion -c "DROP DATABASE daarion_test;" 2>/dev/null || true
else
    echo "⚠️ Postgres backup file not found: $PG_BACKUP"
fi

echo ""
echo "=== 2. Qdrant Restore Test ==="
QDRANT_BACKUP_DIR=$(cat "$METADATA" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['qdrant']['backup_dir'])" 2>/dev/null)
QDRANT_COUNTS_ORIG=$(cat "$METADATA" | python3 -c "import sys,json; d=json.load(sys.stdin); print(json.dumps(d['qdrant']['counts']))" 2>/dev/null)

if [ -d "$QDRANT_BACKUP_DIR" ]; then
    echo "Qdrant snapshots available in: $QDRANT_BACKUP_DIR"
    echo "Original counts: $QDRANT_COUNTS_ORIG"
    echo "✅ Qdrant restore: Snapshot files exist (manual restore required)"
else
    echo "⚠️ Qdrant backup directory not found: $QDRANT_BACKUP_DIR"
fi

echo ""
echo "=== 3. Neo4j Restore Test ==="
NEO4J_BACKUP_DIR=$(cat "$METADATA" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['neo4j']['backup_dir'])" 2>/dev/null)
NEO4J_NODES_ORIG=$(cat "$METADATA" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['neo4j']['nodes'])" 2>/dev/null)
NEO4J_RELS_ORIG=$(cat "$METADATA" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['neo4j']['relationships'])" 2>/dev/null)

if [ -d "$NEO4J_BACKUP_DIR" ]; then
    echo "Neo4j backup available in: $NEO4J_BACKUP_DIR"
    echo "Original: nodes=$NEO4J_NODES_ORIG, relationships=$NEO4J_RELS_ORIG"
    echo "✅ Neo4j restore: Backup files exist (manual restore required)"
else
    echo "⚠️ Neo4j backup directory not found: $NEO4J_BACKUP_DIR"
fi

echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "                    RESTORE TEST SUMMARY"
echo "═══════════════════════════════════════════════════════════════"
echo "✅ Backup files verified"
echo "✅ Postgres restore test completed"
echo "ℹ️ Qdrant/Neo4j require manual restore (snapshot-based)"
