#!/usr/bin/env python3
"""Read-only check against the isolated app home, before and after UI deletion."""
import json
import pathlib
import sqlite3
import sys
home = pathlib.Path(sys.argv[1]) / 'userdata'
thread_id = json.loads(pathlib.Path(sys.argv[2]).read_text())['threadId']
connection = sqlite3.connect(f'file:{home}/statev2.sqlite?mode=ro', uri=True)
row = connection.execute('select deleted_at is not null from orchestration_v2_projection_threads where thread_id=?', (thread_id,)).fetchone()
print('Thread marked deleted:', bool(row[0]))
for (raw,) in connection.execute("select payload_json from orchestration_v2_projection_turn_items where thread_id=? and type='dynamic_tool'", (thread_id,)):
    item = json.loads(raw)
    output = item.get('output')
    try:
        output = json.loads(output) if isinstance(output, str) else output
    except ValueError:
        continue
    if not isinstance(output, dict) or 'htmlRender' not in output:
        continue
    reference = output['htmlRender']
    print('Tool:', item['toolName'], 'status:', item['status'])
    print('Page:', reference['title'], 'height:', reference['height'])
    print('Matching HTML file exists:', (home / 'attachments' / (reference['attachmentId'] + '.html')).is_file())
