import * as Http from "node:http";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { run } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

// Fault injection only: every request reaches the real peer; the first two import
// replies are discarded after the real peer has processed them. No response is invented.
function loseImportReplies(target: string) {
  let imports = 0;
  let origin = "";
  const recovered = Promise.withResolvers<void>();
  const proxy = Http.createServer(async (request, response) => {
    const chunks: Buffer[] = [];
    for await (const chunk of request) chunks.push(Buffer.from(chunk));
    const body = Buffer.concat(chunks);
    const isImport = body.toString().includes('"name":"t3_thread_import"');
    if (isImport) imports++;
    const ordinal = imports;
    const forwardedBody = request.url?.startsWith("/oauth")
      ? Buffer.from(body.toString().replaceAll(origin, target).replaceAll(encodeURIComponent(origin), encodeURIComponent(target)))
      : body;
    const forwardedPath = (request.url ?? "/").replaceAll(encodeURIComponent(origin), encodeURIComponent(target));
    const requestHeaders = { ...request.headers, host: new URL(target).host, "accept-encoding": "identity" };
    delete requestHeaders["content-length"];
    const upstream = Http.request(`${target}${forwardedPath}`, {
      method: request.method,
      headers: requestHeaders,
    }, async (reply) => {
      const received: Buffer[] = [];
      for await (const chunk of reply) received.push(Buffer.from(chunk));
      const payload = Buffer.concat(received);
      if (isImport) console.log(`Real import ${ordinal}: ${payload.toString()}`);
      if (isImport && ordinal <= 2) {
        response.destroy();
        return;
      }
      const headers = { ...reply.headers };
      delete headers['content-length'];
      delete headers['transfer-encoding'];
      response.writeHead(reply.statusCode ?? 500, headers);
      response.end(payload.toString().replaceAll(target, origin));
      if (isImport && ordinal >= 3) recovered.resolve();
    });
    upstream.on('error', (error) => { response.destroy(error); recovered.reject(error); });
    upstream.end(forwardedBody);
  });
  return {
    async start() {
      await new Promise<void>((resolve) => proxy.listen(0, '127.0.0.1', resolve));
      const address = proxy.address();
      if (address === null || typeof address === 'string') throw new Error('No proxy address');
      origin = `http://127.0.0.1:${address.port}`;
      return origin;
    },
    recovered: recovered.promise,
    stop: () => new Promise<void>((resolve) => { proxy.closeAllConnections(); proxy.close(() => resolve()); }),
  };
}

test("A definite import refusal releases a move after its earlier reply was lost", WEB,
async ({ t3, app, screen }) => {
  const source = await t3.project("handoff-demo", { "app.ts": "export const version = 1;\n" });
  const thread = await t3.thread({ project: source, title: "Fix login", messages: ["first"] });
  const second = startSecondServer(app.baseUrl ?? "");
  let proxy: ReturnType<typeof loseImportReplies> | undefined;
  try {
    const { host } = await second.ready;
    const destination = await makeState(SECOND_HOME).state.project("handoff-demo");
    const issued = await runPromise(makeState(SECOND_HOME).cli(["auth", "session", "issue", "--token-only"]));
    const snapshot = await (await fetch(`${host}/api/projects`, { headers: { authorization: `Bearer ${issued.stdout.trim()}` } })).json() as { projects: { id: string; workspaceRoot: string }[] };
    const destinationId = snapshot.projects.find((p) => p.workspaceRoot === destination)?.id;
    if (!destinationId) throw new Error("Destination project was not registered");
    const git = (cwd: string, args: string[]) => runPromise(run("git", args, { cwd }));
    await git(destination, ["fetch", source, "main"]);
    await git(destination, ["reset", "--hard", "FETCH_HEAD"]);
    for (const cwd of [source, destination]) {
      await git(cwd, ["remote", "add", "origin", "https://github.com/scenario/handoff-demo.git"]);
      await git(cwd, ["config", `url.${source}.insteadOf`, "https://github.com/scenario/handoff-demo.git"]);
      await git(cwd, ["checkout", "-b", "fix/login"]);
      await git(cwd, ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", cwd === source ? "Source login fix" : "Destination independent fix"]);
    }
    await git(destination, ["checkout", "main"]);
    proxy = loseImportReplies(host);
    const peerUrl = await proxy.start();
    const prepare = await runPromise(Effect.gen(function* () {
      const primary = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      const peer = yield* rpcClient(SECOND_HOME, host);
      for (const client of [primary, peer]) {
        yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      }
      const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]);
      const { credential } = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Struct({ credential: Schema.String })))(pairing.stdout);
      yield* primary["peerLinks.link"]({ url: peerUrl, pairingCode: credential, access: "full-access" });
      return yield* primary["threadHandoff.options"]({ threadId: ThreadId.make(thread.threadId) });
    }).pipe(Effect.scoped));
    const option = prepare.options[0];
    if (!option) throw new Error(`No destination project: ${JSON.stringify(prepare)}`);
    await t3.open(thread);
    await screen.getByRole("textbox").waitFor();
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["threadHandoff.start"]({ threadId: ThreadId.make(thread.threadId), environmentId: option.environmentId, projectId: ProjectId.make(destinationId) }).pipe(Effect.result);
    }).pipe(Effect.scoped));
    await screen.getByText("Moving to Scenario…", { exact: true }).waitFor();
    await app.screenshot("move-waiting-for-confirmation");
    await Promise.race([proxy.recovered, new Promise((_, reject) => setTimeout(() => reject(new Error("No real recovery import within 75 seconds")), 75_000))]);
    // Let the response's persisted event arrive in the web client before capturing both outcomes.
    await runPromise(Effect.sleep("1 second"));
    await app.screenshot("after-definite-import-refusal");
    await expect(screen.getByText("Could not move to Scenario", { exact: true })).toBeVisible();
    await expect(screen.getByText(/commits the handed-off work lacks/)).toBeVisible();
    await expect(screen.getByRole("textbox")).toBeEnabled();
  } finally {
    await proxy?.stop();
    await second.stop();
  }
});
