import { CommandId, ThreadId, ProjectSnapshot, ProviderInstanceId } from "@t3tools/contracts";
import { randomUUID } from "node:crypto";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const setup = (primaryOrigin: string, secondOrigin: string, collision: string) => runPromise(Effect.scoped(Effect.gen(function* () {
  const primary = yield* rpcClient(T3_HOME, primaryOrigin);
  const second = yield* rpcClient(SECOND_HOME, secondOrigin);
  for (const [client, name] of [[primary, "Laptop"], [second, "Hetzner VPS"]] as const) {
    yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
  }
  const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]);
  const { credential } = yield* Schema.decodeEffect(Schema.fromJsonString(Schema.Struct({ credential: Schema.String })))(pairing.stdout);
  yield* primary["peerLinks.link"]({ url: secondOrigin, pairingCode: credential, access: "read-only" });
  const issued = yield* makeState(SECOND_HOME).cli(["auth", "session", "issue", "--token-only"]);
  const { projects } = yield* HttpClient.execute(HttpClientRequest.get(`${secondOrigin}/api/projects`).pipe(HttpClientRequest.bearerToken(issued.stdout.trim()))).pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)));
  for (const [id, title] of [[collision, "Deploy script"], ["other-thread-0002", "Deploy pipeline notes"]]) {
    yield* second["orchestration.dispatchCommand"]({ type: "thread.create", commandId: CommandId.make(randomUUID()), threadId: ThreadId.make(id!), projectId: projects[0]!.id, title: title!, modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "multi-turn" }, runtimeMode: "full-access", interactionMode: "default", branch: null, worktreePath: null, createdBy: "user", creationSource: "web" });
  }
})).pipe(Effect.provide(FetchHttpClient.layer)));

test("The mention picker excludes only the current environment's thread", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Deployment");
  const current = await t3.thread({ project, title: "Deploy script", messages: ["Start"] });
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const { host, token } = await server.ready;
    await makeState(SECOND_HOME).state.project("Deployment");
    await setup(app.baseUrl ?? "", host, current.threadId);
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByPlaceholder("PAIRCODE").waitFor({ state: "hidden" });
    await t3.open(current);
    await screen.getByRole("textbox").fill("@deploy");
    await screen.getByRole("option", "Deploy pipeline notes Thread on Scenario", { exact: false }).waitFor();
    try {
      await expect(screen.getByRole("option", "Deploy script Thread on Scenario", { exact: false })).toBeVisible();
      await expect(screen.getByRole("option", /^Deploy script Thread$/, { exact: true })).not.toBeVisible();
    } finally {
      await app.screenshot("deploy-thread-mentions");
    }
  } finally { await server.stop(); }
});
