import * as fs from "node:fs/promises";
import * as path from "node:path";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Synthetic replay: a hidden destination puts the emoji across source units 8191/8192.
const prefix = `[l](${"u".repeat(8150)}) `;
const ending = "the changelog now ";
const thought = prefix + "c".repeat(8191 - prefix.length - ending.length) + ending + "😀 tail";
const AGENT = `
import { createInterface } from 'node:readline';
import { watch, existsSync } from 'node:fs';
import { join } from 'node:path';
const send = x => process.stdout.write(JSON.stringify({jsonrpc:'2.0',...x})+'\\n');
let cwd; const sessionId='emoji-boundary';
const update = x => send({method:'session/update',params:{sessionId,update:x}});
const gate = name => new Promise(resolve => { const p=join(cwd,name); if(existsSync(p)) return resolve(); const w=watch(cwd,()=>{if(existsSync(p)){w.close();resolve();}}); });
for await (const line of createInterface({input:process.stdin})) {
 const {id,method,params}=JSON.parse(line); if(id===undefined) continue;
 if(method==='initialize') send({id,result:{protocolVersion:1,agentCapabilities:{},authMethods:[],agentInfo:{name:'Emoji boundary replay',version:'1'}}});
 else if(method==='session/new') {cwd=params.cwd;send({id,result:{sessionId}});}
 else if(method==='session/prompt') { (async()=>{
 update({sessionUpdate:'agent_thought_chunk',content:{type:'text',text:${JSON.stringify(thought)}}});
 await gate('continue-tool');
 update({sessionUpdate:'tool_call',toolCallId:'edit-changelog',kind:'edit',title:'Edit server/CHANGELOG.md',status:'in_progress',rawInput:{path:'server/CHANGELOG.md'},content:[{type:'diff',path:'server/CHANGELOG.md',oldText:'# Changelog\\n',newText:'# Changelog\\nUpdated.\\n'}]});
 await gate('finish-turn');
 update({sessionUpdate:'tool_call_update',toolCallId:'edit-changelog',status:'completed'});
 update({sessionUpdate:'agent_message_chunk',content:{type:'text',text:'Updated the changelog.'}});
 send({id,result:{stopReason:'end_turn'}});
 })(); }
 else send({id,result:{}});
}
`;

test('All three collapsed reasoning previews keep complete Unicode characters', WEB, async ({t3,app,browser,screen})=>{
 const project=await t3.project('emoji-demo',{'emoji-agent.mjs':AGENT,'server/CHANGELOG.md':'# Changelog\n'});
 const instanceId=ProviderInstanceId.make('emoji-replay');
 await runPromise(Effect.gen(function*(){const client=yield* rpcClient(T3_HOME,app.baseUrl??'');yield* client['server.updateSettings']({patch:{},providerInstanceMutation:{operation:'upsert',instanceId,instance:{driver:ProviderDriverKind.make('acpRegistry'),displayName:'Emoji boundary replay',enabled:true,config:{source:'local',commandPath:process.execPath,commandArgs:[path.join(project,'emoji-agent.mjs')]}}}});}).pipe(Effect.scoped));
 const started=await runPromise(makeState(T3_HOME).cli(['thread','start',project,'Update the changelog','--title','Emoji boundary','--provider',instanceId,'--model','default','--json']));
 const {threadId}=JSON.parse(started.stdout);
 await t3.open({threadId});
 const preview=screen.getByText('the changelog now',{exact:false}).first();
 await preview.waitFor({timeout:60000});
 // Expanding the reasoning-only live group removes its thought status line and renders
 // the reasoning-entry label in LiveWorkEntryTimelineRow's reasoning branch.
 await preview.tap();
 await app.screenshot('live-reasoning-entry-label');
 const labelText=await browser.evaluate(()=>document.body.innerText);
 await preview.tap();
 await fs.writeFile(path.join(project,'continue-tool'),'go');
 await screen.getByText('server/CHANGELOG.md',{exact:false}).first().waitFor({timeout:60000});
 await app.screenshot('live-thought-above-tool');
 const toolText=await browser.evaluate(()=>document.body.innerText);
 await fs.writeFile(path.join(project,'finish-turn'),'go');
 await screen.getByText('Updated the changelog.',{exact:true}).waitFor({timeout:60000});
 await screen.getByRole('button',/Worked for/).tap();
 await screen.getByRole('button',/Changed 1 file/).tap();
 await app.screenshot('folded-reasoning-after-completion');
 const foldedText=await browser.evaluate(()=>document.body.innerText);
 expect([labelText,toolText,foldedText].map(text=>text.includes('\uFFFD'))).toEqual([false,false,false]);
});
