import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { MOBILE, MOBILE_T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./second-server.ts";
import { environmentId, makeState, rpcClient, runPromise } from "./t3.ts";
import { IOS, test } from "./t3-mobile.ts";

const reasoning = "The user wants a short tour. I will read the manifest, add a small helper, run the tests, and then summarize with some markdown.";

test("Linked Thinking expands to the reasoning text", IOS, async ({ t3, app, screen, device }) => {
  const primary = `http://127.0.0.1:${MOBILE.serverPort}`;
  const secondServer = startSecondServer(primary);
  try {
    const { host } = await secondServer.ready;
    await runPromise(Effect.gen(function* () {
      const a = yield* rpcClient(MOBILE_T3_HOME, primary);
      const b = yield* rpcClient(SECOND_HOME, host);
      for (const client of [a, b]) yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } });
      const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]);
      const { credential } = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Struct({ credential: Schema.String })))(pairing.stdout);
      yield* a["peerLinks.link"]({ url: host, pairingCode: credential, access: "full-access" });
    }).pipe(Effect.scoped));
    const remote = makeState(SECOND_HOME).state;
    const remoteProject = await remote.project("demo");
    const child = await remote.thread({ project: remoteProject, title: "Show the showcase", messages: ["Show the showcase"], model: "showcase" });
    const target = await runPromise(environmentId(host));
    const via = await runPromise(environmentId(primary));
    const project = await t3.project("demo");
    const parent = await t3.thread({ project, title: "Linked reasoning repro", messages: [`Open [Show the showcase](t3-thread://v2/${target}/${child.threadId})`], model: "multi-turn" });
    await t3.open();
    await screen.getByText("Linked reasoning repro", { exact: false }).first().waitFor({ timeout: 120000 });
    await device.openLink(`t3code-dev://threads/${via}/${parent.threadId}`, { app: "com.t3tools.t3code.dev" });
    await device.alert("accept").catch(() => {});
    await screen.getByText("Show the showcase", { exact: true }).first().tap();
    await screen.getByText("Thinking", { exact: true }).first().waitFor();
    await screen.getByText("Thinking", { exact: true }).first().tap();
    await app.screenshot("linked-thinking-expanded");
    await expect(screen.getByText(reasoning, { exact: true })).toBeVisible();
  } finally {
    await secondServer.stop();
  }
});
