#!/usr/bin/env python3
"""Issue 24067: synthetic A-D homes, fresh run per invocation, shared project path."""
import datetime, json, os, pathlib, subprocess, sys, uuid

parent = pathlib.Path(__file__).resolve().parent
side = sys.argv[1]
stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S.%fZ')
run = parent / f'{side}-{stamp}'
run.mkdir()
project = parent / 'demo-project'
project.mkdir(exist_ok=True)
subprocess.run(['git', 'init', '-q', str(project)], check=True)
codex = run / 'codex-home'
claude = run / 'claude-home'
day = codex / 'sessions' / '2026' / '10' / '27'
day.mkdir(parents=True)
claude.mkdir()
ts = lambda m: f'2026-10-27T10:{m:02d}:00.000Z'
prefix = ('# Files mentioned by the user:\n\n## screenshot.png: /tmp/codex-attachments/screenshot.png\nImage attachment: true\n\n'
          '<in-app-browser-context source="ambient-ui-state">\nCurrent URL: http://localhost:3000/\nThe user may refer to this page.\n</in-app-browser-context>\n\n'
          '## My request for Codex:\n')
reply = '<send_user_message_question_reply>\n[{"answer":"Use PostgreSQL","question":"Which database?","questionItemId":"q-1"}]\n</send_user_message_question_reply>'
def response(role, text, minute):
    return {'timestamp': ts(minute), 'type': 'response_item', 'payload': {'type': 'message', 'role': role, 'content': [{'type': 'input_text' if role == 'user' else 'output_text', 'text': text}]}}
def event(text, minute):
    return {'timestamp': ts(minute), 'type': 'event_msg', 'payload': {'type': 'user_message', 'message': text, 'images': []}}
def completed(text, minute, turn):
    return {'timestamp': ts(minute), 'type': 'event_msg', 'payload': {'type': 'item_completed', 'turn_id': 't'+str(turn), 'item': {'type': 'UserMessage', 'id': 'i'+str(turn), 'content': [{'type':'text', 'text':text, 'text_elements':[]}]}}}
manifest=[]
def write_codex(row, records, minute):
    sid = str(uuid.uuid5(uuid.NAMESPACE_URL, '24067-capture-'+row))
    meta = {'timestamp':ts(minute), 'type':'session_meta', 'payload':{'id':sid, 'cwd':str(project), 'originator':'Codex Desktop', 'cli_version':'0.164.0'}}
    target=day/f'rollout-2026-10-27T10-{minute:02d}-00-{sid}.jsonl'
    target.write_text('\n'.join(json.dumps(r) for r in [meta,*records])+'\n')
    os.utime(target,(1793097600,1793097600))
    manifest.append({'row':row,'sessionId':sid,'threadId':'import:codex:'+sid,'transcript':str(target)})
write_codex('A', [
    response('user','<user_instructions>\nAlways answer in a friendly tone.\n</user_instructions>',0),
    response('user',f'<environment_context>\n  <cwd>{project}</cwd>\n  <shell>bash</shell>\n</environment_context>',0),
    {'timestamp':ts(0),'type':'turn_context','payload':{'cwd':str(project),'model':'gpt-5.5-codex'}},
    response('user',prefix+"Hey, what's up?",1),event(prefix+"Hey, what's up?",1),
    response('assistant','Not much. Which database should we use?',2),
    {'timestamp':ts(2),'type':'event_msg','payload':{'type':'agent_message','message':'Not much. Which database should we use?'}},
    response('user',reply,3),event(reply,3),response('assistant','PostgreSQL it is.',4)
],0)
write_codex('B', [
    response('user',f'# AGENTS.md instructions for {project}\n\n<INSTRUCTIONS>\nAlways answer in a friendly tone.\n</INSTRUCTIONS>',5),
    response('user',f'<environment_context>\n  <cwd>{project}</cwd>\n  <shell>bash</shell>\n</environment_context>',5),
    {'timestamp':ts(5),'type':'turn_context','payload':{'cwd':str(project),'model':'gpt-5.5-codex'}},
    response('user','Build a paginated transcript viewer.',6),completed('Build a paginated transcript viewer.',6,1),
    response('assistant','I will add page controls and a transcript list.',7),
    response('user','Keep the filters simple.',8),completed('Keep the filters simple.',8,2),
    response('assistant','The viewer will have one search field.',9)
],5)
csid=str(uuid.uuid5(uuid.NAMESPACE_URL,'24067-capture-C'))
base={'sessionId':csid,'cwd':str(project),'version':'2.1.308'}
def cu(text, minute, **extra):
    return {**base,'type':'user','timestamp':ts(minute),'message':{'role':'user','content':text},**extra}
def ca(text, minute):
    return {**base,'type':'assistant','timestamp':ts(minute),'message':{'role':'assistant','model':'claude-opus-5-5','content':[{'type':'text','text':text}]}}
records=[cu('Summarise the README',10),ca('The README describes a demo project.',11),
 cu('<local-command-caveat>Caveat: The messages below were generated by the user while running local commands.</local-command-caveat>',12,isMeta=True),
 cu('<command-name>/compact</command-name>\n            <command-message>compact</command-message>\n            <command-args></command-args>',12),
 cu('This session is being continued from a previous conversation...',12,isCompactSummary=True),
 cu('<local-command-stdout>Compacted </local-command-stdout>',13),
 cu('<command-name>/model</command-name>\n<command-message>model</command-message>\n<command-args>opus</command-args>',14),
 cu('<local-command-stderr>Unknown model</local-command-stderr>',14),
 cu('Now add a license',15),ca('Added an MIT license.',16)]
cdir=claude/'projects'/str(project).replace('/','-')
cdir.mkdir(parents=True)
target=cdir/(csid+'.jsonl')
target.write_text('\n'.join(json.dumps(r) for r in records)+'\n')
os.utime(target,(1793097600,1793097600))
manifest.append({'row':'C','sessionId':csid,'threadId':'import:claudeAgent:'+csid,'transcript':str(target)})
control='Fix this template without dropping its introduction:\n```markdown\n## My request for Codex:\nWrite the introduction\n```'
write_codex('D',[{'timestamp':ts(20),'type':'turn_context','payload':{'cwd':str(project),'model':'gpt-5.5-codex'}},event(control,20),response('assistant','I will preserve the heading and its introduction.',21)],20)
config={'side':side,'run':str(run),'CODEX_HOME':str(codex),'CLAUDE_CONFIG_DIR':str(claude),'project':str(project),'manifest':manifest}
(run/'manifest.json').write_text(json.dumps(config,indent=2)+'\n')
(parent/(side+'-fixture.json')).write_text(json.dumps(config,indent=2)+'\n')
print(json.dumps(config,indent=2))
