import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeWS from "@effect/platform-node/NodeWS";
import { ORCHESTRATION_PROTOCOL_VERSION, WsRpcGroup } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { Socket } from "effect/socket";
import fs from "node:fs";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";
const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) {
  const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]);
  const { ticket } = yield* HttpClient.execute(
    HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe(
      HttpClientRequest.bearerToken(issued.stdout.trim()),
    ),
  ).pipe(
    Effect.flatMap(HttpClientResponse.filterStatusOk),
    Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
    Effect.provide(FetchHttpClient.layer),
  );
  // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
  const protocol = yield* Layer.build(
    RpcClient.layerProtocolSocket().pipe(
      Layer.provide(
        Socket.layerWebSocket(
          `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,
        ),
      ),
      Layer.provide(RpcSerialization.layerJson),
      Layer.provide(NodeWS.layerWebSocketConstructor),
    ),
  );
  return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
});


test("Linear URL read and link reuse the validation fetch", WEB, async ({ t3, app, screen, browser }) => {
  const dir = process.env.PROOF_DIR!;
  const proxy = spawn(process.execPath,[`${dir}/linear-proxy.mjs`],{env:process.env,stdio:["ignore","pipe","pipe"]});
  await using proxyScope = { [Symbol.asyncDispose]: async () => {proxy.kill("SIGTERM");if(proxy.exitCode===null)await once(proxy,"exit");} };
  await once(proxy.stdout,"data");
  const issue = JSON.parse(fs.readFileSync(`${dir}/issue.json`, "utf8"));
  const keyFile = fs.readFileSync(`${process.env.HOME}/.config/linear-test.env`, "utf8");
  const token = keyFile.match(/^(?:export )?LINEAR_API_KEY=['"]?([^'"\n]+)/m)![1];
  const project = await t3.project("Linear URL proof");

  const origin = JSON.parse(fs.readFileSync(`${T3_HOME}/userdata/server-runtime.json`, "utf8")).origin;
  const projectId = await runPromise(Effect.gen(function* () {
    const rpc = yield* rpcClient(T3_HOME, origin);
    yield* rpc["issueTrackers.connect"]({tracker: "linear", token});
    const authToken = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
    const snapshot = yield* Effect.promise(()=>fetch(`${origin}/api/projects`,{headers:{authorization:`Bearer ${authToken.stdout.trim()}`}}).then(r=>r.json()));
    const projects = snapshot.projects;
    const projectId = projects.find((p) => p.workspaceRoot === project)!.id;
    yield* rpc["issueTrackers.bindProject"]({projectId, binding:{tracker:"linear",scope:issue.team}});
    yield* rpc["server.updateSettings"]({patch:{},providerInstanceMutation:{operation:"upsert",instanceId:"devReplay",instance:{driver:"acpRegistry",displayName:"Replay (dev)",config:{source:"local",commandPath:process.execPath,commandArgs:[`${dir}/replay-credential-tap.mjs`,`${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`]}}}});
    return projectId;
  }).pipe(Effect.scoped));
  const thread = await t3.thread({ project, title: "Read and attach a Linear URL", messages: ["Prepare the Linear URL proof"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox").first();
  await composer.waitFor({state:"visible"});
  await screen.getByText("Syncing messages...", {exact:true}).waitFor({state:"hidden"});
  await composer.fill(`Read and link this Linear URL: ${issue.url}`);
  await browser.keyboard.press("Enter");
  await screen.getByText("second fixture turn complete", {exact:false}).waitFor({state:"visible"});
  const files = fs.readdirSync(dir).filter(f=>/^runtime-/.test(f)).sort();
  const results = JSON.parse(fs.readFileSync(`${dir}/${files.at(-1)}`,"utf8"));
  await screen.getByText("Syncing messages...", {exact:true}).waitFor({state:"hidden"});
  await app.screenshot("linear-url-result");
  for (const {isError,stats} of results) {
    expect(isError).toBe(false);
    expect(stats.reads).toBe(1);
  }
});
