import * as NodeFS from "node:fs";
import { DatabaseSync } from "node:sqlite";
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 { 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("Assistant Linear issue links open the issue panel", WEB, async ({t3, app, screen}) => {
 const project = await t3.project("proj");
 const db = new DatabaseSync(`${T3_HOME}/userdata/statev2.sqlite`, {readOnly:true});
 const row = db.prepare("SELECT project_id FROM projection_projects WHERE title = 'proj'").get() as {project_id:string};
 db.close();
 const credentialFile = NodeFS.readFileSync(`${process.env.HOME}/.config/linear-test.env`, "utf8");
 const match = credentialFile.match(/^(?:export )?LINEAR_API_KEY=(.*)$/m);
 const token = match![1].trim().replace(/^["']|["']$/g, "");
 await runPromise(Effect.gen(function*(){
   const client = yield* rpcClient(T3_HOME, app.baseUrl!);
   yield* client["issueTrackers.connect"]({tracker:"linear", token});
   yield* client["issueTrackers.bindProject"]({projectId:row.project_id, binding:{tracker:"linear",scope:"T3CF"}});
 }).pipe(Effect.scoped));
 const text = "Linear [T3CF-18](https://linear.app/pinglabs/issue/T3CF-18/factory-38742-evidence-open-linear-link-in-issue-panel) and GitHub [#38742](https://github.com/pingdotgg/t3code/issues/38742).";
 const transcript = [
 {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}},
 {type:"emit_inbound",frame:{kind:"notification",method:"session/update",params:{sessionId:"dev-replay-session",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text}}}}},
 {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}}
 ].map(x=>JSON.stringify(x)).join("\n");
 NodeFS.writeFileSync(`${APP_DIR}/apps/server/scripts/dev-replay/command_output_transcript.ndjson`,transcript);
 const thread = await t3.thread({project,title:"Linear issue link proof",messages:["Show the Linear and GitHub issue links."],model:"command-output"});
 await t3.open(thread);
 await screen.getByRole("link","T3CF-18",{exact:true}).waitFor();
 await app.screenshot("before-click");
 await screen.getByRole("link","T3CF-18",{exact:true}).tap();
 try {
  await expect(screen.getByRole("button","Refresh issue",{exact:true})).toBeVisible();
  await expect(screen.getByText("Factory 38742 evidence: open Linear link in issue panel",{exact:true})).toBeVisible();
 } finally {
  await app.screenshot("linear-link-click");
 }
});
