#!/bin/bash
OPENCODE_BIN="/home/ardo/.opencode/bin/opencode"
OPENCODE_DB="$HOME/.local/share/opencode/opencode.db"

if [ "$1" = "export" ]; then
    tmpfile=$(mktemp /tmp/opencode-export-XXXXXX.json)
    "$OPENCODE_BIN" "$@" > "$tmpfile" 2>/dev/null
    cat "$tmpfile"
    rm -f "$tmpfile"
elif [ "$1" = "session" ] && [ "$2" = "list" ] && [ "$3" = "--format" ] && [ "$4" = "json" ]; then
    parent_sessions=$("$OPENCODE_BIN" session list --format json 2>/dev/null)
    if [ -n "$parent_sessions" ] && command -v sqlite3 &>/dev/null && [ -f "$OPENCODE_DB" ]; then
        tmpfile=$(mktemp /tmp/opencode-merge-XXXXXX.py)
        cat > "$tmpfile" << 'PYEOF'
import json, sys, subprocess, os

db_path = os.path.expanduser("~/.local/share/opencode/opencode.db")
parents = json.load(sys.stdin)

try:
    result = subprocess.run(
        ["sqlite3", "-json", db_path,
         "SELECT id, title, time_updated AS updated, time_created AS created, project_id AS projectId, COALESCE(path, directory, '') AS directory FROM session WHERE parent_id IS NOT NULL ORDER BY time_updated DESC;"],
        capture_output=True, text=True, check=True
    )
    children = json.loads(result.stdout)
except:
    children = []

seen = {s["id"] for s in parents}
all_sessions = parents + [c for c in children if c["id"] not in seen]
all_sessions.sort(key=lambda s: s.get("updated", 0), reverse=True)
json.dump(all_sessions, sys.stdout)
PYEOF
        echo "$parent_sessions" | python3 "$tmpfile"
        rm -f "$tmpfile"
    else
        echo "$parent_sessions"
    fi
else
    exec "$OPENCODE_BIN" "$@"
fi
