import fs from "node:fs";
import crypto from "node:crypto";
import * as NodeWS from "@effect/platform-node/NodeWS";
import { ORCHESTRATION_PROTOCOL_VERSION, WsRpcGroup } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { Socket } from "effect/socket";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("An agent reads a Linear issue by HTTPS URL and rejects another workspace", WEB,
  async ({ t3, app, screen }) => {
    const workspace = await t3.project("Linear URL proof");
    const { stdout } = await runPromise(makeState(T3_HOME).cli([
      "auth", "session", "issue", "--token-only",
    ]));
    const origin = app.baseUrl!;
    const headers = { authorization: `Bearer ${stdout.trim()}` };
    const snapshot = await fetch(`${origin}/api/projects`, { headers }).then(r => r.json());
    const project = snapshot.projects.find(p => p.workspaceRoot === workspace);
    if (!project) throw new Error("Seeded project missing from server snapshot");
    const { ticket } = await fetch(`${origin}/api/auth/websocket-ticket`, {
      method: "POST", headers,
    }).then(r => r.json());
    const threadId = crypto.randomUUID();
    await runPromise(Effect.gen(function* () {
      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),
      ));
      const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
      yield* client["issueTrackers.connect"]({ tracker: "linear", token: process.env.LINEAR_API_KEY });
      yield* client["issueTrackers.bindProject"]({
        projectId: project.id,
        binding: { tracker: "linear", scope: process.env.LINEAR_TEST_TEAM_KEY },
      });
      yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
        operation: "upsert", instanceId: "linearProof", instance: {
          driver: "acpRegistry", displayName: "Linear proof (scripted)", enabled: true,
          config: { source: "local", commandPath: process.execPath, commandArgs: [
            process.env.LINEAR_PROOF_AGENT,
            process.env.LINEAR_PROOF_FIXTURE,
            `${process.env.LINEAR_PROOF_OUTPUT}/scenario-${threadId}.json`,
          ] },
        },
      } });
      yield* client["orchestration.launchThread"]({
        commandId: crypto.randomUUID(), threadId, projectId: project.id,
        title: "Linear issue URL verification",
        modelSelection: { instanceId: "linearProof", model: "linear-proof" },
        runtimeMode: "full-access", interactionMode: "default", workspaceStrategy: { type: "root" },
      });
    }).pipe(Effect.scoped));
    await t3.open({ threadId });
    await screen.getByRole("button", "Toggle main sidebar").tap();
    await screen.getByRole("button", "Toggle thread details panel").tap();
    const composer = screen.getByRole("textbox", "Message Linear issue URL verification");
    await composer.fill("Read the synthetic Linear issue by its full HTTPS URL. Check the same issue by identifier as a control, and reject a URL with another workspace and the same issue key.");
    await composer.press("Enter");
    await screen.getByText("Different workspace, same key: REJECTED", { exact: false }).waitFor();
    await screen.getByRole("button", "Stop generation").waitFor({ state: "hidden" });
    await app.screenshot("linear-url-result");
    await expect(screen.getByText("Full HTTPS URL: SUCCESS", { exact: false })).toBeVisible();
  },
);
