#!/usr/bin/env python3
"""Synthetic fixture for the recovery-read failure. No live data is used.
Run the checkout's scripts/scenarios/start-app.ts web HOME 127.0.0.1 PORT first.
Usage: recovery-driver.py CHECKOUT HOME seed|arm|state
AI-assisted; verified with the tests and tools listed above.
"""
import json
import pathlib
import sqlite3
import subprocess
import sys

checkout, home, action = pathlib.Path(sys.argv[1]), pathlib.Path(sys.argv[2]), sys.argv[3]
def run(args, cwd=checkout):
    return subprocess.check_output(args, cwd=cwd, text=True)
def cli(*args):
    return run(["node", "apps/server/src/bin.ts", *args, "--base-dir", str(home)])
if action == "seed":
    workspace = home / "workspaces" / "recovery-demo"
    workspace.mkdir(parents=True)
    (workspace / "README.md").write_text("Synthetic recovery failure reproduction.\n")
    run(["git", "init", "--quiet", "--initial-branch=main"], workspace)
    run(["git", "add", "."], workspace)
    run(["git", "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--quiet", "-m", "Initial commit"], workspace)
    cli("project", "add", str(workspace), "--title", "recovery-demo")
    cli("thread", "start", str(workspace), "Prepare a short reply", "--title", "Recovery failure demo", "--provider", "devReplay", "--model", "showcase", "--wait", "--json")
    print("Initial turn completed.")
else:
    db = sqlite3.connect(home / "userdata" / "statev2.sqlite", timeout=5)
    thread_id = db.execute("SELECT thread_id FROM orchestration_v2_projection_threads WHERE title = 'Recovery failure demo'").fetchone()[0]
    if action == "arm":
        db.executescript("""
        CREATE TRIGGER corrupt_recovery_on_followup AFTER INSERT ON orchestration_v2_projection_messages
        WHEN NEW.thread_id = '%s' AND NEW.role = 'user'
        BEGIN
          INSERT INTO orchestration_v2_projection_turn_items
            (turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,
             type, status, ordinal, updated_at, payload_json)
          VALUES ('synthetic-unreadable-recovery', NEW.thread_id, NULL, NULL, NULL, NULL,
            'command_execution', 'running', -1, NEW.created_at, '{"obsolete":true}');
        END;
        """ % thread_id)
        print("The next user message will insert the malformed recovery item.")
    elif action == "state":
        db.row_factory = sqlite3.Row
        queries = {
            "runs": "SELECT ordinal,status FROM orchestration_v2_projection_runs ORDER BY ordinal",
            "attempts": "SELECT r.ordinal AS run,a.status FROM orchestration_v2_projection_run_attempts a JOIN orchestration_v2_projection_runs r ON r.run_id=a.run_id ORDER BY r.ordinal",
            "roots": "SELECT r.ordinal AS run,n.status FROM orchestration_v2_projection_nodes n JOIN orchestration_v2_projection_runs r ON r.run_id=n.run_id WHERE n.kind='root_turn' ORDER BY r.ordinal",
            "startEffects": "SELECT status,attempt_count, CASE WHEN last_error LIKE '%ProjectionStoreReadError%' THEN 'ProjectionStoreReadError at getRuntimeRecoveryProjection' ELSE NULL END AS error FROM orchestration_v2_effect_outbox WHERE effect_type='provider-turn.start' ORDER BY created_at",
            "errors": "SELECT json_extract(payload_json,'$.title') AS title FROM orchestration_v2_projection_turn_items WHERE type='error'",
        }
        print(json.dumps({name:[dict(row) for row in db.execute(query)] for name,query in queries.items()}, indent=2))
    else:
        raise ValueError("Unknown action")
