"""Read synthetic proof state without exporting paths, credentials, or unrelated threads.

Usage: python3 collect-evidence.py CHECKOUT THREAD_ID OUTPUT_JSON
The server may be running; SQLite is opened read-only.
"""
import json
import pathlib
import sqlite3
import subprocess
import sys

checkout = pathlib.Path(sys.argv[1]).resolve()
thread_id = sys.argv[2]
db = sqlite3.connect(f"file:{checkout}/.t3/userdata/statev2.sqlite?mode=ro", uri=True)
thread = json.loads(db.execute(
    "select payload_json from orchestration_v2_projection_threads where thread_id=?",
    (thread_id,),
).fetchone()[0])
provider_thread = json.loads(db.execute(
    "select payload_json from orchestration_v2_projection_provider_threads where thread_id=?",
    (thread_id,),
).fetchone()[0])
native_id = provider_thread["nativeThreadRef"]["nativeId"]
session = json.loads(db.execute(
    "select payload_json from orchestration_v2_projection_provider_sessions where thread_id=?",
    (thread_id,),
).fetchone()[0])
project_key = "".join(c if c.isalnum() else "-" for c in session["cwd"])
native_path = pathlib.Path.home() / ".claude/projects" / project_key / f"{native_id}.jsonl"
native_titles = []
for line in native_path.read_text().splitlines():
    row = json.loads(line)
    if row.get("type") == "custom-title":
        native_titles.append(row["customTitle"])
output = {
    "commit": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=checkout, text=True).strip(),
    "model": thread["modelSelection"]["model"],
    "t3TitleAfterFollowUp": thread["title"],
    "nativeCustomTitleHistory": native_titles,
    "nativeTitleAfterFollowUp": native_titles[-1],
}
pathlib.Path(sys.argv[3]).write_text(json.dumps(output, indent=2) + "\n")
print(json.dumps(output, indent=2))
