#!/usr/bin/env python3
"""Offline fixture used for this proof. Stop the task's server before running.
Usage: python3 fixture.py CHECKOUT/.t3/userdata/statev2.sqlite THREAD_ID
Seed through CLI first, finish todo-list Replay turn, and click Settle thread.
Only nativeThreadRef is changed. No event, run, binding, or association is changed.
"""
import json
import sqlite3
import sys

with sqlite3.connect(sys.argv[1]) as db:
    thread_id = sys.argv[2]
    bindings = db.execute('SELECT count(*) FROM orchestration_v2_projection_provider_session_bindings WHERE thread_id=?', (thread_id,)).fetchone()[0]
    assert bindings == 0, 'Settle the completed thread before applying this fixture'
    rows = db.execute('SELECT provider_thread_id,payload_json FROM orchestration_v2_projection_provider_threads WHERE thread_id=?', (thread_id,)).fetchall()
    assert len(rows) == 1
    provider_thread_id, raw = rows[0]
    before = json.loads(raw)
    assert before['providerInstanceId'] == 'devReplay'
    assert before['appThreadId'] == thread_id
    db.execute("UPDATE orchestration_v2_projection_provider_threads SET payload_json=json_set(payload_json,'$.nativeThreadRef',null) WHERE provider_thread_id=?", (provider_thread_id,))
    after = json.loads(db.execute('SELECT payload_json FROM orchestration_v2_projection_provider_threads WHERE provider_thread_id=?', (provider_thread_id,)).fetchone()[0])
    assert after == {**before, 'nativeThreadRef': None}
    print(json.dumps({'bindingCount': bindings, 'nativeThreadRef': after['nativeThreadRef'], 'sourceProvider': after['providerInstanceId'], 'associationPreserved': True}))
