import * as NodeHttp from "node:http";
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 * 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 { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const BODY = "## Summary\n\nAdd a synthetic greeting.\n\n## Validation\n\n- Review the greeting text.\n- Preserve this multiline description.\n";
const configure = Effect.fn("scenario.configure")(function* (origin: string, port: number) {
  const issued = yield* makeState(T3_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));
  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["server.updateSettings"]({patch: {
    textGenerators: { recordedWriter: {kind: "openaiCompatible", label: "Recorded writer", baseUrl: `http://127.0.0.1:${port}/v1`, apiKey: "", enabled: true}},
    textGenerationModelSelection: {instanceId: "recordedWriter", model: "recording"},
    sourceControlWriterModelSelection: {instanceId: "recordedWriter", model: "recording"},
  }});
}, Effect.scoped);

test("Snap glab creates MRs with multiline descriptions", WEB, async ({t3, app, screen, browser}) => {
  const writer = NodeHttp.createServer(async (req, res) => {
    for await (const _ of req) {}
    res.setHeader("content-type", "application/json");
    res.end(JSON.stringify({choices:[{finish_reason:"stop",message:{content:JSON.stringify({title:"Add synthetic greeting",body:BODY,subject:"Add synthetic greeting",branch:"greeting"})}}]}));
  });
  await new Promise<void>(resolve => writer.listen(0,"127.0.0.1",resolve));
  try {
    await runPromise(configure(app.baseUrl!, (writer.address() as {port:number}).port));
    const fixtures = [];
    for (const mode of ["create", "commit-push"] as const) {
      const project = await t3.project(mode === "create" ? "Create MR proof" : "Commit push MR proof");
      const git = (...args: string[]) => runPromise(run("git",args,{cwd:project}));
      await git("remote","add","origin","https://gitlab.com/julius54/t3-snap-proof-31763-r3.git");
      await git("fetch","origin","main");
      await git("reset","--hard","origin/main");
      await git("remote","set-head","origin","main");
      await git("config","user.name","Scenario");
      await git("config","user.email","scenario@example.invalid");
      const branch = `proof-${mode}-${Date.now()}`;
      await git("checkout","-b",branch);
      await runPromise(run("sh",["-c","printf 'Hello from Snap MR proof.\\n' > greeting.txt"],{cwd:project}));
      if (mode === "create") {
        await git("add","greeting.txt");
        await git("commit","-m","Add synthetic greeting");
        await git("push","-u","origin",branch);
      }
      await runPromise(run("glab",["mr","list"],{cwd:project}));
      const thread = await t3.thread({project,title:mode === "create" ? "Create MR with Snap glab" : "Commit, push and MR with Snap glab",messages:["Start"]});
      fixtures.push({mode, project, branch, thread});
    }
    const outcomes = [];
    for (const {mode, project, branch, thread} of fixtures) {
      await t3.open(thread);
      if (mode === "create") {
        await screen.getByRole("button","Git action options").tap();
        await screen.getByRole("menuitem","Create MR",{exact:true}).tap();
      } else {
        await screen.getByRole("button","Commit, push & MR",{exact:true}).tap();
      }
      await screen.getByText(/Action failed|Created MR/).first().waitFor({state:"visible",timeout:120000});
      const result = await runPromise(run("glab",["api","projects/89028711/merge_requests", "-X", "GET", "-f", `source_branch=${branch}`,"-f","state=opened"],{cwd:project}));
      const mrs = JSON.parse(result.stdout);
      await browser.evaluate(async () => {
        await Promise.all(document.getAnimations().filter(animation => animation.effect?.getComputedTiming().iterations !== Infinity).map(animation => animation.finished.catch(() => {})));
        return true;
      });
      await app.screenshot(`${mode}-result`);
      outcomes.push({mode, count:mrs.length, description:mrs[0]?.description ?? null});
      if (mrs.length === 0) await screen.getByRole("button","Dismiss notification").tap();
    }
    await expect(outcomes).toEqual([
      {mode:"create",count:1,description:BODY.trimEnd()},
      {mode:"commit-push",count:1,description:BODY.trimEnd()},
    ]);
  } finally { await new Promise<void>(resolve=>writer.close(()=>resolve())); }
});
