import { expect } from "e2e";
import { createServer } from "node:http";
import { readdirSync, readFileSync } from "node:fs";
import { test, WEB } from "./t3.ts";
import { APP_DIR } from "../e2e.config.ts";

test("Preview typing rejects a standalone secret reference", WEB, async ({ t3, app, browser, screen }) => {
  const ref = "secret-ref:0123456789abcdef0123456789abcdef";
  const sentence = `${ref} is a handle`;
  const server = createServer((_req, res) => {
    res.setHeader("Content-Type", "text/html; charset=utf-8");
    res.end(`<!doctype html><html><head><title>Preview typing proof</title><style>body{font:20px system-ui;padding:30px;background:#f5f6fa;color:#172033}label{display:block;margin:20px 0}input{display:block;font:18px system-ui;width:95%;padding:9px}output{display:block;margin:14px 0;font-family:monospace}h1{font-size:28px}</style></head><body><h1>Preview typing proof</h1><p>Synthetic login form · no real secrets</p><label>Username<input id="username"></label><label>Password<input type="password" id="password"></label><output id="state">Password length: 0 · starts with secret-ref: false</output><label>Reference in a sentence<input id="note"></label><output id="control"></output><script>document.addEventListener('input',()=>{const p=document.querySelector('#password').value;document.querySelector('#state').textContent='Password length: '+p.length+' · starts with secret-ref: '+p.startsWith('secret-ref:');document.querySelector('#control').textContent='Username: '+document.querySelector('#username').value+' | Sentence preserved: '+document.querySelector('#note').value.endsWith(' is a handle')})</script></body></html>`);
  });
  await new Promise<void>(resolve => server.listen(18765, "127.0.0.1", resolve));
  try {
    const project = await t3.project("Preview proof");
    const thread = await t3.thread({ project, title: "Preview secret reference", messages: ["Ready for preview verification"], model: "question" });
    await t3.open(thread);
    await browser.evaluate(() => new Promise<void>(resolve => {
      const ready = () => document.body.innerText.includes("Should this fixture prefer strict schemas or UI flexibility?");
      if (ready()) return resolve();
      const observer = new MutationObserver(() => { if (ready()) { observer.disconnect(); resolve(); } });
      observer.observe(document.body, {subtree:true,childList:true,characterData:true});
    }));
    let env: Record<string,string> | undefined;
    for (const pid of readdirSync('/proc').filter(n => /^\d+$/.test(n))) {
      try {
        const cmd = readFileSync(`/proc/${pid}/cmdline`, 'utf8');
        if (!cmd.includes(`${APP_DIR}/apps/server/scripts/dev-replay-agent.ts`)) continue;
        const values = Object.fromEntries(readFileSync(`/proc/${pid}/environ`, 'utf8').split('\0').map(x => { const n=x.indexOf('='); return [x.slice(0,n),x.slice(n+1)]; }));
        if (values.T3CODE_THREAD_ID === thread.threadId) { env=values; break; }
      } catch {}
    }
    if (!env) throw new Error('Replay thread MCP credentials were not available');
    let id=0;
    let session: string | null = null;
    const rpc = async (method: string, params: unknown) => {
      const response = await fetch(env!.T3_ACP_MCP_ENDPOINT, { method:'POST', headers:{'Content-Type':'application/json',Accept:'application/json, text/event-stream',Authorization:env!.T3_ACP_MCP_AUTHORIZATION,...(session ? {'Mcp-Session-Id':session} : {})}, body:JSON.stringify({jsonrpc:'2.0',id:++id,method,params}) });
      session=response.headers.get('mcp-session-id') ?? session;
      const body=await response.text();
      const data=body.startsWith('data:') || body.includes('\ndata:') ? JSON.parse(body.split('\n').find(x=>x.startsWith('data:'))!.slice(5)) : JSON.parse(body);
      if(data.error) throw new Error(JSON.stringify(data.error));
      return data.result;
    };
    await rpc('initialize',{protocolVersion:'2025-06-18',capabilities:{},clientInfo:{name:'preview-proof',version:'1'}});
    const tool=(name:string,args:unknown)=>rpc('tools/call',{name,arguments:args});
    const opened=await tool('preview_open',{url:'http://127.0.0.1:18765/',open:true});
    if(opened.isError) throw new Error(JSON.stringify(opened));
    await tool('preview_resize',{mode:'freeform',width:620,height:720});
    await browser.evaluate(() => document.querySelector<HTMLButtonElement>('[aria-label="Open preview in right panel"]')?.focus());
    await screen.getByRole('button', 'Open preview in right panel').tap();
    const typed=await tool('preview_act',{action:'type',selector:'#password',clear:true,text:ref});
    const state=await tool('preview_evaluate',{expression:"({length:document.querySelector('#password').value.length,startsWithRef:document.querySelector('#password').value.startsWith('secret-ref:')})"});
    await app.screenshot('secret-reference-result');
    const username=await tool('preview_act',{action:'type',selector:'#username',clear:true,text:'ada@example.com'});
    const mention=await tool('preview_act',{action:'type',selector:'#note',clear:true,text:sentence});
    const controls=await tool('preview_evaluate',{expression:"({username:document.querySelector('#username').value,note:document.querySelector('#note').value})"});
    console.log('Proof results',JSON.stringify({typed,state,username,mention,controls}));
    await tool('preview_snapshot',{});
    await browser.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
    await browser.keyboard.press('Escape');
    await browser.mouse.move(300,250);
    await app.screenshot('preview-secret-reference');
    await expect(typed.isError ?? false).toBe(true);
    await expect(JSON.stringify(state)).toContain('"length":0');
  } finally {
    await new Promise<void>((resolve,reject)=>server.close(err=>err?reject(err):resolve()));
  }
});
