import { execFileSync } from "node:child_process";
import { readFileSync } from "node:fs";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NetService from "@t3tools/shared/Net";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as EnvironmentAuth from "../../apps/server/src/auth/EnvironmentAuth.ts";
import * as ServerConfig from "../../apps/server/src/config.ts";
import { resolveCliAuthConfig } from "../../apps/server/src/cli/config.ts";
import { mcpToolSession } from "../../apps/server/src/mcp/AcpMcpStdioBridge.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { runPromise, test, WEB } from "./t3.ts";

const mr = "https://gitlab.com/julius54/t3-pr-watch-proof-37741/-/merge_requests/1";
const sha = "dd499825ae742fed68e339bab8c40a0235a2e63d";
const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const status = (state: string) => execFileSync("glab", ["api", "-X", "POST", `projects/89026146/statuses/${sha}`, "-f", `state=${state}`, "-f", "name=ci-build", "-f", "ref=ci-watch"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });

test("CI passing before a new watch's first sweep wakes the thread once", WEB, async ({ t3, app, screen }) => {
  status("success");
  status("pending");
  const project = await t3.project("CI watch sample");
  execFileSync("git", ["remote", "add", "origin", "https://gitlab.com/julius54/t3-pr-watch-proof-37741.git"], { cwd: project });
  const thread = await t3.thread({ project, title: "Watch CI before first sweep", messages: ["Watch the merge request while CI is pending, then resume when checks pass."], model: "multi-turn" });
  await t3.open(thread);
  const token = await runPromise(Effect.gen(function* () {
    const config = yield* resolveCliAuthConfig({ baseDir: Option.some(T3_HOME) }, Option.none(), { quietLogs: true });
    return yield* Effect.gen(function* () {
      const auth = yield* EnvironmentAuth.EnvironmentAuth;
      const issued = yield* auth.issueMcpClientSession({ label: "CI watch proof", access: "full-access", peerLink: false, client: { deviceType: "bot" } });
      return issued.token;
    }).pipe(Effect.provide(EnvironmentAuth.layerRuntime.pipe(Layer.provide(ServerConfig.layer(config)), Layer.provide(Layer.succeed(References.MinimumLogLevel, "Error")))));
  }).pipe(Effect.provide([NetService.layer, NodeCrypto.layer])));
  const runtime = JSON.parse(readFileSync(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const call = async (tool: string) => Effect.runPromise(Effect.scoped(Effect.gen(function* () {
    const session = yield* mcpToolSession({ endpoint: `${runtime.origin}/mcp`, authorization: `Bearer ${token}`, clientName: "ci-watch-proof" });
    const result = yield* session.call(tool, { threadId: thread.threadId, url: mr });
    if ((result as { isError?: boolean }).isError) throw new Error(JSON.stringify(result));
    return result;
  })));
  try {
    await call("watch_pull_request");
    await pause(15_000);
    await app.screenshot("watch-started-ci-pending");
    status("success");
    await pause(135_000);
    await app.screenshot("ci-passed-after-first-sweep");
    await expect(screen.getByText("#1: checks passed", { exact: false }).first()).toBeVisible();
    await expect(screen.getByText("second fixture turn complete", { exact: false }).first()).toBeVisible();
  } finally {
    await call("unwatch_pull_request");
  }
});
