/// <reference lib="dom" />
import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { writeFileSync } from "node:fs";
import { appendFile } from "node:fs/promises";
import { test, WEB } from "./t3.ts";

test("Sent review comments keep the exact whitespace in their file targets", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("demo", {" leading.txt":"Leading file\n", "trailing.txt ":"Trailing file\n"});
  await appendFile(`${project}/ leading.txt`, "Review this leading file\n");
  await appendFile(`${project}/trailing.txt `, "Review this trailing file\n");
  const thread = await t3.thread({project, title:"Whitespace paths", messages:["Start"]});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff", {exact:true}).tap();
  for (const name of [" leading.txt", "trailing.txt "]) {
    await expect.poll(() => browser.evaluate((name) => {
      for (const host of document.querySelectorAll("*")) {
        const title = [...(host.shadowRoot?.querySelectorAll<HTMLElement>("[data-title]") ?? [])].find(e=>e.textContent===name);
        if(title){title.click();return true;}
      }
      return false;
    }, name)).toBe(true);
    let point: {x:number,y:number}|null = null;
    await expect.poll(async () => { point = await browser.evaluate(() => {
      for(const host of document.querySelectorAll("*")) {
        if(!host.shadowRoot?.querySelector("[data-content]")) continue;
        const nums = [...host.shadowRoot.querySelectorAll<HTMLElement>("[data-column-number]")];
        const node = nums.find(e=>e.getAttribute("data-column-number")==="2");
        if(node){const r=node.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};}
      }
      return null;
    }); return point !== null; }).toBe(true);
    if (!point) throw new Error("Missing line 2");
    await browser.mouse.move(point.x,point.y);
    await browser.mouse.down(); await browser.mouse.up();
    await screen.getByRole("textbox", "Comment on lines L2").fill(`Please review ${name.trim()}`);
    await screen.getByRole("button", "Comment", {exact:true}).tap();
    await screen.getByRole("button", `Close ${name}`, {exact:true}).tap();
  }
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("second fixture turn complete", {exact:false}).waitFor();
  await app.screenshot("sent-review-comments");
  // Inspect the persisted context through the app's own sent-message chip popover.
  await screen.getByRole("button", "Review comment, trailing.txt", {exact:false}).tap();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter(animation => animation.effect?.getTiming().iterations !== Infinity).map(animation => animation.finished.catch(() => {})));
  });
  await screen.getByText("Review this trailing file", {exact:true}).waitFor();
  await app.screenshot("sent-review-target");
  await browser.keyboard.press("Escape");
  await screen.getByRole("button", "leading.txt L2. Show details", {exact:false}).tap();
  await screen.getByText("Review this leading file", {exact:true}).waitFor();
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().filter(animation => animation.effect?.getTiming().iterations !== Infinity).map(animation => animation.finished.catch(() => {}))); });
  await app.screenshot("sent-leading-target");
  const rows = execFileSync("sqlite3", ["-readonly", `${T3_HOME}/userdata/statev2.sqlite`, "SELECT payload_json FROM orchestration_events WHERE event_type = 'message.updated' ORDER BY sequence"], {encoding:"utf8"}).trim().split("\n").map(line=>JSON.parse(line));
  const records = rows.flatMap(row=>row.message?.context?.records ?? row.context?.records ?? []).filter(record=>record.kind === "review-comment");
  const sha = execFileSync("git", ["-C", APP_DIR, "rev-parse", "HEAD"], {encoding:"utf8"}).trim();
  writeFileSync(`/tmp/factory-pr-43378-evidence-2/context-${sha}.json`, JSON.stringify({sha, records:records.map(({filePath,sectionId})=>({filePath,sectionId}))}, null, 2));
  console.log("SENT_REVIEW_CONTEXT", JSON.stringify(records.map(({filePath,sectionId})=>({filePath,sectionId}))));
  expect(records.map(record=>({filePath:record.filePath,sectionId:record.sectionId}))).toEqual([
    {filePath:" leading.txt",sectionId:"file: leading.txt"},
    {filePath:"trailing.txt ",sectionId:"file:trailing.txt "},
  ]);
});
