/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";

test("CR line endings obey file preview limits and streaming boundaries", WEB, async ({ t3, app, browser, screen }) => {
  const code = Array.from({length:150000}, (_, i) => `const value${i} = "hello";`);
  const partial = Array.from({length:22000}, (_, i) => `row ${String(i+1).padStart(5,"0")} ${"downloaded content ".repeat(5)}`).join("\r");
  const project = await t3.project("Line endings", {
    "lf.txt": "x\n".repeat(1200000)+"END",
    "cr.txt": "x\r".repeat(1200000)+"END",
    "control.ts": 'const example = "highlighting is available";\n'.repeat(100),
    "lf.ts": code.join("\n"), "cr.ts": code.join("\r"),
    "stream.txt": partial,
    "split-crlf.txt": "x\r\n".repeat(1199999)+"END",
  });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* client.subscribeServerConfig({}).pipe(Stream.filter(event => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some(p=>p.instanceId === "devReplay" && p.models?.some(m=>m.slug==="multi-turn"));
    }), Stream.runHead);
  }).pipe(Effect.scoped));
  const thread = await t3.thread({ project, title: "Line ending limits", messages:["Start"] });
  await t3.open(thread);
  await screen.getByRole("textbox", "Message Line ending limits").waitFor();
  const open = async (name:string) => {
    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill(name);
    await screen.getByRole("option",`${name} ${name}`,{exact:true}).waitFor();
    await browser.evaluate(async () => { await new Promise(r=>setTimeout(r,700)); return null; });
    await browser.keyboard.press("Enter");
    await expect.poll(()=>browser.evaluate(()=>document.querySelector('[data-testid="project-file-picker"]')===null)).toBe(true);
    await browser.locator("diffs-container, [data-preview-row]").first().waitFor({timeout:120000});
  };
  const settle = async () => { await browser.evaluate(async () => { await new Promise(r=>setTimeout(r,2200)); return null; }); };
  const colors = () => browser.evaluate(() => {
    const root = document.querySelector("diffs-container")?.shadowRoot;
    return [...new Set(Array.from(root?.querySelectorAll('[data-line] span') ?? [], s=>getComputedStyle(s).color))];
  });
  await open("control.ts"); await settle();
  await app.screenshot("001-small-typescript-highlight-control");
  const controlColors = await colors();
  await open("lf.ts"); await settle();
  await app.screenshot("002-LF-highlighting-limit");
  const lfColors = await colors();
  await open("cr.ts"); await settle();
  await app.screenshot("003-CR-highlighting-limit");
  const crColors = await colors();
  await open("lf.txt");
  await screen.getByText(/1,200,001 lines/).waitFor({timeout:120000}); await settle();
  await app.screenshot("004-LF-rendered-limit");
  await open("cr.txt"); await settle();
  await app.screenshot("005-CR-rendered-limit");
  const crWorker = await browser.evaluate(()=>document.body.textContent?.includes("1,200,001 lines") ?? false);

  // Keep bytes from the real HTTP response; only their delivery timing and chunk boundaries change.
  await browser.evaluate(() => {
    const state = window as unknown as { delivery?: { mode:string; release?:()=>void; ready:boolean; size:number; cut:number } };
    const original = window.fetch.bind(window);
    window.fetch = async (input, init) => {
      const response = await original(input,init);
      const delivery = state.delivery;
      if (!delivery || init?.cache !== "no-store") return response;
      const bytes = new Uint8Array(await response.arrayBuffer());
      if (bytes.length < 1000000) return new Response(bytes,{status:response.status,headers:response.headers});
      const cut = delivery.mode === "crlf" ? bytes.lastIndexOf(13)+1 : bytes.indexOf(13,1500000)+1;
      delivery.size = bytes.length; delivery.cut = cut;
      const stream = new ReadableStream<Uint8Array>({ async start(controller) {
        controller.enqueue(bytes.slice(0,cut)); delivery.ready = true;
        await new Promise<void>(r=>{delivery.release=r;});
        controller.enqueue(bytes.slice(cut)); controller.close();
      }});
      return new Response(stream,{status:response.status,headers:response.headers});
    };
    return null;
  });
  const arm = (mode:string) => browser.evaluate((mode)=>{ (window as any).delivery={mode,ready:false,size:0,cut:0}; return null; },mode);
  const ready = () => browser.evaluate(()=>!!(window as any).delivery?.ready);
  const release = () => browser.evaluate(()=>{(window as any).delivery?.release?.(); (window as any).delivery=undefined; return null;});
  const bottom = () => browser.evaluate(()=>{const el=document.querySelector<HTMLElement>(".file-preview-virtualizer"); if(el) el.scrollTop=el.scrollHeight; return null;});
  const visibleRows = () => browser.evaluate(()=>Array.from(document.querySelector("diffs-container")?.shadowRoot?.querySelectorAll("[data-line]") ?? [],e=>e.textContent??"").join("\n"));
  await arm("cr"); await open("stream.txt");
  await expect.poll(ready).toBe(true); await settle(); await bottom(); await settle();
  const partialRows = await visibleRows();
  await app.screenshot("006-CR-partial-download-bottom");
  await release(); await settle(); await bottom(); await settle();
  await app.screenshot("007-CR-download-complete-bottom");
  await arm("crlf"); await open("split-crlf.txt");
  await expect.poll(ready).toBe(true); await settle();
  await app.screenshot("008-CRLF-held-between-CR-and-LF");
  await release(); await settle();
  await app.screenshot("009-CRLF-complete-without-false-limit");
  const splitWorker = await browser.evaluate(()=>/1,200,00[01] lines/.test(document.body.textContent??""));
  expect({controlHighlighted:controlColors.length>1, lfPlain:lfColors.length===1, crPlain:crColors.length===1, crWorker, partialAdvanced:/row 14\d{3}|row 15\d{3}/.test(partialRows), crlfBelowLimit:!splitWorker}).toEqual({controlHighlighted:true,lfPlain:true,crPlain:true,crWorker:true,partialAdvanced:true,crlfBelowLimit:true});
});
