/// <reference lib="dom" />
import { expect } from "e2e";
import { mkdir, writeFile } from "node:fs/promises";
import { setTimeout as wait } from "node:timers/promises";
import { test, WEB } from "./t3.ts";

const ERROR = "The file could not be accessed or read. It may be missing or inaccessible.";
test("Ambiguous chat citations stay unresolved and local matches still open", WEB, async ({t3,app,browser,screen}) => {
  // Public, synthetic workspace names keep capture paths independent of the worker checkout.
  await mkdir("/tmp/citation-demo", {recursive:true});
  const reports = await t3.project("reports", {"notes/HANDOFF.txt":"REPORT HANDOFF — wrong cross-project selection"});
  const support = await t3.project("support", {"current/Handoff.txt":"CURRENT SUPPORT HANDOFF", "archive/HANDOFF.txt":"ARCHIVED SUPPORT HANDOFF", "local.txt":"SUCCESSFUL THREAD-LOCAL MATCH"});
  const planning = await t3.project("planning");
  const cases = [
    {project:planning,title:"Basename from planning",path:"handoff.txt", label:"basename-third-project", unresolved:true},
    {project:support,title:"Basename from support",path:"handoff.txt",label:"basename-thread-project",unresolved:true},
    {project:support,title:"Qualified from support",path:"docs/handoff.txt",label:"qualified-thread-project",unresolved:true},
    {project:support,title:"Exact local match",path:"local.txt",label:"successful-local-match",unresolved:false},
  ];
  const threads = [];
  for (const c of cases) {
    threads.push(await t3.thread({project:c.project,title:c.title,messages:["Review the cited handoff file."],model:"multi-turn"}));
  }
  const outcomes = [];
  for (let i=0;i<cases.length;i++) {
    const c=cases[i]!;
    if(i===2) {
      for(const [root,file,text] of [[reports,"notes/docs/handoff.txt","REPORT QUALIFIED HANDOFF — wrong cross-project selection"],[support,"current/docs/handoff.txt","CURRENT QUALIFIED SUPPORT HANDOFF"],[support,"archive/docs/handoff.txt","ARCHIVED QUALIFIED SUPPORT HANDOFF"]]) {
        await mkdir(`${root}/${file!.slice(0,file!.lastIndexOf("/"))}`,{recursive:true});
        await writeFile(`${root}/${file}`,text!);
      }
    }

    await t3.open(threads[i]!);
    const links = screen.getByRole("link", c.path === "local.txt" ? /^local\.txt/ : /handoff\.txt/i);
    await (c.path === "docs/handoff.txt" ? links.nth(1) : links.first()).tap();
    const hideExplorer = screen.getByRole("button", "Hide file explorer");
    if(await hideExplorer.isVisible()) await hideExplorer.tap();
    const panelText = () => browser.evaluate(()=>{
      const panel=document.querySelector("[data-right-panel-surface-content]");
      let text=panel?.textContent ?? "";
      for(const host of panel?.querySelectorAll("*") ?? []) text += host.shadowRoot?.querySelector("[data-content]")?.textContent ?? "";
      return text;
    });
    await expect.poll(async()=> /The file could not be accessed|REPORT.*HANDOFF|SUCCESSFUL THREAD-LOCAL MATCH/.test(await panelText())).toBe(true);
    const content = await panelText();
    const passed = c.unresolved ? content.includes(ERROR) : content.includes("SUCCESSFUL THREAD-LOCAL MATCH");
    await browser.evaluate(()=> { if(document.activeElement instanceof HTMLElement) document.activeElement.blur(); });
    await wait(1000);
    await app.screenshot(c.label);
    await wait(1000);
    outcomes.push(passed);
  }
  expect(outcomes).toEqual([true,true,true,true]);
});
