#!/bin/bash
#
# search-archive.sh - Search archived sessions by metadata
#
# Usage: ./search-archive.sh [--session-id UUID] [--key PATTERN] [--after DATE] [--before DATE]
#

set -euo pipefail

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

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

# Parse arguments
SESSION_ID=""
KEY_PATTERN=""
AFTER_DATE=""
BEFORE_DATE=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --session-id) SESSION_ID="$2"; shift 2 ;;
        --key) KEY_PATTERN="$2"; shift 2 ;;
        --after) AFTER_DATE="$2"; shift 2 ;;
        --before) BEFORE_DATE="$2"; shift 2 ;;
        --help) 
            echo "Usage: $0 [--session-id UUID] [--key PATTERN] [--after DATE] [--before DATE]"
            exit 0 ;;
        *) echo "Unknown option: $1"; exit 1 ;;
    esac
done

# Build jq filter
FILTER="to_entries[]"

if [[ -n "$SESSION_ID" ]]; then
    FILTER="$FILTER | select(.value.sessionId == \"$SESSION_ID\")"
fi

if [[ -n "$KEY_PATTERN" ]]; then
    FILTER="$FILTER | select(.key | contains(\"$KEY_PATTERN\"))"
fi

if [[ -n "$AFTER_DATE" ]]; then
    AFTER_MS=$(( $(date -d "$AFTER_DATE" +%s) * 1000 ))
    FILTER="$FILTER | select(.value.updatedAt >= $AFTER_MS)"
fi

if [[ -n "$BEFORE_DATE" ]]; then
    BEFORE_MS=$(( $(date -d "$BEFORE_DATE" +%s) * 1000 ))
    FILTER="$FILTER | select(.value.updatedAt <= $BEFORE_MS)"
fi

# Execute search
echo "Searching archived sessions..."
echo ""

jq -r "$FILTER | \"Session: \(.key)\n  ID: \(.value.sessionId)\n  Updated: \(.value.updatedAt | . / 1000 | strftime(\"%Y-%m-%d %H:%M:%S UTC\"))\n  Archived: \(.value.archivedAt | . / 1000 | strftime(\"%Y-%m-%d %H:%M:%S UTC\"))\n  Path: \(.value.archivePath)\n\"" "$ARCHIVE_INDEX"

TOTAL=$(jq "$FILTER | .key" "$ARCHIVE_INDEX" | wc -l)
echo "Found: $TOTAL archived sessions"
