import * as fs from "node:fs/promises";
import { expect } from "e2e";
import { IOS, test } from "./t3-mobile.ts";
import { environmentId, runPromise } from "./t3.ts";
import { MOBILE } from "../e2e.config.ts";

test("Native composer preserves literal BOM examples and chips only prose", IOS, async({t3,app,screen,device})=>{
 const project=await t3.project("examples");
 const file=await t3.thread({project,title:"File example",messages:["Start"]});
 const linked=await t3.thread({project,title:"Thread example",messages:["Start"]});
 const env=await runPromise(environmentId(`http://127.0.0.1:${MOBILE.serverPort}`));
 await t3.open();
 const raw=device.unstable_raw;
 const snapshot=()=>raw.client.capture.snapshot({...raw.selection,interactiveOnly:false});
 const field=(nodes:Awaited<ReturnType<typeof snapshot>>["nodes"])=>{
  const matches=nodes.filter(n=>/TextView|TextField/i.test(n.type??"") && n.rect && n.rect.width>0 && n.rect.height>0 && n.visibleToUser!==false);
  if(matches.length!==1 || !matches[0]!.rect)throw new Error("Expected one native composer with bounds");
  return matches[0]!;
 };
 const open=async(threadId:string,title:string)=>{
  await device.openLink(`t3code-dev://threads/${env}/${threadId}`,{app:"com.t3tools.t3code.dev"});
  await device.locator(`id="${title}"`).waitFor();
  await screen.getByRole("textbox","Ask anything",{exact:true}).tap({position:{x:16,y:12}});
 };
 await open(file.threadId,"File example");
 const example="```md\n[example](t3-context://v1/file/demo)\n```";
 const observations=[];
 let candidate=0;
 for(const count of [1,2]){
  await device.setClipboard("\uFEFF".repeat(count)+example);
  const read=await device.clipboard();
  if(read.startsWith("\uFEFF")&&!read.startsWith("\uFEFF\uFEFF"))candidate=count;
  observations.push({writtenBOMs:count,readPrefix:[...read.slice(0,5)].map(c=>c.charCodeAt(0))});
 }
 await fs.writeFile(`/tmp/factory-pr-43817-evidence-4/final-clipboard-${Date.now()}.json`,JSON.stringify(observations));
 if(!candidate)throw new Error("Clipboard did not return exactly one BOM");
 const paste=async(text:string)=>{
  await device.setClipboard("\uFEFF".repeat(candidate)+text);
  const editor=field((await snapshot()).nodes);
  const rect=editor.rect!;
  await raw.client.interactions.longPress({...raw.selection,x:rect.x+16,y:rect.y+Math.min(16,rect.height/2),durationMs:1000});
  const menu=(await snapshot()).nodes.find(n=>n.label==="Paste" && /Cell|MenuItem/i.test(n.type??""));
  if(!menu?.rect)throw new Error("Native Paste menu item was not present");
  await raw.client.interactions.press({...raw.selection,x:menu.rect.x+menu.rect.width/2,y:menu.rect.y+menu.rect.height/2});
  // Let the OS paste notification leave the capture.
  await new Promise(resolve=>setTimeout(resolve,3500));
  return (await snapshot()).nodes;
 };
 const fileNodes=await paste(example);
 const fileValue=field(fileNodes).value??"";
 const unavailable=fileNodes.some(n=>n.label?.includes("example · unavailable"));
 await app.screenshot("native-bom-file-example");
 await open(linked.threadId,"Thread example");
 const link=`<t3-thread://v2/${env}/${linked.threadId}>`;
 await paste(`~~~\n${link}\n~~~\n${link}`);
 await app.screenshot("native-bom-thread-example");
 expect(unavailable).toBe(false);
 expect(fileValue).toContain("[example](t3-context://v1/file/demo)");
});
