"""Prints the preview_snapshot tool result recorded in a dev server's own database.

Usage: python3 -I extract.py <statev2.sqlite> <thread-id>
"""
import json
import sqlite3
import sys

db, thread = sys.argv[1], sys.argv[2]
con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
rows = con.execute(
    "select payload_json from orchestration_v2_projection_turn_items where thread_id = ? and type = 'dynamic_tool' order by ordinal",
    (thread,),
).fetchall()


def find_snapshot(node):
    if isinstance(node, dict):
        if "visibleText" in node and "url" in node:
            return node
        for value in node.values():
            found = find_snapshot(value)
            if found:
                return found
    elif isinstance(node, list):
        for value in node:
            found = find_snapshot(value)
            if found:
                return found
    elif isinstance(node, str) and '"visibleText"' in node:
        try:
            return find_snapshot(json.loads(node))
        except ValueError:
            return None
    return None


for (payload,) in rows:
    snap = find_snapshot(json.loads(payload))
    if not snap:
        continue
    print("url:", snap.get("url"))
    print("visibleText chars:", len(snap["visibleText"]))
    print("visibleText head:", repr(snap["visibleText"][:120]))
    print("accessibilityTree chars:", len(snap.get("accessibilityTree") or ""))
    print("snapshot JSON bytes:", len(json.dumps(snap, ensure_ascii=False, separators=(",", ":")).encode()))
    print("omitted:", json.dumps(snap.get("omitted")))
