import { readdir, readFile } from "node:fs/promises";
import * as Effect from "effect/Effect";
import { expect } from "e2e";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";

import { runPromise } from "./t3.ts";

// Use the credential issued to this synthetic replay thread, without logging it.
async function agentTool(threadId: string, tool: string, args: Record<string, unknown>) {
  for (const pid of await readdir("/proc")) {
    if (!/^\d+$/.test(pid)) continue;
    const env = await readFile(`/proc/${pid}/environ`, "utf8").catch(() => "");
    const entries = Object.fromEntries(env.split("\0").map((line) => {
      const at = line.indexOf("=");
      return [line.slice(0, at), line.slice(at + 1)];
    }));
    if (entries.T3CODE_THREAD_ID !== threadId || !entries.T3_ACP_MCP_AUTHORIZATION) continue;
    return runPromise(Effect.gen(function* () {
      const session = yield* mcpToolSession({ endpoint: entries.T3_ACP_MCP_ENDPOINT!, authorization: entries.T3_ACP_MCP_AUTHORIZATION!, clientName: "preview-proof" });
      const result = yield* session.call(tool, args);
      if ((result as { isError?: boolean }).isError) throw new Error(JSON.stringify(result));
      return result;
    }).pipe(Effect.scoped));
  }
  throw new Error("Synthetic replay thread has no MCP credential");
}

import { makeState } from './t3.ts';
const [home, output, port] = process.argv.slice(2);
const fixture = makeState(home!, { T3CODE_PORT: port! });
const project = await fixture.state.project('Browser demo');
const launched = await runPromise(fixture.cli(['thread', 'start', project, 'Open the preview', '--title', 'Browser handoff', '--provider', 'devReplay', '--model', 'showcase', '--json']));
const seed = JSON.parse(launched.stdout);
await import('node:fs/promises').then(fs => fs.writeFile(output!, JSON.stringify({project,...seed})));
let result;
for(let i=0;i<12;i++) {
 try { result = await agentTool(seed.threadId, 'preview_open', { url: 'https://example.com' }); break; }
 catch(e) { if(i===11) throw e; await new Promise(r=>setTimeout(r,200)); }
}
console.log(JSON.stringify(result));
