import { expect } from "e2e";
import { writeFileSync, readFileSync } from "node:fs";
import * as Effect from "effect/Effect";
import { IOS, test } from "./t3-mobile.ts";
import { runPromise } from "./t3.ts";
const fault = process.env.T3_PROOF_FAULT_FILE!;
test("Native snapshot failure is visible and foreground wake recovers", IOS, async ({t3, app, screen, device}) => {
  writeFileSync(fault, 'off'); writeFileSync(fault+'.log','');
  const project = await t3.project('Recovery demo');
  await t3.thread({project,title:'Message recovery',messages:['go'],model:'command-output'});
  await device.setAppearance('dark');
  await t3.open();
  await screen.getByText('Message recovery',{exact:false}).first().tap();
  await screen.getByText('The command printed one JSON line.',{exact:false}).first().waitFor({timeout:60000});
  await app.screenshot('01-native-live-history');
  writeFileSync(fault,'all');
  await device.home(); await runPromise(Effect.sleep('12 seconds'));
  await device.openApp('com.t3tools.t3code.dev'); await runPromise(Effect.sleep('4 seconds'));
  await app.screenshot('02-native-snapshot-fails');
  const failed = await screen.getByText('Could not sync messages',{exact:true}).isVisible();
  await device.home(); await runPromise(Effect.sleep('12 seconds'));
  writeFileSync(fault,'off');
  await device.openApp('com.t3tools.t3code.dev'); await runPromise(Effect.sleep('4 seconds'));
  await app.screenshot('03-native-foreground-recovers');
  const clear = !(await screen.getByText('Could not sync messages',{exact:true}).isVisible()) && !(await screen.getByText('Syncing messages…',{exact:true}).isVisible());
  console.log('NATIVE_LABEL_PROOF',readFileSync(fault+'.log','utf8'));
  expect(failed,'Native shows the synchronization failure').toBe(true);
  expect(clear,'Foreground wake clears the failure').toBe(true);
});
