import { readFile, writeFile } from "node:fs/promises";
import { DatabaseSync } from "node:sqlite";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { APP_DIR } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, environmentId } from "./t3.ts";
import { prepareHome } from "./start-app.ts";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
const a = process.env.PROOF_HOME!;
const b = process.env.PROOF_REMOTE_HOME!;
const output = process.env.PROOF_OUT!;
const primary = "http://127.0.0.1:14090";
const remote = "http://127.0.0.1:14092";
const command = process.argv[2];
const first = makeState(a),
  second = makeState(b);
const transcript = `${APP_DIR}/apps/server/scripts/dev-replay/showcase_transcript.ndjson`;
const agent = `${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`;
const commandOutput = `${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`;
const turn = (text: string) => [
  { type: "expect_outbound", frame: { kind: "request", method: "session/prompt" } },
  {
    type: "emit_inbound",
    frame: {
      kind: "notification",
      method: "session/update",
      params: {
        sessionId: "dev-replay-session",
        update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
      },
    },
  },
  {
    type: "emit_inbound",
    frame: { kind: "response", method: "session/prompt", result: { stopReason: "end_turn" } },
  },
];
const encode = (entries: unknown[]) => entries.map((e) => JSON.stringify(e)).join("\n") + "\n";
const setting = () =>
  runPromise(
    Effect.gen(function* () {
      for (const [home, url] of [
        [a, primary],
        [b, remote],
      ]) {
        const rpc = yield* rpcClient(home!, url!);
        yield* rpc["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      }
    }).pipe(Effect.scoped),
  );
if (command === "prepare-remote") await runPromise(prepareHome(b));
else if (command === "setup") {
  await setting();
  const files = {
    agent: await readFile(agent, "utf8"),
    transcript: await readFile(transcript, "utf8"),
    commandOutput: await readFile(commandOutput, "utf8"),
  };
  await writeFile(`${output}/original-fixtures.json`, JSON.stringify(files));
  await writeFile(
    agent,
    files.agent
      .replace(
        'const cwd = typeof params.cwd === "string" ? params.cwd : process.cwd();',
        'const cwd = typeof params.cwd === "string" ? params.cwd : process.cwd();\nif(cwd.endsWith("/Link proof")) NodeFS.writeFileSync(' +
          JSON.stringify(`${a}/agent-mcp.json`) +
          ",JSON.stringify(params.mcpServers));",
      )
      .replace(
        "if (turn !== undefined) ended = await playTurn(sessionId, turn, controller.signal);",
        'if (turn !== undefined) ended = await playTurn(sessionId, turn, controller.signal);\nif(session.model === "command-output") await untilAbort(new Promise(() => {}),controller.signal);',
      ),
  );
  const project = await first.state.project("Link proof");
  const remoteProject = await second.state.project("Remote notes");
  const child = JSON.parse(
    (
      await runPromise(
        second.cli([
          "thread",
          "start",
          remoteProject,
          "Read these remote design notes",
          "--title",
          "Remote design notes",
          "--provider",
          "devReplay",
          "--model",
          "multi-turn",
          "--json",
        ]),
      )
    ).stdout,
  );
  const linked = await runPromise(environmentId(remote));
  const via = await runPromise(environmentId(primary));
  await writeFile(
    transcript,
    encode([
      ...turn("Ready for the remote thread."),
      ...turn(`Delegated: [Thread on B](t3-thread://v2/${linked}/${child.threadId})`),
    ]),
  );
  await writeFile(commandOutput, encode(turn("Ready for the remote review.")));
  const chat = JSON.parse(
    (
      await runPromise(
        first.cli([
          "thread",
          "start",
          project,
          "Prepare the conversation",
          "--title",
          "Chat link proof",
          "--provider",
          "devReplay",
          "--model",
          "showcase",
          "--json",
        ]),
      )
    ).stdout,
  );
  const subagent = JSON.parse(
    (
      await runPromise(
        first.cli([
          "thread",
          "start",
          project,
          "Prepare the remote review",
          "--title",
          "Subagent link proof",
          "--provider",
          "devReplay",
          "--model",
          "command-output",
          "--json",
        ]),
      )
    ).stdout,
  );
  await writeFile(
    `${output}/metadata.json`,
    JSON.stringify({
      via,
      linked,
      child: child.threadId,
      chat: chat.threadId,
      subagent: subagent.threadId,
      remoteProject,
    }),
  );
  console.log("Synthetic chat and active subagent parent ready.");
} else if (command === "link") {
  await setting();
  await runPromise(
    Effect.gen(function* () {
      const pair = yield* second.cli(["auth", "pairing", "create", "--json"]);
      const { credential } = JSON.parse(pair.stdout);
      const rpc = yield* rpcClient(a, primary);
      yield* rpc["peerLinks.link"]({ url: remote, pairingCode: credential, access: "full-access" });
    }).pipe(Effect.scoped),
  );
  console.log("Linked externally.");
} else if (command === "send") {
  const m = JSON.parse(await readFile(`${output}/metadata.json`, "utf8"));
  await runPromise(
    first.cli([
      "thread",
      "send",
      m.chat,
      `[User thread on B](t3-thread://v2/${m.linked}/${m.child})`,
      "--json",
    ]),
  );
  console.log("Sent user and replayed assistant thread links.");
} else if (command === "delegate") {
  const m = JSON.parse(await readFile(`${output}/metadata.json`, "utf8"));
  const remoteProject = await second.state.project("Delegated review");
  const db = new DatabaseSync(`${b}/userdata/statev2.sqlite`, { readOnly: true });
  const projectId = String(
    db
      .prepare("SELECT project_id FROM projection_projects WHERE workspace_root=?")
      .get(remoteProject)!.project_id,
  );
  db.close();
  const servers = JSON.parse(await readFile(`${a}/agent-mcp.json`, "utf8"));
  const config = servers.find((s: { name: string }) => s.name === "t3-code");
  const env = Object.fromEntries(
    config.env.map((e: { name: string; value: string }) => [e.name, e.value]),
  );
  await runPromise(
    Effect.gen(function* () {
      const session = yield* mcpToolSession({
        endpoint: env.T3_ACP_MCP_ENDPOINT,
        authorization: env.T3_ACP_MCP_AUTHORIZATION,
        clientName: "link-proof-replay",
      });
      yield* session.call("orchestrator_capabilities", {});
      const result = yield* session.call("delegate_task", {
        task: "Read these remote design notes",
        title: "Remote design review",
        mode: "async",
        target: {
          environmentId: yield* environmentId(remote),
          projectId,
          providerInstanceId: "devReplay",
          model: "multi-turn",
        },
      });
      if ((result as { isError?: boolean }).isError) throw new Error(JSON.stringify(result));
    }).pipe(Effect.scoped),
  );
  console.log("Real remote task delegated.");
} else if (command === "restore") {
  const files = JSON.parse(await readFile(`${output}/original-fixtures.json`, "utf8"));
  await writeFile(agent, files.agent);
  await writeFile(transcript, files.transcript);
  await writeFile(commandOutput, files.commandOutput);
}
