import * as NodeWS from "@effect/platform-node/NodeWS";
import {
  CommandId,
  ORCHESTRATION_PROTOCOL_VERSION,
  ThreadId,
  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 { chromium } from "playwright-core";
import { 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));
});


const seedChildren = Effect.fn("scenario.seedChildren")(function* (origin: string, threadId: string) {
  const client = yield* rpcClient(T3_HOME, origin);
  const projection = yield* client["orchestration.getThreadProjection"]({threadId: ThreadId.make(threadId)});
  const run = projection.runs[0]!;
  for (let i = 1; i <= 4; i++) {
    yield* client["orchestration.dispatchCommand"]({
      type: "delegated_task.request", commandId: CommandId.make(crypto.randomUUID()),
      parentThreadId: ThreadId.make(threadId), parentRunId: run.id, parentNodeId: run.rootNodeId!,
      createdBy: "agent", creationSource: "mcp", task: `say hi ${i}`, title: `say hi ${i}`,
      modelSelection: {instanceId: "devReplay", model: "multi-turn"},
      runtimeMode: "full-access", interactionMode: "default", completionWake: "settled_only",
    });
  }
}, Effect.scoped);

test("Thread details lineage has no stray touch scrollbars", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("Lineage demo");
  const thread = await t3.thread({project, title: "Lineage demo", messages: ["Delegate four greetings"], model: "question"});
  await runPromise(seedChildren(app.baseUrl ?? "", thread.threadId));
  await t3.open(thread);
  const connected = await chromium.connectOverCDP("http://127.0.0.1:19227");
  const context = connected.contexts().find(c => c.pages().some(p => p.url().includes(thread.threadId)))!;
  const page = context.pages().find(p => p.url().includes(thread.threadId))!;
  await page.getByRole("button", {name: /^Strict schemas/}).click();
  await page.getByRole("button", {name: "Submit", exact: true}).click();
  await page.getByRole("button", {name: "Stop generation", exact: true}).waitFor({state: "hidden"});
  const panel = page.locator("[data-thread-details-card]");
  if (!await panel.isVisible()) await page.getByRole("button", {name: "Toggle thread details panel", exact: true}).click();
  await panel.waitFor({state: "visible"});
  const cdp = await context.newCDPSession(page);
  await cdp.send("Emulation.setTouchEmulationEnabled", {enabled: true, maxTouchPoints: 1});
  const previous = screen.getByRole("button", "Previous agents", {exact: false});
  await previous.tap();
  await page.getByRole("list", {name: "Related threads"}).getByRole("button", {name: /say hi 4/}).waitFor();
  await page.waitForFunction(() => document.querySelectorAll('[aria-label="Related threads"] li').length === 4);
  await page.mouse.move(600, 650);
  // Capture only after two frames 500 ms apart are identical.
  let prior = await page.screenshot();
  for (let i=0;i<20;i++) {
    await new Promise(resolve => setTimeout(resolve, 500));
    const current = await page.screenshot();
    if (prior.equals(current)) break;
    prior = current;
  }
  const metrics = await browser.evaluate(() => {
    const list = document.querySelector('[aria-label="Related threads"]')!;
    return {coarse: matchMedia('(pointer: coarse)').matches, scrollWidth: list.scrollWidth, clientWidth: list.clientWidth, scrollHeight: list.scrollHeight, clientHeight: list.clientHeight};
  });
  console.log("LINEAGE_METRICS", JSON.stringify(metrics));
  await app.screenshot("touch-lineage");
  expect(metrics.scrollWidth).toBe(metrics.clientWidth);
  expect(metrics.scrollHeight).toBe(metrics.clientHeight);
});
