#!/usr/bin/env python3
"""Synthetic schedule proof fixtures. Run from either checkout; never use live data.
Setup: python driver.py seed --agent /absolute/path/quota-agent.mjs
Start with T3CODE_DEV_SEED=0 vp run dev. Add a demo git project with t3 project add.
Start Quota runner using quotaReplay/showcase and Runner using devReplay/showcase.
In Settings > Scheduled tasks create Quota bookkeeping and Morning bookkeeping:
  prompt: Do the daily bookkeeping.; weekdays 09:00; One thread, continuing the
  conversation; choose Schedule demo and the respective existing thread.
Record browser: Actions for Quota bookkeeping > Run now, then Actions for Morning
bookkeeping > Run now. Wait for both turns to terminate; inspect task badges.
Stop dev; run `python driver.py missed`; restart same dev command, reconnect,
and record Settings. Run `python driver.py status` for supporting runtime rows.
"""
import argparse, json, pathlib, shutil, sqlite3
from datetime import datetime, timezone, timedelta
p=argparse.ArgumentParser(); p.add_argument('action',choices=['seed','missed','status']);p.add_argument('--agent'); a=p.parse_args()
home=pathlib.Path('.t3/userdata')
if a.action=='seed':
    home.mkdir(parents=True,exist_ok=True)
    settings={'defaultModelSelection':{'instanceId':'devReplay','model':'showcase'},'providerInstances':{k:{'driver':k,'enabled':False} for k in ['codex','claudeAgent','cursor','grok','muse','pi','opencode','antigravity']}}
    settings['providerInstances']['quotaReplay']={'driver':'acpRegistry','displayName':'Quota replay','enabled':True,'config':{'source':'local','commandPath':shutil.which('node'),'commandArgs':[str(pathlib.Path(a.agent).resolve()),str(pathlib.Path('apps/server/scripts/dev-replay-agent.ts').resolve())]}}
    (home/'settings.json').write_text(json.dumps(settings))
else:
    db=sqlite3.connect(f'file:{home}/statev2.sqlite?mode={"rw" if a.action=="missed" else "ro"}',uri=True)
    db.row_factory=sqlite3.Row
    if a.action=='missed':
        due=(datetime.now(timezone.utc)-timedelta(minutes=25)).isoformat(timespec='milliseconds').replace('+00:00','Z')
        db.execute("update scheduled_tasks set next_run_at=? where title='Morning bookkeeping'",[due]);db.commit()
        print(json.dumps({'simulatedMissedSlot':due}))
    print(json.dumps({'tasks':[dict(x) for x in db.execute('select title,next_run_at,last_run_at,last_run_status,last_run_error,run_count from scheduled_tasks order by title')], 'runs':[dict(x) for x in db.execute("select t.title,json_extract(r.payload_json,'$.ordinal') ordinal,json_extract(r.payload_json,'$.status') status,json_extract(r.payload_json,'$.requestedAt') requestedAt,json_extract(r.payload_json,'$.completedAt') completedAt,(select json_extract(i.payload_json,'$.failure.message') from orchestration_v2_projection_turn_items i where i.run_id=r.run_id and json_extract(i.payload_json,'$.type')='error' limit 1) error from orchestration_v2_projection_runs r join orchestration_v2_projection_threads t on r.thread_id=t.thread_id where t.title in ('Runner','Quota runner') order by t.title,ordinal")]},indent=2))
