"""Projection-only fixtures. Invoke --apply only with isolated backend stopped."""
import sqlite3,json,sys,shutil,time
from pathlib import Path
p=Path('/tmp/t3-issue-24223-runtime/userdata/statev2.sqlite')
c=sqlite3.connect('file:'+str(p)+'?mode=ro',uri=True)
template=json.loads(c.execute("select payload_json from orchestration_v2_projection_threads where thread_id='mermaid-repro'").fetchone()[0]); c.close()
t='2026-10-26T06:00:00.000Z'; rows=[]; payloads=[]
small='```mermaid\nflowchart TD\n A[Start] --> B[Finish]\n```'
wide='```mermaid\nflowchart LR\n A[Receive a very long incoming request] --> B[Validate all required deployment parameters] --> C[Prepare the complete deployment artifact] --> D[Publish and verify successful deployment]\n```'
def row(table,d): rows.append((table,d))
def fixture(slug,title,items):
 tid='proof-'+slug
 thread={**template,'id':tid,'title':title}
 row('orchestration_v2_projection_threads',dict(thread_id=tid,project_id=thread['projectId'],title=title,default_provider='codex',runtime_mode='full-access',interaction_mode='default',created_at=t,updated_at=t,payload_json=json.dumps(thread)))
 payloads.append(('OrchestrationV2AppThread',thread))
 for n,(kind,text) in enumerate(items):
  iid=tid+'-item-'+str(n)
  i=dict(id=iid,threadId=tid,runId=None,nodeId=None,providerThreadId=None,providerTurnId=None,nativeItemRef=None,parentItemId=None,ordinal=n,status='completed',title=None,startedAt=t,completedAt=t,updatedAt=t,type=kind)
  if kind in ['assistant_message','user_message']:
   mid=tid+'-msg-'+str(n); role='user' if kind=='user_message' else 'assistant'
   m=dict(id=mid,threadId=tid,runId=None,nodeId=None,role=role,text=text,attachments=[],streaming=False,createdAt=t,updatedAt=t,createdBy='user' if role=='user' else 'agent',creationSource='mobile' if role=='user' else 'provider')
   payloads.append(('OrchestrationV2ConversationMessage',m))
   row('orchestration_v2_projection_messages',dict(message_id=mid,thread_id=tid,role=role,streaming=0,created_at=t,updated_at=t,payload_json=json.dumps(m)))
   i.update(messageId=mid,text=text)
   if kind=='assistant_message': i['streaming']=False
   else: i.update(createdBy='user',creationSource='mobile',inputIntent='turn_start',attachments=[])
  elif kind=='proposed_plan': i.update(planId=tid+'-plan',markdown=text,streaming=False)
  else: i.update(text=text,streaming=False)
  payloads.append(('OrchestrationV2TurnItem',i))
  row('orchestration_v2_projection_turn_items',dict(turn_item_id=iid,thread_id=tid,ordinal=n,type=kind,status='completed',updated_at=t,payload_json=json.dumps(i)))
fixture('01','Proof 01 assistant widths',[('assistant_message','# Deployment flow\n\nBefore small diagram.\n\n'+small+'\n\nBetween diagrams.\n\n'+wide+'\n\nAfter diagrams.\n\n- Verify output\n- Keep original order\n\n```ts\nconst done = true;\n```')])
fixture('02','Proof 02 proposed plan',[('proposed_plan','# Deployment plan\n\nPrepare the release.\n\n'+small+'\n\n'+wide+'\n\n- [ ] Validate\n- [ ] Deploy')])
fixture('03','Proof 03 lone reasoning',[('reasoning','Reasoning before diagram.\n\n'+wide+'\n\n'+'\n\n'.join('Reasoning tail paragraph '+str(x)+'. Check scrolling boundaries.' for x in range(12))),('assistant_message','Reasoning completed; feed tail remains reachable.')])
fixture('04','Proof 04 grouped reasoning',[('reasoning','First thought.\n\n'+wide+'\n\n'+'\n\n'.join('First thought tail '+str(x) for x in range(12))),('reasoning','Second thought.\n\n'+small+'\n\nSecond thought tail preserved.'),('assistant_message','Grouped reasoning completed; feed tail remains reachable.')])
fixture('07','Proof 07 invalid fallback',[('assistant_message','Valid before.\n\n'+small+'\n\n```mermaid\nthis is not a valid diagram !!!\n```\n\nValid after.\n\n'+small)])
fixture('09','Proof 09 fence variants',[('assistant_message','Uppercase tilde CRLF:\n\n~~~Mermaid\r\nflowchart TD\r\n A[Uppercase] --> B[Tilde]\r\n~~~~\r\n\nInfo suffix:\n\n```mermaid extra\nflowchart TD\n A[Info] --> B[Suffix]\n```\n\n'+small+'\n\n'+small+'\n\nVariants tail.')])
fixture('10','Proof 10 parser controls',[('assistant_message','Empty fence:\n\n```mermaid\n\n```\n\nIndented:\n\n  ```mermaid\n  flowchart TD\n   A --> B\n  ```\n\nNested:\n\n````text\n```mermaid\nflowchart TD\n A --> B\n```\n````\n\nInline `mermaid`.\n\n```python\nprint("control")\n```\n\nOpen fence:\n\n```mermaid\nflowchart TD\n A[Open] --> B[Unclosed]')])
fixture('11','Proof 11 markdown context',[('assistant_message','[Guide][g]\n\n1. First numbered item\n\n'+small+'\n\n2. Second numbered item\n\n[g]: https://example.com\n\nContext tail.')])
fixture('12','Proof 12 artifact ordering',[('assistant_message','Before template.\n\n::artifact-template{skill_name="artifact-template-proof" skill_directory="/tmp/issue-24223-template" display_name="Proof template" artifact_kind="document"}\n\nBetween template and diagram.\n\n'+small+'\n\n[Local scratch](/tmp/issue-24223-seed.py)\n\nAfter diagram.')])
fixture('13','Proof 13 user control',[('user_message','User diagram must remain code:\n\n'+small),('assistant_message','Plain assistant response. No Mermaid content.')])
fixture('14','Proof 14 escaped labels',[('assistant_message','Escaped HTML and links disabled.\n\n```mermaid\nflowchart TD\n A["<b>HTML label</b>"] --> B["Safe destination"]\n click B "https://example.com"\n```\n\nFeed tail.')])
Path('/tmp/issue-24223-fixture-payloads.json').write_text(json.dumps(payloads))
Path('/tmp/issue-24223-fixture-rows.json').write_text(json.dumps(rows))
if '--apply' not in sys.argv:
 print('Prepared',len(rows),'rows; no database writes. Validate payloads before --apply.'); sys.exit()
shutil.copy2(p,str(p)+'.proof-backup-'+str(int(time.time())))
c=sqlite3.connect(p)
for table,d in rows:
 c.execute('INSERT OR REPLACE INTO '+table+' ('+','.join(d)+') VALUES ('+','.join('?' for _ in d)+')',list(d.values()))
c.commit();c.close();print('Applied',len(rows),'projection rows')
