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 { readFile } from "node:fs/promises";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";
import { run } from "./shell.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("Custom Enterprise issue URL reads through its project and opens the issue panel", WEB, async ({t3,app,screen,browser}) => {
  const project=await t3.project("Enterprise web", {
    "README.md":"Synthetic Enterprise issue proof.\n",
    ".git/config":'[remote "origin"]\n  url = https://code.acme.test/acme/web.git\n  fetch = +refs/heads/*:refs/remotes/origin/*\n'
  });
  const testedSha=(await runPromise(run("git",["rev-parse","HEAD"],{cwd:APP_DIR}))).stdout.trim();
  const runtime=JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`,"utf8"));
  await runPromise(Effect.gen(function*(){
    const client=yield* rpcClient(T3_HOME,runtime.origin);
    yield* client["server.updateSettings"]({patch:{},providerInstanceMutation:{operation:"upsert",instanceId:"issueReplay",instance:{driver:"acpRegistry",displayName:"Issue proof replay",enabled:true,config:{source:"local",commandPath:process.execPath,commandArgs:[process.env.ISSUE_PROOF_AGENT_PATH!,testedSha]}}}});
  }).pipe(Effect.scoped));
  const result=await runPromise(makeState(T3_HOME).cli(["thread","start",project,"Read [Open issue 7](https://code.acme.test/acme/web/issues/7) using T3 read_issue. Report its actual result.","--title","Enterprise issue URL","--provider","issueReplay","--model","default","--wait","--json"]));
  const thread=JSON.parse(result.stdout);
  await t3.open({threadId:thread.threadId});
  // Tapping the finished response puts it in view and waits for history to mount.
  await screen.getByText("T3 issue tool",{exact:false}).last().tap();
  await screen.getByRole("button","Worked for",{exact:false}).tap();
  await new Promise(resolve=>setTimeout(resolve,1500));
  await app.screenshot("agent-read-stability");
  await new Promise(resolve=>setTimeout(resolve,500));
  await app.screenshot("agent-read");
  await screen.getByRole("link","Open Enterprise issue").tap();
  // Record the settled screen after the request. A base link opens outside the app.
  await browser.evaluate(async()=>{await document.fonts.ready;});
  await new Promise(resolve=>setTimeout(resolve,2000));
  await app.screenshot("issue-panel-stability");
  await new Promise(resolve=>setTimeout(resolve,500));
  await app.screenshot("issue-panel");
  await expect(screen.getByRole("button","Refresh issue")).toBeVisible();
  await expect(screen.getByText("Confirmed: correct Enterprise host and repository.",{exact:false}).last()).toBeVisible();
  await expect(screen.getByText("Enterprise issue seven",{exact:true}).last()).toBeVisible();
});
