import { expect } from "e2e";
import { readFile } from "node:fs/promises";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { T3_HOME } from "../e2e.config.ts";

test("Revocation closes an established native speech stream", WEB, async ({t3, app, browser}) => {
  await t3.project("Speech demo");
  await t3.open("/settings/voice");
  const cli = makeState(T3_HOME).cli;
  const owner = (await runPromise(cli(["auth","session","issue","--token-only","--label","Evidence owner"]))).stdout.trim();
  const runtime = JSON.parse(await readFile(`${T3_HOME}/userdata/server-runtime.json`, "utf8"));
  const origin = runtime.origin;
  async function api(path: string, body?: unknown, cookie?: string) {
    const r = await fetch(origin+path, {method: body === undefined ? "GET":"POST", headers: {"content-type":"application/json", ...(cookie ? {cookie} : {authorization:`Bearer ${owner}`})}, ...(body === undefined ? {} : {body:JSON.stringify(body)})});
    const text = await r.text();
    if (!r.ok) throw new Error(`${path}: ${r.status} ${text}`);
    return {data:text ? JSON.parse(text):null, cookie:r.headers.get("set-cookie")?.split(";")[0]};
  }
  const modelId="handy-computer/moonshine-streaming-tiny-gguf";
  await api("/api/voice/models/download", {modelId});
  for(let i=0;i<300;i++) {
    try { await api("/api/voice/models/select", {modelId}); break; } catch(e) { if(i===299) throw e; await new Promise(r=>setTimeout(r,1000)); }
  }
  await api("/api/voice/models/prepare", {});
  const status=(await api("/api/voice/status")).data;
  const pair=(await api("/api/auth/pairing-token", {label:"Second browser 2"})).data;
  const second=await api("/api/auth/browser-session", {credential:pair.credential});
  if(!second.cookie) throw new Error("No second-client cookie");
  const sessions=JSON.parse((await runPromise(cli(["auth","session","list","--json"]))).stdout);
  const session=sessions.find((s:any)=>s.client?.label === "Second browser 2");
  if(!session) throw new Error("Second session missing: "+JSON.stringify(sessions));
  const ticket=(await api("/api/auth/websocket-ticket/media", {}, second.cookie)).data.ticket;
  const ws=new WebSocket(origin.replace(/^http/,"ws")+"/ws/voice?wsTicket="+encodeURIComponent(ticket));
  let closed=false, closeCode=0, updates=0, after=0, revoked=false, transcript="", revocation="Not revoked", authenticated="true";
  const events:string[]=[];
  const start=Date.now();
  const log=(s:string)=>events.push(`${((Date.now()-start)/1000).toFixed(2)}s  ${s}`);
  ws.addEventListener("close", e=>{closed=true;closeCode=e.code;log(`SOCKET CLOSED code=${e.code}`)});
  await new Promise<void>((resolve,reject)=>{ws.addEventListener("error",()=>reject(new Error("Socket error")));ws.addEventListener("message",e=>{const v=JSON.parse(String(e.data));if(v.type==="ready"){log("ready — native speech stream started");resolve();}if(v.type==="error")reject(new Error(v.message));if(v.type==="update"){updates++;if(revoked)after++;if(v.text)transcript=v.text.committed+" "+v.text.tentative;log(`update #${updates}${revoked?" AFTER REVOCATION":""}: ${transcript.slice(-170)}`);}});ws.addEventListener("open",()=>ws.send(JSON.stringify({type:"start",options:{speechLanguage:"en",speechTranslateToEnglish:false,speechCustomWords:[],speechRemoveFillerWords:true,speechSilenceFiltering:false}})));});
  const pcm=await readFile(process.env.T3_PROOF_AUDIO_FILE ?? "./speech.pcm");
  await browser.evaluate(()=>{const panel=document.createElement("div");panel.id="speech-evidence";panel.style.cssText="position:fixed;inset:25px;z-index:999999;background:#101722;color:#eff6ff;padding:28px;font:18px monospace;white-space:pre-wrap;overflow:hidden";document.body.append(panel)});
  async function show() { await browser.evaluate((text)=>{document.getElementById("speech-evidence")!.textContent=text},`LIVE DICTATION / SESSION REVOCATION
Real T3 server · native Moonshine Streaming Tiny · 16 kHz synthetic speech

Model: ${status.state}
Session revoked: ${revoked} · ${revocation}\nSecond client authenticated: ${authenticated}
Socket: ${closed?`CLOSED (${closeCode})`:"OPEN"}
Updates after revocation: ${after}

${events.slice(-6).join("\n")}`); }
  for(let i=0;i<100;i++) {
    if(i===20) {const result=(await api("/api/auth/clients/revoke",{sessionId:session.sessionId})).data;revoked=true;revocation="HTTP 200 "+JSON.stringify(result);log("Owner revoked second session: "+JSON.stringify(result));const auth=(await api("/api/auth/session",undefined,second.cookie)).data;authenticated=String(auth.authenticated);log("Second client authenticated="+auth.authenticated);}
    if(ws.readyState===WebSocket.OPEN) {const offset=(i*16000)%pcm.length;ws.send(pcm.subarray(offset,Math.min(offset+16000,pcm.length)));}
    if(i%4===0) await show();
    await new Promise(r=>setTimeout(r,250));
  }
  log("Final native model state: "+(await api("/api/voice/status")).data.state);
  await show();
  await app.screenshot("revoked-live-dictation");
  const observedClosed=closed;
  if(ws.readyState===WebSocket.OPEN) ws.close();
  expect(observedClosed).toBe(true);
});
