import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { runPromise, test, WEB } from "./t3.ts";

test("Failed replay recovers, failed snapshot is visible, and a replacement session retries", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("Recovery demo");
  const thread = await t3.thread({project, title:"Message recovery", messages:["go"], model:"command-output"});
  await browser.addInitScript(() => {
    const sockets: WebSocket[] = [];
    const log: {cursor: unknown; failed: boolean}[] = [];
    const errors: string[] = [];
    (window as any).resumeProof = {log, sockets, errors};
    new MutationObserver(() => {
      if (document.body?.innerText.includes('Could not sync messages')) errors.push('Could not sync messages');
    }).observe(document, {subtree:true, childList:true, characterData:true});
    const Native = window.WebSocket;
    window.WebSocket = class extends Native {
      constructor(...args: ConstructorParameters<typeof WebSocket>) { super(...args); sockets.push(this); }
      override send(data: Parameters<WebSocket['send']>[0]) {
        if (typeof data !== 'string') return super.send(data);
        let parsed; try { parsed = JSON.parse(data); } catch {return super.send(data);}
        const messages = Array.isArray(parsed) ? parsed : [parsed];
        const pass = messages.filter(m => {
          if (m._tag !== 'Request' || m.tag !== 'orchestration.subscribeThread') return true;
          const mode = sessionStorage.getItem('proofFault');
          const cursor = m.payload?.afterSequence;
          const failed = mode === 'all' || (mode === 'cursor' && cursor !== undefined);
          log.push({cursor: cursor ?? null, failed});
          if (!failed) return true;
          setTimeout(() => this.dispatchEvent(new MessageEvent('message', {data: JSON.stringify({
            _tag:'Exit', requestId:m.id, exit:{_tag:'Failure',cause:[{_tag:'Die',defect:'replay event could not be decoded'}]}
          })})), 50);
          return false;
        });
        if (pass.length) super.send(JSON.stringify(Array.isArray(parsed) ? pass : pass[0]));
      }
    };
  });
  await browser.emulateMedia({colorScheme:'dark', reducedMotion:'reduce'});
  await t3.open(thread);
  await expect(screen.getByText('The command printed one JSON line.').first()).toBeVisible();
  await runPromise(Effect.sleep('2 seconds'));
  await app.screenshot('01-live-cached-history');
  const url = await browser.evaluate(() => location.href);
  await browser.evaluate(() => sessionStorage.setItem('proofFault','cursor'));
  await app.open(url);
  await runPromise(Effect.sleep('8 seconds'));
  await app.screenshot('02-after-failed-resume');
  const recovery = await browser.evaluate(() => ({log:(window as any).resumeProof.log, errors:(window as any).resumeProof.errors, text:document.body.innerText}));
  await browser.evaluate(() => sessionStorage.setItem('proofFault','all'));
  await app.open(url);
  await runPromise(Effect.sleep('4 seconds'));
  await app.screenshot('03-snapshot-also-fails');
  const failure = await browser.evaluate(() => ({log:(window as any).resumeProof.log, text:document.body.innerText, alerts:[...document.querySelectorAll('[role="alert"]')].map(e=>e.textContent)}));
  await browser.evaluate(() => {sessionStorage.removeItem('proofFault'); for (const s of (window as any).resumeProof.sockets) s.close();});
  await runPromise(Effect.sleep('8 seconds'));
  await expect(screen.getByText('The command printed one JSON line.').first()).toBeVisible({timeout:60000});
  await screen.getByText('Syncing messages...', {exact:true}).waitFor({state:'hidden',timeout:60000});
  await screen.getByText('Could not sync messages', {exact:true}).waitFor({state:'hidden',timeout:60000});
  await app.screenshot('04-replacement-session-recovers');
  const retry = await browser.evaluate(() => ({log:(window as any).resumeProof.log,text:document.body.innerText}));
  console.log('RESUME_PROOF',JSON.stringify({recovery,failure,retry}));
  expect(recovery.log.some((r:any)=>r.failed && r.cursor !== null), 'cached reopen attempted cursor replay').toBe(true);
  expect(recovery.log.some((r:any)=>!r.failed && r.cursor === null), 'failed replay recovered through cursorless snapshot').toBe(true);
  expect(recovery.errors.length, 'snapshot recovery did not briefly render failure').toBe(0);
  expect(recovery.text.includes('Syncing messages'), 'snapshot recovery cleared syncing').toBe(false);
  expect(failure.text.includes('Could not sync messages'), 'failed snapshot shows failure label').toBe(true);
  expect(failure.alerts.some((s:string)=>s?.includes('Could not sync messages')), 'failure has role alert').toBe(true);
  expect(retry.text.includes('Could not sync messages') || retry.text.includes('Syncing messages'), 'replacement session cleared synchronization failure').toBe(false);
});
