/// <reference lib="dom" />
import { expect } from "e2e";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

test("A real GitHub PR refresh preserves the live thread activity timestamp", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("pr-refresh-demo");
  const thread = await t3.thread({project, title: "PR refresh activity", messages: ["go"]});
  await t3.open(thread);
  await browser.evaluate(`(async () => {
    const {appAtomRegistry: registry} = await import('/src/rpc/atomRegistry.ts');
    const {environmentThreadStateAtom} = await import('/src/state/threads.ts');
    const {deriveThreadRuntime} = await import(${JSON.stringify('/@fs' + APP_DIR + '/packages/client-runtime/src/state/threadExecution.ts')});
    const [environmentId, threadId] = location.pathname.split('/').filter(Boolean);
    const atom = environmentThreadStateAtom(environmentId, threadId);
    const panel = document.createElement('pre');
    panel.style.cssText = 'position:fixed;bottom:20px;left:25px;z-index:9999;background:#111827;color:#fff;border:2px solid #60a5fa;border-radius:8px;padding:16px;font:14px/1.7 monospace;pointer-events:none';
    document.body.append(panel);
    window.readActivity = () => {
      const p = registry.get(atom).value?.data?.value;
      if (!p) return null;
      const iso = x => typeof x === 'string' ? x : new Date(x.epochMilliseconds).toISOString();
      const links = p.thread.pullRequests ?? [];
      const data = {projection: iso(p.updatedAt), thread: iso(p.thread.updatedAt), runtime: deriveThreadRuntime(p)?.updatedAt, links, server: window.serverActivity ?? null};
      panel.textContent = 'LIVE CLIENT — read-only diagnostics\\nProjection activity: ' + data.projection + '\\nThread activity:     ' + data.thread + '\\nRuntime activity:    ' + data.runtime + '\\nPR refresh received: ' + links.some(x => x.snapshot != null) + '\\nPR synced at:        ' + (links[0]?.snapshot?.syncedAt ?? 'pending') + '\\nFresh snapshot:      ' + (window.serverActivity ?? 'not read yet') + '\\nActivity matches:    ' + (data.projection === data.thread && data.runtime === data.thread);
      return data;
    };
    registry.subscribe(atom, () => window.readActivity());
    window.waitForPr = () => new Promise(resolve => {
      const ready = () => window.readActivity()?.links.some(x => x.snapshot != null);
      if (ready()) return resolve(null);
      const stop = registry.subscribe(atom, () => { if (ready()) { stop(); resolve(null); } });
    });
    window.readActivity();
  })()`);
  await screen.getByRole("textbox", "Message PR refresh activity").waitFor();
  await browser.evaluate(`(async () => { const {openCommandPalette} = await import('/src/commandPaletteBus.ts'); openCommandPalette(); })()`);
  await screen.getByRole("dialog", "Command palette").getByRole("combobox").fill("> Link pull request to thread");
  await screen.getByText("Link pull request to thread", {exact:true}).tap();
  await screen.getByPlaceholder("Pull request URL or #42").fill("https://github.com/pingdotgg/t3code/pull/44789");
  await screen.getByRole("button", "Link", {exact:true}).tap();
  await browser.evaluate(`window.waitForPr()`);
  await browser.evaluate(`(async () => {
    const threadId = location.pathname.split('/').filter(Boolean)[1];
    const response = await fetch('/api/orchestration/threads/' + encodeURIComponent(threadId), {headers:{'x-t3-orchestration-protocol':'2'}});
    if (!response.ok) throw new Error('Snapshot read failed: ' + response.status);
    const snapshot = await response.json();
    window.serverActivity = snapshot.projection.updatedAt;
    window.readActivity();
  })()`);
  const values = await browser.evaluate<{projection:string;thread:string;runtime:string;server:string}>(`window.readActivity()`);
  await app.screenshot("pr-refreshed-activity");
  await expect(values.projection).toBe(values.server);
  await expect(values.projection).toBe(values.thread);
  await expect(values.runtime).toBe(values.thread);
});
