/// <reference lib="dom" />
// @effect-diagnostics nodeBuiltinImport:off -- Reads only the replay processes created by this scenario.
import * as fs from 'node:fs/promises';
import { expect } from 'e2e';
import { test, WEB } from './t3.ts';

const cases = [
  {label:'IPv6', reason:'Open https://[2001:db8::1]:8443/setup to continue.', url:'https://[2001:db8::1]:8443/setup'},
  {label:'Array query', reason:'Visit https://example.org/setup?scope[]=repo to continue.', url:'https://example.org/setup?scope[]=repo'},
  {label:'Repeated Markdown', reason:'Open [https://a.dev/x?scope[]=repo](https://a.dev/x?scope[]=repo) and sign in.', url:'https://a.dev/x?scope[]=repo'},
  {label:'Control', reason:'Visit https://example.org/setup?scope=repo to continue.', url:'https://example.org/setup?scope=repo'},
];

test('Secret cards preserve brackets in inferred sign-in destinations', WEB, async ({t3, app, browser, screen}) => {
  const seeded = [];
  const pending: Promise<unknown>[] = [];
  for (const item of cases) {
    const project = await t3.project(item.label.replaceAll(' ', '-'));
    const thread = await t3.thread({project, title:item.label, model:'question', messages:['Prepare setup.']});
    let authorization = '';
    for (const pid of await fs.readdir('/proc')) {
      if (!/^\d+$/.test(pid)) continue;
      try {
        if (await fs.readlink(`/proc/${pid}/cwd`) !== project) continue;
        const env = (await fs.readFile(`/proc/${pid}/environ`, 'utf8')).split('\0');
        authorization = env.find(v => v.startsWith('T3_ACP_MCP_AUTHORIZATION='))?.slice('T3_ACP_MCP_AUTHORIZATION='.length) ?? '';
        if (authorization) break;
      } catch {}
    }
    if (!authorization) throw new Error('Replay session MCP authorization unavailable');
    let session = '';
    const send = async (body: object) => {
      const response = await fetch(`${app.baseUrl}/mcp`, {method:'POST', headers:{'content-type':'application/json', accept:'application/json, text/event-stream', authorization, ...(session ? {'mcp-session-id':session} : {})}, body:JSON.stringify({jsonrpc:'2.0', ...body})});
      session = response.headers.get('mcp-session-id') ?? session;
      const text = await response.text();
      if (!response.ok || text.includes('"isError":true')) throw new Error(`MCP request failed: ${text}`);
      return text;
    };
    await send({id:1, method:'initialize', params:{protocolVersion:'2025-06-18', capabilities:{}, clientInfo:{name:'scenario', version:'1'}}});
    await send({method:'notifications/initialized'});
    const call = send({id:2, method:'tools/call', params:{name:'request_secret', arguments:{label:'Setup token', reason:item.reason}}});
    call.catch(()=>{});
    pending.push(call);
    seeded.push({...item, thread});
  }
  const actual: string[] = [];
  for (const item of seeded) {
    await t3.open(item.thread);
    await screen.getByText('Setup token', {exact:true}).waitFor();
    await screen.getByText('Syncing messages...', {exact:true}).waitFor({state:'hidden'});
    const destination = await browser.evaluate(() => {
      const save = Array.from(document.querySelectorAll('button')).find(b=>b.textContent?.includes('Save securely'));
      let card = save?.parentElement;
      while (card && !card.textContent?.includes('Setup token')) card = card.parentElement;
      const link = card?.querySelector('a[href^="https://"]');
      const href = link?.getAttribute('href') ?? '(no sign-in button)';
      const readout = document.createElement('div');
      readout.id='destination-evidence';
      readout.textContent=`Actual sign-in button destination: ${href}`;
      readout.style.cssText='position:fixed;bottom:20px;left:300px;right:24px;z-index:99999;padding:18px;background:#fff;color:#111;border:2px solid #666;font:16px monospace;overflow-wrap:anywhere';
      document.body.append(readout);
      return href;
    });
    actual.push(destination);
    await app.screenshot(item.label);
  }
  expect(actual).toEqual(cases.map(item=>item.url));
});
