#!/usr/bin/env bash
# apply.sh — Apply the BirdAI vendored graphiti-core patches.
#
# Backs up the original venv files into ./backups/<timestamp>/ before
# overwriting. The backup directory layout mirrors the venv layout so a
# revert is just a tree copy back.
#
# Usage: ./apply.sh

set -euo pipefail

PATCH_DIR="$(cd "$(dirname "$0")" && pwd)"
VENV_BASE="/home/aaron/aaronai/venv/lib/python3.12/site-packages"
TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP_DIR="$PATCH_DIR/backups/$TIMESTAMP"

# Files to patch — paths relative to graphiti_core/.
FILES=(
    "graph_queries.py"
    "driver/falkordb_driver.py"
    "driver/falkordb/operations/search_ops.py"
)

echo "graphiti-core vendored patch apply — BirdAI"
echo "Patch directory: $PATCH_DIR"
echo "Venv target:     $VENV_BASE/graphiti_core/"
echo "Backup to:       $BACKUP_DIR"
echo

# Pre-flight: confirm all source patch files exist.
for rel in "${FILES[@]}"; do
    if [ ! -f "$PATCH_DIR/graphiti_core/$rel" ]; then
        echo "ERROR: missing patch file: $PATCH_DIR/graphiti_core/$rel" >&2
        exit 1
    fi
done

# Pre-flight: confirm all target venv files exist.
for rel in "${FILES[@]}"; do
    if [ ! -f "$VENV_BASE/graphiti_core/$rel" ]; then
        echo "ERROR: missing venv file: $VENV_BASE/graphiti_core/$rel" >&2
        echo "  graphiti-core may not be installed, or version differs from 0.29.0." >&2
        exit 1
    fi
done

# Backup originals.
echo "[1/3] Backing up originals..."
for rel in "${FILES[@]}"; do
    backup_path="$BACKUP_DIR/graphiti_core/$rel"
    mkdir -p "$(dirname "$backup_path")"
    cp "$VENV_BASE/graphiti_core/$rel" "$backup_path"
    echo "  backed up: $rel"
done
echo

# Apply patches by copying.
echo "[2/3] Applying patches..."
for rel in "${FILES[@]}"; do
    cp "$PATCH_DIR/graphiti_core/$rel" "$VENV_BASE/graphiti_core/$rel"
    echo "  patched: $rel"
done
echo

# Sanity check: confirm patched files have the marker.
echo "[3/3] Verifying patched files..."
for rel in "${FILES[@]}"; do
    if grep -q "PATCHED 2026-05-02" "$VENV_BASE/graphiti_core/$rel"; then
        echo "  OK: $rel contains patch marker"
    else
        echo "  WARNING: $rel missing patch marker (may be expected for graph_queries.py — its docstring uses the marker only in the module header)"
    fi
done
echo
echo "Done. Backup: $BACKUP_DIR"
echo "Restart the sidecar to pick up changes:"
echo "  sudo systemctl restart aaronai-graphiti.service"
