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

// Deterministic ACP replay: call the real request_secret MCP tool, then check its delivered file.
const agent = `
import { createInterface } from 'node:readline';
import { readFile } from 'node:fs/promises';
import * as Effect from ${JSON.stringify(NodePath.join(APP_DIR, 'apps/server/node_modules/effect/dist/Effect.js'))};
import { mcpToolSession } from ${JSON.stringify(NodePath.join(APP_DIR, 'apps/server/src/mcp/AcpMcpStdioBridge.ts'))};
const send = message => process.stdout.write(JSON.stringify({jsonrpc:'2.0', ...message})+'\\n');
let mcp;
const sessionId = 'named-secret-replay';
async function prompt(id) {
 try {
  const env = Object.fromEntries((mcp.env ?? []).map(e => [e.name,e.value]));
  const endpoint = mcp.url ?? env.T3_ACP_MCP_ENDPOINT;
  const authorization = mcp.headers?.find(h => h.name.toLowerCase()==='authorization')?.value ?? env.T3_ACP_MCP_AUTHORIZATION;
  const result = await Effect.runPromise(Effect.gen(function*(){
   const client = yield* mcpToolSession({endpoint,authorization,clientName:'named-secret-replay'});
   return yield* client.call('request_secret',{label:'Test secret',reason:'Test saving a named field on iOS',delivery:'file',fields:[{name:'test_field',label:'Test value',secret:true}]});
  }).pipe(Effect.scoped));
  const data = result.structuredContent ?? JSON.parse(result.content.find(c=>c.type==='text').text);
  if (data.status !== 'saved' || await readFile(data.files.test_field,'utf8') !== 'test-value') throw new Error('Named field delivery did not match');
  send({method:'session/update',params:{sessionId,update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:'Named field test_field was delivered with the correct value.'}}}});
  send({id,result:{stopReason:'end_turn'}});
 } catch(error) { process.stderr.write(String(error)+'\\n'); send({id,error:{code:-32000,message:String(error)}}); }
}
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:{mcpCapabilities:{http:true}},authMethods:[],agentInfo:{name:'Secret replay',version:'1'}}});
 else if(method==='session/new') {mcp=params.mcpServers.find(s=>s.name==='t3-code');send({id,result:{sessionId}});}
 else if(method==='session/prompt') void prompt(id);
 else send({id,error:{code:-32601,message:'Method not found'}});
}
`;

test('A pre-fields client saves a request with one named secret field', WEB, async ({t3,app,screen,browser}) => {
 const project = await t3.project('secret-demo', {'secret-agent.mjs':agent});
 const instanceId = ProviderInstanceId.make('secret-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:'Secret replay',enabled:true,config:{source:'local',commandPath:process.execPath,commandArgs:[NodePath.join(project,'secret-agent.mjs')]}}}});
 }).pipe(Effect.scoped));
 const started = await runPromise(makeState(T3_HOME).cli(['thread','start',project,'Request the named test secret.','--title','Named secret request','--provider',instanceId,'--model','default','--json']));
 const {threadId} = JSON.parse(started.stdout);
 await t3.open({threadId});
 const input = browser.locator('input[type="password"]');
 await input.waitFor({timeout:60000});
 await input.fill('test-value');
 await app.screenshot('before-save');
 await screen.getByRole('button','Save securely',{exact:true}).tap();
 // Wait for either outcome before recording the same point on both servers.
 await browser.locator('text=/Could not answer the request|Named field test_field was delivered with the correct value/').waitFor({timeout:30000});
 await app.screenshot('after-save');
 await expect(screen.getByText('Test secret · Saved securely and kept private',{exact:true})).toBeVisible();
 await expect(screen.getByText('Named field test_field was delivered with the correct value.',{exact:false})).toBeVisible();
});
