import { cpSync, mkdirSync, renameSync, symlinkSync, statSync, realpathSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { join, dirname } from 'node:path';
import { ProviderDriverKind, ProviderInstanceId } from '@t3tools/contracts';
import { expect } from 'e2e';
import * as Effect from 'effect/Effect';
import * as Duration from 'effect/Duration';
import * as Stream from 'effect/Stream';
import { T3_HOME } from '../e2e.config.ts';
import { rpcClient, runPromise, test, WEB } from './t3.ts';

test('Codex rechecks a recovered real npm installation after the retry interval', WEB, async ({t3, app, screen, browser}) => {
  await browser.emulateMedia({colorScheme:'dark'});
  await t3.project('demo');
  const packages = join(T3_HOME,'bin/node_modules/@openai');
  mkdirSync(packages,{recursive:true});
  const source = join(dirname(realpathSync(execFileSync('which',['codex'],{encoding:'utf8'}).trim())), '../..');
  cpSync(join(source,'codex'),join(packages,'codex'),{recursive:true});
  cpSync(join(source,'codex-linux-x64'),join(packages,'codex-linux-x64'),{recursive:true});
  const cli = join(T3_HOME,'bin/codex');
  symlinkSync('node_modules/@openai/codex/bin/codex.js',cli);
  const platform = join(packages,'codex-linux-x64');
  const fingerprint = statSync(cli);
  renameSync(platform,platform+'.held');
  try { execFileSync(cli,['--version'],{stdio:'pipe'}); throw new Error('CLI should fail with the real platform package absent'); }
  catch (error) { if (!String(error).includes('Missing optional dependency')) throw error; }
  // Startup may have resolved the host CLI before this private installation existed.
  await new Promise(resolve=>setTimeout(resolve,35_000));
  const instanceId = ProviderInstanceId.make('codex-recovery');
  const rpc = <A>(f: (client: any) => Effect.Effect<A, any, any>) => runPromise(Effect.gen(function*(){const client=yield* rpcClient(T3_HOME,app.baseUrl??''); return yield* f(client);}).pipe(Effect.scoped));
  await rpc(client=>client['server.updateSettings']({patch:{backgroundActivity:{profile:'custom',baseProfile:'balanced',overrides:{providerHealthRefreshInterval:Duration.zero}}},providerInstanceMutation:{operation:'upsert',instanceId,instance:{driver:ProviderDriverKind.make('codex'),displayName:'Codex recovery',enabled:true,config:{setupMode:'managed'}}}}));
  await rpc(client=>client['server.refreshProviders']({instanceId,fresh:true}));
  await rpc(client=>client['provider.install.start']({instanceId}));
  await rpc(client=>client['provider.install.subscribe']({instanceId}).pipe(Stream.filter((state:any)=>state.phase==='succeeded'||state.phase==='failed'),Stream.runHead));
  await t3.open('/settings/providers?instanceId=codex-recovery');
  await screen.getByRole('button', /Refresh provider status/).waitFor();
  await screen.getByText('v0.166.0', {exact:true}).first().waitFor();
  await app.screenshot('temporary-local-failure-managed-runtime');
  renameSync(platform+'.held',platform);
  const restored = statSync(cli);
  if (restored.ino!==fingerprint.ino || restored.mtimeMs!==fingerprint.mtimeMs || restored.size!==fingerprint.size) throw new Error('Executable fingerprint changed');
  if (execFileSync(cli,['--version'],{encoding:'utf8'}).trim()!=='codex-cli 0.174.0') throw new Error('Real CLI not restored');
  execFileSync(cli,['app-server','--help'],{stdio:'pipe'});
  // This is the reported retry interval, elapsed on the running real server.
  await new Promise(resolve=>setTimeout(resolve,75_000));
  await screen.getByRole('button', /Refresh provider status/).tap();
  await rpc(client=>client['server.refreshProviders']({instanceId,fresh:true}));
  await screen.getByRole('button', /Refresh provider status/).tap();
  const result:any = await rpc(client=>client['server.refreshProviders']({instanceId,fresh:true}));
  await app.screenshot('recovered-cli-after-75-seconds-and-refresh');
  const provider = result.providers.find((p:any)=>p.instanceId===instanceId);
  await expect(provider.version).toBe('0.174.0');
});
