/// <reference lib="dom" />
import { expect } from "e2e";
import { run } from "./shell.ts";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

// Synthetic forge responses; the real app, renderer, file actions and media server run unchanged.
const text = [
  '## Author paths (synthetic reproduction)',
  'Problem: `~/Dév` and `~/` belong to the author.',
  'Outside inline paths: `/etc/hosts` and `../outside.ts`.',
  'Outside markdown links: [absolute hosts](/etc/hosts) and [parent source](../outside.ts).',
  'Repository paths: `packages/x/y.ts` and [repository source](packages/x/y.ts).',
  'Outside image: ![Outside local image](../outside.svg)',
  'Outside audio: ![Outside local audio](../outside.wav)',
].join('\n\n');

test('PR bodies and comments keep author paths inert while chat keeps file actions', WEB,
async ({ t3, app, browser, screen }) => {
  const project = await t3.project('path-demo', {
    'packages/x/y.ts': 'export const example = true;\n',
    '../outside.ts': 'export const outside = true;\n',
    '../outside.svg': '<svg xmlns="http://www.w3.org/2000/svg" width="400" height="60"><rect width="400" height="60" fill="#b91c1c"/><text x="15" y="38" fill="white" font-size="20">OUTSIDE CHECKOUT: LOCAL IMAGE</text></svg>',
    '../outside.wav': new Uint8Array([82,73,70,70,36,0,0,0,87,65,86,69,102,109,116,32,16,0,0,0,1,0,1,0,68,172,0,0,136,88,1,0,2,0,16,0,100,97,116,97,0,0,0,0]),
  });
  await runPromise(run('git', ['remote','add','origin','https://github.com/example/path-demo.git'], {cwd:project}));
  const thread = await t3.thread({ project, title: 'Ordinary chat', messages: ['Chat paths: `/etc/hosts` and `packages/x/y.ts`. Review [PR fixture](https://github.com/example/path-demo/pull/42).'] });
  const issued = await runPromise(makeState(T3_HOME).cli(['auth', 'session', 'issue', '--token-only']));
  const projects = await fetch(`${app.baseUrl}/api/projects`, { headers: { authorization: `Bearer ${issued.stdout.trim()}` } }).then(r=>r.json());
  const projectId = projects.projects.find((p: {title:string})=>p.title==='path-demo').id;
  await browser.setViewport({width:1600,height:1100});
  await browser.addInitScript(({project,projectId,text}) => {
    localStorage.setItem('t3-theme','light');
    const actor = {login:'example-author',name:null,avatarUrl:null};
    const detail = {
      provider:'github',projectId,projectTitle:'path-demo',workspaceRoot:project,
      repository:'example/path-demo',number:42,title:'Author paths in PR text',body:text,
      url:'https://github.com/example/path-demo/pull/42',author:actor,viewer:'reviewer',state:'open',isDraft:false,
      mergeability:'mergeable',additions:1,deletions:0,changedFiles:1,headBranch:'feature',baseBranch:'main',
      createdAt:'2026-10-01T00:00:00Z',updatedAt:'2026-10-02T00:00:00Z',mergedAt:null,closedAt:null,
      reviewers:[],labels:[],checks:[],mergeCapabilities:{merge:false,squash:false,rebase:false},
      capabilities:{diff:true,comment:false,search:true,actions:[],mergeMethods:[],review:{inlineComment:false,reply:false,resolve:false,verdicts:[]},reviewers:{request:false,listCandidates:false},edit:{changeRequest:false,comment:false}},
      viewerPermissions:{actions:[],comment:false,resolve:false,verdicts:[],requestReviewers:false},
    };
    const activity = {comments:[{id:'comment-1',kind:'issue-comment',author:actor,body:'## PR comment\n\n'+text,createdAt:'2026-10-02T00:00:00Z',url:null,path:null,reviewState:null}],commentCount:1,commentsTruncated:false,reviewThreads:[],commits:[]};
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      const request = typeof data==='string' ? JSON.parse(data) : null;
      if(request?._tag!=='Request' || !request.tag.startsWith('pullRequests.')) return send.call(this,data);
      const entry = {...detail,host:'github.com',viewerReviewRequested:false};
      const responses: Record<string,unknown> = {
        'pullRequests.list':{viewers:{'github.com':'reviewer'},providers:[{host:'github.com',kind:'github',searchesOnHost:true,projectCount:1,projectIds:[projectId],configured:true,detail:null}],entries:[entry],errors:[],truncated:false,nextCursors:{}},
        'pullRequests.detail':detail,'pullRequests.activity':activity,
        'pullRequests.summary':entry,'pullRequests.checks':{state:'open',checks:[]},
        'pullRequests.routing':{accountId:'fixture',host:'github.com',provider:'github',viewer:'reviewer',projectTitle:'path-demo',workspaceRoot:project},
        'pullRequests.routingIdentity':{accountId:'fixture',host:'github.com',provider:'github',viewer:'reviewer'},
        'pullRequests.stack':null,'pullRequests.linkedThreads':{threads:[]},
        'pullRequests.listStats':{entries:[]},
      };
      if(!(request.tag in responses)) return send.call(this,data);
      queueMicrotask(()=>this.dispatchEvent(new MessageEvent('message',{data:JSON.stringify({_tag:'Exit',requestId:request.id,exit:{_tag:'Success',value:responses[request.tag]}})})));
    };
  }, {project,projectId,text});
  await t3.open(`/pull-requests?selectedProjectId=${projectId}&repository=example%2Fpath-demo&number=42&selectedHost=github.com`);
  await screen.getByText('Author paths in PR text',{exact:true}).first().waitFor();
  await screen.getByText('Outside markdown links:',{exact:false}).first().waitFor();
  await app.screenshot('pr-body-paths-links-media');
  const bodyOutside = await browser.evaluate(()=>[...document.querySelectorAll('.chat-markdown-file-link')].map(e=>e.textContent));
  const bodyMedia = await browser.evaluate(()=>[...document.querySelectorAll('img')].filter(e=>e.alt==='Outside local image' && e.naturalWidth>0).length);
  await screen.getByRole('button','Timeline',{exact:true}).tap();
  await screen.getByRole('button', /^1 comment 1 author/).tap();
  await screen.getByRole('heading','PR comment',{exact:true}).first().waitFor();
  await screen.getByText('Outside audio:',{exact:false}).first().waitFor();
  await app.screenshot('pr-comment-paths-links-media');
  const commentOutside = await browser.evaluate(()=>[...document.querySelectorAll('.chat-markdown-file-link')].map(e=>e.textContent));
  await t3.open(thread);
  await screen.getByRole('button',/^Agent Chat paths:/).tap();
  await browser.locator('.chat-markdown-file-link').first().waitFor();
  await app.screenshot('ordinary-chat-retains-file-chips');
  const chat = await browser.evaluate(()=>[...document.querySelectorAll('.chat-markdown-file-link')].map(e=>e.textContent));
  await screen.getByRole('link', 'PR fixture', {exact:true}).tap();
  await screen.getByRole('heading', 'Author paths in PR text', {exact:true}).waitFor();
  await screen.getByRole('button','Summary',{exact:true}).tap();
  await screen.getByText('Outside markdown links:',{exact:false}).first().waitFor();
  await browser.evaluate(async()=>{ await Promise.all([...document.images].map(img=>img.decode().catch(()=>{}))); return null; });
  await app.screenshot('thread-pr-local-media');
  const threadMedia = await browser.evaluate(()=>[...document.querySelectorAll('img')].filter(e=>e.alt==='Outside local image' && e.naturalWidth>0).length);
  await screen.getByRole('button','Timeline',{exact:true}).tap();
  await screen.getByRole('button', /^1 comment 1 author/).tap();
  await screen.getByText('Outside audio:',{exact:false}).first().waitFor();
  await browser.evaluate(async()=>{ await Promise.all([...document.images].map(img=>img.decode().catch(()=>{}))); return null; });
  await app.screenshot('thread-pr-comment-local-media');
  expect(bodyOutside.filter(t=>/hosts|outside|Dév|absolute hosts|parent source/.test(t??'')), 'PR body outside paths have no file actions').toEqual([]);
  expect(commentOutside.filter(t=>/hosts|outside|Dév|absolute hosts|parent source/.test(t??'')), 'PR comment outside paths have no file actions').toEqual([]);
  expect(threadMedia, 'PR body cannot load outside media').toBe(0);
  expect(bodyOutside.some(t=>t?.includes('y.ts')), 'Repository path retains a chip').toBe(true);
  expect(chat.some(t=>t?.includes('hosts')), 'Ordinary chat retains host file actions').toBe(true);
});
