#!/bin/bash
#
# restore-session.sh - Restore a session from archive
#
# Usage: ./restore-session.sh <session-id>
#

set -euo pipefail

SESSIONS_DIR="/home/aria/.openclaw/agents/main/sessions"
ARCHIVE_INDEX="$SESSIONS_DIR/archive/index.json"

if [[ $# -lt 1 ]]; then
    echo "Usage: $0 <session-id>"
    exit 1
fi

SESSION_ID="$1"

if [[ ! -f "$ARCHIVE_INDEX" ]]; then
    echo "No archive index found."
    exit 1
fi

# Find session in archive
ARCHIVE_ENTRY=$(jq -r --arg id "$SESSION_ID" '
    to_entries[] | select(.value.sessionId == $id) | @json
' "$ARCHIVE_INDEX")

if [[ -z "$ARCHIVE_ENTRY" ]]; then
    echo "Session $SESSION_ID not found in archive."
    exit 1
fi

SESSION_KEY=$(echo "$ARCHIVE_ENTRY" | jq -r '.key')
ARCHIVE_PATH=$(echo "$ARCHIVE_ENTRY" | jq -r '.value.archivePath')
SESSION_DATA=$(echo "$ARCHIVE_ENTRY" | jq '.value | del(.archivePath, .archivedAt)')

echo "Found archived session:"
echo "  Key: $SESSION_KEY"
echo "  Archive: $ARCHIVE_PATH"
echo ""

read -p "Restore this session? [y/N] " -n 1 -r
echo ""

if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Cancelled."
    exit 0
fi

# Decompress transcript
if [[ -f "$ARCHIVE_PATH" ]]; then
    RESTORED_FILE="$SESSIONS_DIR/$(basename "${ARCHIVE_PATH%.gz}")"
    gunzip -c "$ARCHIVE_PATH" > "$RESTORED_FILE"
    echo "Restored transcript: $RESTORED_FILE"
fi

# Add back to sessions.json
jq --arg key "$SESSION_KEY" --argjson value "$SESSION_DATA" \
    '.[$key] = $value' \
    "$SESSIONS_DIR/sessions.json" > "$SESSIONS_DIR/sessions.json.tmp" \
    && mv "$SESSIONS_DIR/sessions.json.tmp" "$SESSIONS_DIR/sessions.json"

echo "Added to sessions.json"

# Remove from archive index
jq --arg key "$SESSION_KEY" 'del(.[$key])' \
    "$ARCHIVE_INDEX" > "$ARCHIVE_INDEX.tmp" \
    && mv "$ARCHIVE_INDEX.tmp" "$ARCHIVE_INDEX"

echo "Removed from archive index"
echo ""
echo "Session restored successfully!"
