/// <reference lib="dom" />
import { readFile, symlink, mkdir } from "node:fs/promises";
import * as NodeWS from "@effect/platform-node/NodeWS";
import { CommandId, ThreadId, 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 { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

const configureScripts = (origin: string, project: string, threadId?: string) => runPromise(Effect.gen(function* () {
  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));
  if (threadId) {
    yield* client["orchestration.dispatchCommand"]({type:"thread.settle",commandId:CommandId.make(crypto.randomUUID()),threadId:ThreadId.make(threadId)});
  } else {
    const script = (id:string, setup:boolean) => ({id, name:setup ? "Setup shell probe":"Settle shell probe", icon:"play" as const, runOnWorktreeCreate:setup, runOnSettle:!setup, async:false, command:`PS1='> '; { printf 'Automatic ${setup ? "setup":"settle"} shell\\n'; printf 'Executable: '; readlink /proc/$$/exe; printf 'BASH_VERSION=%s\\n' "$BASH_VERSION"; printf 'PROBE_DONE\\n'; } > '${project}/automatic-${setup ? "setup":"settle"}.txt'`});
    yield* client["server.updateSettings"]({patch:{defaultProjectScripts:[script("setup-shell",true),script("settle-shell",false)]}});
  }
}).pipe(Effect.scoped));

test("POSIX default, executable resolution, fallback and automatic scripts", WEB, async ({t3,app,browser,screen}) => {
  const project=await t3.project("terminal-demo");
  await mkdir(`${project}/shell tools`);
  await symlink("/bin/dash",`${project}/shell tools/customsh`);
  await mkdir(`${project}/ tools `);
  await symlink("/bin/dash",`${project}/ tools /customsh`);
  await browser.addInitScript(() => {
    const send=WebSocket.prototype.send;
    WebSocket.prototype.send=function(data) {
      if(typeof data === "string") {
        let messages=JSON.parse(data);
        for(const message of [messages].flat()) {
          if(message?._tag === "Request" && (message.tag === "terminal.open" || message.tag === "terminal.attach")) {
            message.payload.env={...message.payload.env,...(window as any).probeEnv};
          }
        }
        data=JSON.stringify(messages);
      }
      return send.call(this,data);
    };
  });
  const captureStable=async(label:string)=> {
    await browser.mouse.move(900,50);
    let previous=await app.screenshot(`${label}-settling-0`);
    let stable=false;
    for(let i=1;i<=15;i++) {
      await browser.evaluate(()=>new Promise(resolve=>setTimeout(resolve,500)));
      const next=await app.screenshot(`${label}-settling-${i}`);
      if((await readFile(previous)).equals(await readFile(next))) {stable=true;break;}
      previous=next;
    }
    if(!stable)throw new Error("The capture did not stabilize");
    await app.screenshot(label);
  };
  const results:Record<string,string>={};
  for(const [label,env] of [
    ["default-shell",{T3CODE_TERMINAL_SHELL:""}],
    ["missing-executable-fallback",{T3CODE_TERMINAL_SHELL:"/not-installed/terminal-shell"}],
    ["relative-shell-path",{T3CODE_TERMINAL_SHELL:"./shell tools/customsh"}],
    ["relative-PATH-entry",{T3CODE_TERMINAL_SHELL:"customsh",PATH:`shell tools:${process.env.PATH}`}],
    ["whitespace-PATH-entry",{T3CODE_TERMINAL_SHELL:"customsh",PATH:` tools :${process.env.PATH}`}],
  ] as const) {
    const thread=await t3.thread({project,title:label,messages:["Check terminal shell"]});
    await t3.open(thread);
    await browser.evaluate((env) => { (window as any).probeEnv=env; return null; },env);
    await screen.getByRole("button","Toggle terminal drawer").tap();
    const input=screen.getByRole("textbox","Terminal input");
    await expect(input).toHaveAttribute("data-workspace-focus-default", "");
    await input.focus();
    await browser.keyboard.type(`PS1='> '; clear; { printf '${label}\\nExecutable: '; readlink /proc/$$/exe; printf 'BASH_VERSION=%s\\n' "\${BASH_VERSION:-unset}"; printf 'PROBE_DONE\\n'; } | tee ${label}.txt; printf '\\033[?25l'\n`);
    const result=()=>readFile(`${project}/${label}.txt`,"utf8").catch(()=>"");
    await expect.poll(result,{timeout:30000}).toContain("PROBE_DONE");
    results[label]=await result();
    await captureStable(label);
  }
  await configureScripts(app.baseUrl ?? "",project);
  const launched=await runPromise(makeState(T3_HOME).cli(["thread","start",project,"Check setup and settle shells","--title","Automatic scripts","--provider","devReplay","--model","multi-turn","--worktree","main","--branch","shell-probe","--wait","--json"]));
  const {threadId}=JSON.parse(launched.stdout);
  await configureScripts(app.baseUrl ?? "",project,threadId);
  const resultsThread=await t3.thread({project,title:"Automatic script results",messages:["Check automatic script shells"]});
  await t3.open(resultsThread);
  await screen.getByRole("button","Toggle terminal drawer").tap();
  for(const label of ["setup","settle"]) {
    const file=`${project}/automatic-${label}.txt`;
    await expect.poll(()=>readFile(file,"utf8").catch(()=>""),{timeout:30000}).toContain("PROBE_DONE");
    const input=screen.getByRole("textbox","Terminal input");
    await expect(input).toHaveAttribute("data-workspace-focus-default", "");
    await input.focus();
    await browser.keyboard.type(`PS1='> '; clear; cat automatic-${label}.txt; printf '\\033[?25l'\n`);
    await captureStable(`automatic-${label}`);
  }
  await expect(results["relative-shell-path"]).toContain("/usr/bin/dash");
  await expect(results["relative-PATH-entry"]).toContain("/usr/bin/dash");
  await expect(results["whitespace-PATH-entry"]).toContain("/usr/bin/dash");
  await expect(results["default-shell"]).toContain("/usr/bin/bash");
  await expect(results["missing-executable-fallback"]).toContain("/usr/bin/bash");
});
