import * as Net from "@t3tools/shared/Net";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { GlobalFlag } from "effect/cli";
import { withThreadTools } from "../../apps/server/src/cli/thread.ts";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

const control = (path: string) => fetch(`http://127.0.0.1:13996/${path}`).then(r => r.json());
test("Stopping a watch during its first GitHub read keeps it stopped", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("watch-race");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl);
    yield* client["server.refreshProviders"]({ instanceId: "devReplay", cwd: project, fresh: true, refreshModels: true });
  }).pipe(Effect.scoped));
  const thread = await t3.thread({ project, title: "Stop during first pull request read", messages: ["Ready"], model: "multi-turn" });
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor();
  await runPromise(withThreadTools({ baseDir: Option.some(T3_HOME), json: true }, tools => Effect.promise(async () => {
    const call = (name: string, args: object) => runPromise(tools.call(name, args, Schema.Unknown));
    const args = { threadId: thread.threadId, url: "https://github.com/pingdotgg/t3code/pull/47519" };
    console.log("Initial links", JSON.stringify(await call("list_thread_pull_requests", { threadId: thread.threadId })));
    await control("arm");
    const start = call("watch_pull_request", args);
    try {
      // The proxy only buffers bytes returned by the real GitHub API.
      for (let i=0; i<200; i++) {
        if ((await control("status")).held > 0) break;
        if(i===199) throw new Error("No real GitHub response reached the buffering proxy");
        await new Promise(resolve => setTimeout(resolve, 100));
      }
      console.log("Initial host read held");
      console.log("Stop completed", JSON.stringify(await call("unwatch_pull_request", args)));
      console.log("Links after stop", JSON.stringify(await call("list_thread_pull_requests", { threadId: thread.threadId })));
    } finally { await control("release"); }
    const result = await start as { watching: boolean };
    console.log("Earlier start completed", JSON.stringify(result));
    console.log("Final links", JSON.stringify(await call("list_thread_pull_requests", { threadId: thread.threadId })));
    await screen.getByRole("textbox").waitFor();
    if (result.watching) await screen.getByText("Watching pull request #47519", { exact: false }).waitFor();
    await app.screenshot("After releasing the initial GitHub read");
    await new Promise(resolve => setTimeout(resolve, 500));
    await app.screenshot("Settled after releasing the initial GitHub read");
    expect(result.watching).toBe(false);
  })).pipe(Effect.provideService(GlobalFlag.LogLevel, Option.none()), Effect.provide(Net.layer), Effect.provide(NodeCrypto.layer)));
});
