"""Read this proof's fresh dev databases and preserve real device_open responses.
Usage: python3 extract-responses.py BASE_CHECKOUT HEAD_CHECKOUT
Run beside reproduction-driver.py, while both dev servers and device leases are still running.
"""
import sys,sqlite3,json
from pathlib import Path
for side,root in zip(['base','head'],sys.argv[1:]):
    database=Path(root).resolve()/'.t3/userdata/statev2.sqlite'
    connection=sqlite3.connect(database.as_uri()+'?mode=ro',uri=True)
    responses=[]
    for (payload,) in connection.execute('select payload_json from orchestration_v2_projection_turn_items where type="dynamic_tool"'):
        item=json.loads(payload)
        output=item.get('output')
        try:
            while isinstance(output,str):output=json.loads(output)
            if isinstance(output,dict) and 'quickStart' in output:responses.append(output)
        except (ValueError,TypeError):pass
    if not responses:raise RuntimeError('No real device_open response found for '+side)
    (Path(__file__).parent/(side+'-opened-private.json')).write_text(json.dumps(responses))
    print(side, 'saved',len(responses),'real responses; keep this file private')
