/// <reference lib="dom" />
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import { expect } from 'e2e';
import { T3_HOME } from '../e2e.config.ts';
import { test, WEB } from './t3.ts';

const receipt = `${T3_HOME}/editor-args.txt`;
const readReceipt = () => {
  const value = existsSync(receipt) ? readFileSync(receipt, 'utf8') : '';
  return value.startsWith('--classic\n') ? value : '';
};
const quote = (v: string) => "'" + v.replaceAll("'", "'\\''") + "'";
const publicPath = (v: string) => v.replace(/.*\/workspaces\/w-[^/]+\//g, 'workspace/').replace(/^\/home\/[^/]+\//, 'home/');

test('Relative links preserve literal POSIX backslashes in terminals and markdown', WEB,
 async ({ t3, app, browser, screen }) => {
  // Discovery probes must not overwrite a recorded editor launch.
  writeFileSync(`${T3_HOME}/bin/cursor-stub.mjs`, [
    'import { writeFileSync } from "node:fs";',
    'const args = process.argv.slice(2);',
    'if (args.includes("--version")) { console.log("1.0.0"); }',
    'else if (args[0] === "--classic") { writeFileSync(new URL("../editor-args.txt", import.meta.url), args.join("\\n") + "\\n"); }',
  ].join('\n'));

  await browser.addInitScript(() => {
    (window as any).pathRequests = [];
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if(typeof data === 'string') {
        try { for(const m of [JSON.parse(data)].flat()) {
          if(m.tag === 'filesystem.getMetadata' || m.tag === 'shell.openInEditor') (window as any).pathRequests.push(m);
        } } catch {}
      }
      return send.call(this, data);
    };
  });
  const cases = [];
  for (const title of ['photos\\', 'C:\\files', 'plain']) {
    const project = await t3.project(title, {
      'note.txt': `inside ${title} workspace\nsecond line\n`,
      '~\\note.txt': 'literal tilde-backslash filename inside workspace\n',
      ...(title === 'photos\\' ? {'nested/proof-link.txt':'inside photos-backslash project: cross-project basename match\n'} : {}),
    });
    if(title === 'photos\\') {
      mkdirSync(`${dirname(project)}/photos/nested`, {recursive:true});
      writeFileSync(`${dirname(project)}/photos/note.txt`, 'WRONG sibling file\n');
      writeFileSync(`${dirname(project)}/photos/nested/proof-link.txt`, 'WRONG sibling cross-project match\n');
    }
    const thread = await t3.thread({project,title:`Check ${title}`,messages:[title === 'plain' ? 'See [proof-link.txt](proof-link.txt)' : 'Check the terminal file links.']});
    cases.push({title, project, thread});
  }
  const outcomes: Array<{label:string, actual:string, expected:string, metadata:string[], targetExists:boolean, content:string}> = [];
  let serial = 0;
  const settle = () => browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 600)));
  for (const c of cases) {
    await t3.open(c.thread);
    await screen.getByRole('button','Toggle terminal drawer').tap();
    const input = screen.getByRole('textbox','Terminal input');
    await expect(input).toHaveAttribute('data-workspace-focus-default','');
    const showReport = async (text: string, label: string) => {
      serial++;
      const name = `receipt-${serial}`;
      writeFileSync(`${c.project}/${name}.txt`,text);
      writeFileSync(`${c.project}/${name}.sh`, `clear; cat ${name}.txt; touch ${name}.done\n`);
      await input.focus(); await browser.keyboard.type(`bash ${name}.sh\n`);
      await expect.poll(() => existsSync(`${c.project}/${name}.done`)).toBe(true);
      await settle();
      await app.screenshot(label);
    };
    const links = c.title === 'C:\\files' ? ['./note.txt','./note.txt:2','~\\note.txt'] : ['./note.txt'];
    for(const [index, link] of links.entries()) {
      writeFileSync(receipt, '');
      const marker = `${c.project}/printed-${index}`;
      writeFileSync(`${c.project}/print-${index}.sh`, `clear; cat note.txt; for i in $(seq 1 100); do printf '%s\\n' ${quote(link)}; done; touch ${quote(marker)}\n`);
      await input.focus(); await browser.keyboard.type(`bash print-${index}.sh\n`);
      await expect.poll(() => existsSync(marker)).toBe(true);
      await settle();
      const box = await browser.evaluate(() => {
        const b = document.querySelector('[aria-label="Terminal input"]')?.parentElement?.querySelector('canvas')?.getBoundingClientRect();
        return b ? {x:b.x,y:b.y,width:b.width,height:b.height} : null;
      });
      if(!box) throw new Error('terminal canvas missing');
      await browser.mouse.move(box.x+22,box.y+box.height/2 - (index%2)*40);
      await settle();
      const label = `${c.title === 'photos\\' ? 'photos' : c.title === 'plain' ? 'plain' : 'drive'}-${index}`;
      await app.screenshot(`${label}-hover`);
      await browser.keyboard.down('Control'); await browser.mouse.down(); await browser.mouse.up(); await browser.keyboard.up('Control');
      try { await expect.poll(readReceipt, {timeout:3000}).not.toBe(''); }
      catch(error) { if((error as {code?:string}).code !== 'ASSERTION_FAILED') throw error; }
      const actual = readReceipt().trim().split('\n').at(-1) || 'NO EDITOR LAUNCH';
      const expected = `${c.project}/${link.replace(/^\.\//,'')}`;
      const requests = await browser.evaluate(() => (window as any).pathRequests);
      const metadata: string[] = requests.filter((m:any) => m.tag === 'filesystem.getMetadata').flatMap((m:any) => m.payload.paths);
      const target = actual.replace(/:\d+$/, '');
      const content = existsSync(target) ? readFileSync(target,'utf8').trim() : '';
      const checked = metadata.at(-1) ?? '';
      outcomes.push({label:`${c.title} ${link}`,actual:publicPath(actual),expected:publicPath(expected),metadata:metadata.map(publicPath),targetExists:existsSync(checked),content});
      await showReport(`WORKSPACE: ${c.title}\nCLICKED: ${link}\nMETADATA TARGET: ${publicPath(checked)}\nMETADATA TARGET EXISTS: ${existsSync(checked)}\nACTUAL EDITOR TARGET: ${publicPath(actual)}\nOPENED FILE CONTENT: ${content || '(no editor launch)'}\nEXPECTED: ${publicPath(expected)}\n`,`${label}-result`);
    }
    if(c.title === 'plain') {
      await screen.getByRole('button','Toggle terminal drawer').tap();
      await screen.getByRole('button', /^Agent See/).tap();
      writeFileSync(receipt,'');
      await browser.keyboard.down('Control'); await screen.getByRole('link', /proof-link\.txt/).tap(); await browser.keyboard.up('Control');
      await expect.poll(readReceipt).not.toBe('');
      const actual = readReceipt().trim().split('\n').at(-1)!;
      const expected = `${cases[0]!.project}/nested/proof-link.txt`;
      const content = existsSync(actual) ? readFileSync(actual,'utf8').trim() : '';
      outcomes.push({label:'markdown cross-project basename lookup (path.ts)',actual:publicPath(actual),expected:publicPath(expected),metadata:[],targetExists:existsSync(actual),content});
      await screen.getByRole('button','Toggle terminal drawer').tap();
      await showReport(`CHAT MARKDOWN: proof-link.txt\nBASENAME FOUND IN PROJECT: photos\\\nACTUAL EDITOR TARGET: ${publicPath(actual)}\nOPENED FILE CONTENT: ${content}\nEXPECTED: ${publicPath(expected)}\n`, 'markdown-cross-project-path-ts');
    }
    await screen.getByRole('button','Toggle terminal drawer').tap();
  }
  const outDir = `/tmp/factory-pr-43753-evidence-2/run-${Date.now()}`;
  mkdirSync(outDir,{recursive:true});
  writeFileSync(`${outDir}/outcomes.json`, JSON.stringify(outcomes,null,2));
  expect(outcomes.map(({label,actual}) => ({label,actual}))).toEqual(outcomes.map(({label,expected}) => ({label,actual:expected})));
 });
