# Rewrites the last assistant message of the "R01" thread in an isolated dev DB to the
# issue-21008 fixture, in both the message and turn-item projections.
import sqlite3, json, sys
db = sys.argv[1]
MARKER = "R01_POLISHED_R2"
TEXT = """Reporter fixture:

1. First
2. Second
3. Third

Ten items (multi-digit path):

8. Eight
9. Nine
10. Ten

Nested:

1. Outer
   1. Inner a
   2. Inner b
2. Outer two
   - bullet child

Tasks:

1. [x] Done task
2. [ ] Open task

<!-- i21008 -->"""
c = sqlite3.connect(db)
def patch(o):
    if isinstance(o, dict):
        for k, v in o.items():
            if isinstance(v, str) and (MARKER in v or "<!-- i21008 -->" in v): o[k] = TEXT
            else: patch(v)
    elif isinstance(o, list):
        for v in o: patch(v)
for table, key in (("orchestration_v2_projection_messages", "message_id"), ("orchestration_v2_projection_turn_items", "turn_item_id")):
    rows = c.execute(f"SELECT {key}, payload_json FROM {table} WHERE payload_json LIKE ? OR payload_json LIKE ?", (f"%{MARKER}%", "%i21008%")).fetchall()
    for rid, payload in rows:
        item = json.loads(payload); patch(item)
        c.execute(f"UPDATE {table} SET payload_json=? WHERE {key}=?", (json.dumps(item), rid))
    print(table, len(rows))
c.commit()
