"""Read only the supplied isolated T3 database and its synthetic Claude sessions.
Usage: python3 inspect.py CHECKOUT SIDE > session-evidence.json
"""
import json
from pathlib import Path
import sqlite3
import sys

checkout, side = Path(sys.argv[1]).resolve(), sys.argv[2]
db = sqlite3.connect(f"file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro", uri=True)
def rows(table):
    return [json.loads(r[0]) for r in db.execute(f"select payload_json from {table}")]
runs = rows("orchestration_v2_projection_runs")
threads = rows("orchestration_v2_projection_provider_threads")
handoffs = rows("orchestration_v2_projection_context_handoffs")
private_paths = set()
out = {"side": side, "commit": __import__('subprocess').check_output(
    ["git", "-C", str(checkout), "rev-parse", "HEAD"], text=True).strip(),
    "runs": [{k: r.get(k) for k in ["threadId", "ordinal", "status", "requestedAt", "startedAt", "completedAt"]} for r in runs],
    "handoffs": [{k: h.get(k) for k in ["threadId", "strategy", "coveredRunOrdinals"]} for h in handoffs],
    "providerThreads": []}
for t in threads:
    sid = t["nativeThreadRef"]["nativeId"]
    entry = {"threadId": t["appThreadId"], "nativeSessionId": sid,
             "forkedFrom": t.get("forkedFrom"), "transcript": []}
    files = list((Path.home() / ".claude/projects").glob("*/" + sid + ".jsonl"))
    for f in files:
        for line in f.read_text().splitlines():
            r = json.loads(line)
            if r.get("type") not in ["user", "assistant"]:
                continue
            message = {"role": r["type"], "uuid": r.get("uuid"), "timestamp": r.get("timestamp"), "content": []}
            content = r.get("message", {}).get("content", [])
            if isinstance(content, str):
                message["content"] = content if len(content) < 300 else content[:100] + " [remaining handoff text omitted]"
            else:
                for c in content:
                    kind = c.get("type")
                    item = {"type": kind}
                    if kind == "tool_use":
                        item.update(name=c.get("name"), id=c.get("id"))
                        if c.get("name") == "Read":
                            path = c.get("input", {}).get("file_path", "")
                            private_paths.add(path)
                            item["file"] = Path(path).name
                    elif kind == "tool_result":
                        item.update(tool_use_id=c.get("tool_use_id"), content=c.get("content"))
                    elif kind == "text":
                        text = c.get("text", "")
                        item["text"] = text if len(text) < 400 else text[:100] + " [remaining story omitted]"
                    message["content"].append(item)
            entry["transcript"].append(message)
    out["providerThreads"].append(entry)
serialized = json.dumps(out, indent=2)
for path in private_paths:
    if path:
        serialized = serialized.replace(path, Path(path).name)
print(serialized)
