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

const program = String.raw`import {writeFileSync} from 'node:fs';
const lines = ['详见 https://example.com/docs。', '（https://example.com/docs）', '见 /tmp/a.txt:12，然后', 'see /tmp/a.txt:12 then', '详见 https://example.com/文档。'];
process.stdin.setRawMode(true);
function show(n) {
 const row = Math.floor(process.stdout.rows / 2);
 process.stdout.write('\x1b[2J\x1b[HASCII terminal links followed by CJK punctuation\r\nCtrl+click the link in the middle row\x1b['+row+';1H'+lines[n]+'\x1b[?25l',()=>writeFileSync('state',JSON.stringify({n,row,rows:process.stdout.rows,cols:process.stdout.columns})));
}
show(0); process.stdin.on('data',c=>{const n=Number(c.toString());if(n>=1&&n<=5)show(n-1);});`;

test("Terminal links stop at CJK punctuation after ASCII and preserve Unicode punctuation", WEB, async ({t3, app, browser, screen}) => {
 await browser.emulateMedia({colorScheme:"dark"});
 const project = await t3.project("terminal-links", {"program.mjs":program});
 const start = (model:string) => t3.thread({project,title:"CJK terminal links",messages:["hello"],model});
 const thread = await start("multi-turn").catch(async error => {
   if (!String(error).includes("not advertised")) throw error;
   return start("default").catch(async error => {
     if (!String(error).includes("not advertised")) throw error;
     return start("multi-turn");
   });
 });
 const read = (path:string) => runPromise(Effect.gen(function*(){const fs=yield* FileSystem.FileSystem; return yield* fs.readFileString(path);}).pipe(Effect.orElseSucceed(()=>"")));
 await t3.open(thread);
 await browser.evaluate(()=>{(window as any).openedTargets=[]; window.open=((url:unknown)=>{(window as any).openedTargets.push(String(url));return null;}) as typeof window.open;});
 await screen.getByRole("button","Toggle terminal drawer").tap();
 const input=screen.getByLabel("Terminal input");
 await expect(input).toHaveAttribute("data-workspace-focus-default","");
 await expect.poll(async()=>{await input.focus();await browser.keyboard.type("echo ready > shell-ready");await browser.keyboard.press("Enter");return read(`${project}/shell-ready`);},{timeout:30000}).toBe("ready\n");
 await browser.keyboard.type(`seq 1 20 > /tmp/a.txt; '${process.execPath}' program.mjs`);
 await browser.keyboard.press("Enter");
 await expect.poll(()=>read(`${project}/state`)).not.toBe("");
 const labels=["ascii-url-full-stop","ascii-url-parenthesis","ascii-path-comma","ascii-space-control","unicode-url-preserved"];
 const editorResults:string[]=[];
 for(let n=0;n<5;n++){
   await input.focus(); await browser.keyboard.type(String(n+1));
   await expect.poll(async()=>JSON.parse(await read(`${project}/state`)||"{}").n).toBe(n);
   const state=JSON.parse(await read(`${project}/state`));
   const point=await browser.evaluate((n)=>{const c=document.querySelector('[aria-label="Terminal input"]')!.parentElement!.querySelector("canvas")!;const b=c.getBoundingClientRect();const ctx=c.getContext("2d")!;const pixels=ctx.getImageData(0,0,c.width,c.height).data;let first=-1,last=-1;for(let y=Math.floor(c.height*.25);y<c.height*.75;y++){let ink=0;for(let x=5;x<c.width/2;x++){const i=(y*c.width+x)*4;if(pixels[i]+pixels[i+1]+pixels[i+2]>350)ink++;}if(ink>5){if(first<0)first=y;last=y;}}if(first<0)throw new Error("No rendered terminal text in middle rows");return {x:b.x+90+n,y:b.y+(first+last)/2*c.clientHeight/c.height};},n);
   await browser.mouse.move(point.x,point.y);
   await browser.evaluate(()=>new Promise(r=>setTimeout(r,700)));
   await app.screenshot(labels[n]);
   await browser.keyboard.down("Control"); await browser.mouse.down();await browser.mouse.up();await browser.keyboard.up("Control");
   await browser.evaluate(()=>new Promise(r=>setTimeout(r,700)));
   if(n===2||n===3)editorResults.push(await read(`${T3_HOME}/editor-args.txt`));
 }
 const urls=await browser.evaluate(()=>(window as any).openedTargets);
 await app.screenshot("after-activation");
 expect({urls,path:editorResults[0],control:editorResults[1]}).toEqual({urls:["https://example.com/docs","https://example.com/docs","https://example.com/文档。"],path:"--classic\n--goto\n/tmp/a.txt:12\n",control:"--classic\n--goto\n/tmp/a.txt:12\n"});
});
