import { expect } from "e2e";
import { writeFileSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { APP_DIR } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

// Synthetic replay data only; both app revisions receive this exact transcript.
test("Sideways table gestures preserve timeline follow during a subsequent reply", { ...WEB, timeout: 700_000 }, async ({ t3, app, screen, browser }) => {
  const fixture = join(APP_DIR, "apps/server/scripts/dev-replay/showcase_transcript.ndjson");
  const original = readFileSync(fixture, "utf8");
  const row = (cells: string[]) => `| ${cells.join(" | ")} |\n`;
  const table = row(Array.from({length:20}, (_,i) => `Column ${i+1}`)) + row(Array(20).fill("---")) + Array.from({length:6}, (_,r) => row(Array.from({length:20}, (_,c) => `Value-${r+1}-${c+1}`))).join("");
  const prompt = {type:"expect_outbound",frame:{kind:"request",method:"session/prompt",params:"<any>"}};
  const end = {type:"emit_inbound",frame:{kind:"response",method:"session/prompt",result:{stopReason:"end_turn"}}};
  const chunk = (text:string, afterMs=30) => ({type:"emit_inbound",afterMs,frame:{kind:"notification",method:"session/update",params:{sessionId:"replay",update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text}}}}});
  const paragraph = (n:number) => `Paragraph ${n}. ` + "The river winds through the valley as the afternoon light settles across the hills. This synthetic reply keeps growing so we can observe whether new content remains in view after scrolling the table sideways. ".repeat(3) + "\n\n";
  writeFileSync(fixture, [prompt, chunk(table), end, prompt, chunk("Starting the long reply.\n\n",2000), ...Array.from({length:30}, (_,i)=>chunk(paragraph(i+1), i===0?2000:30)), end].map(x=>JSON.stringify(x)).join("\n"));
  const results: Array<{name:string; gap:number; shouldFollow:boolean}> = [];
  try {
    const project = await t3.project("Table scrolling");
    const cases = [
      {name:"sideways-with-upward-noise", dx:60,dy:-8,count:4,shift:false,follow:true},
      {name:"trackpad-like-noise",dx:20,dy:-3,count:10,shift:false,follow:true},
      {name:"shift-wheel-upward",dx:0,dy:-40,count:4,shift:true,follow:true},
      {name:"pure-sideways-control",dx:60,dy:0,count:4,shift:false,follow:true},
      {name:"vertical-upward-control",dx:0,dy:-40,count:4,shift:false,follow:false},
    ];
    for (const gesture of cases) {
      const thread = await t3.thread({project,title:gesture.name,messages:["Show a markdown table with 20 columns and 6 rows, and nothing else."],model:"showcase"});
      await t3.open(thread);
      await screen.getByRole("textbox").fill("Write 30 long paragraphs.");
      await screen.getByRole("textbox").press("Enter");
      await screen.getByText("Starting the long reply.", {exact:false}).waitFor({state:"visible"});
      // Let initial follow reach the bottom before delivering the gesture.
      await browser.evaluate(() => new Promise<void>((resolve, reject) => {
        let attempts = 0;
        const timer = setInterval(() => {
          const el = document.querySelector<HTMLElement>(".messages-timeline-scroll")!;
          if (el.scrollHeight-el.clientHeight-el.scrollTop <= 2) { clearInterval(timer); resolve(); }
          else if (++attempts > 100) { clearInterval(timer); reject(new Error("Initial follow did not reach bottom")); }
        }, 20);
      }));
      const point = await browser.evaluate(() => {
        const timeline = document.querySelector<HTMLElement>(".messages-timeline-scroll")!;
        const table = timeline.querySelector("table")!;
        const rect = table.getBoundingClientRect();
        const clip = timeline.getBoundingClientRect();
        const samples: unknown[] = [];
        (window as any).__followSamples = samples;
        (window as any).__followTimer = setInterval(() => samples.push({gap:timeline.scrollHeight-timeline.clientHeight-timeline.scrollTop}),250);
        return {x:Math.max(rect.left,clip.left)+100,y:Math.max(rect.top,clip.top)+35,gap:timeline.scrollHeight-timeline.clientHeight-timeline.scrollTop};
      });
      console.log(gesture.name,"before gesture",point);
      await browser.mouse.move(point.x,point.y);
      if(gesture.shift) await browser.keyboard.down("Shift");
      for(let i=0;i<gesture.count;i++) await browser.mouse.wheel(gesture.dx,gesture.dy);
      if(gesture.shift) await browser.keyboard.up("Shift");
      await app.screenshot(`${gesture.name}-gesture`);
      await screen.getByRole("button","Stop generation").waitFor({state:"hidden",timeout:180_000});
      // Generation can finish before the final follow animation. Wait for stable geometry.
      await browser.evaluate(() => new Promise<void>((resolve, reject) => {
        let previous = "", stable = 0, attempts = 0;
        const timer = setInterval(() => {
          const el = document.querySelector<HTMLElement>(".messages-timeline-scroll")!;
          const current = `${el.scrollTop}:${el.scrollHeight}:${el.clientHeight}`;
          stable = current === previous ? stable + 1 : 0;
          previous = current;
          if (stable >= 15) { clearInterval(timer); resolve(); }
          else if (++attempts > 200) { clearInterval(timer); reject(new Error("Final viewport did not settle")); }
        }, 50);
      }));
      // Read the app's actual scroll state, without moving it or forcing follow.
      const metrics = await browser.evaluate(() => {
        clearInterval((window as any).__followTimer);
        const timeline = document.querySelector<HTMLElement>(".messages-timeline-scroll")!;
        const table = timeline.querySelector("table")!;
        const scroller = table.parentElement!;
        return {gap:timeline.scrollHeight-timeline.clientHeight-timeline.scrollTop,scrollTop:timeline.scrollTop,scrollHeight:timeline.scrollHeight,scrollLeft:scroller.scrollLeft,samples:(window as any).__followSamples};
      });
      console.log(gesture.name,JSON.stringify(metrics));
      await app.screenshot(`${gesture.name}-finished`);
      results.push({name:gesture.name,gap:metrics.gap,shouldFollow:gesture.follow});
    }
    for(const result of results) {
      if(result.shouldFollow) expect(result.gap, result.name).toBeLessThanOrEqual(2);
      else expect(result.gap,result.name).toBeGreaterThan(100);
    }
  } finally { writeFileSync(fixture, original); }
});
