import * as fs from 'node:fs/promises';
import * as path from 'node:path';
import { ProviderDriverKind, ProviderInstanceId } from '@t3tools/contracts';
import { expect } from 'e2e';
import * as Effect from 'effect/Effect';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { rpcClient, runPromise, test, WEB } from './t3.ts';

test('The Codex update target follows the cwd launcher before a later npm installation', WEB, async ({ t3, app, screen, browser }) => {
  await t3.project('PATH evidence');
  const launcher = path.join(APP_DIR, 'apps/server/codex');
  const oldCodex = process.env.PATH_PROOF_CODEX;
  if (!oldCodex) throw new Error('Set PATH_PROOF_CODEX to the real Codex 0.164.0 executable');
  await fs.writeFile(launcher, `#!/bin/sh\nexec '${oldCodex}' "$@"\n`, { mode: 0o755 });
  const instanceId = ProviderInstanceId.make('codex');
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? '');
    yield* client['server.updateSettings']({ patch: {}, providerInstanceMutation: {
      operation: 'upsert', instanceId, instance: { driver: ProviderDriverKind.make('codex'), enabled: true,
        environment: [{ name: 'PATH', value: ':/usr/local/bin:/usr/bin:/bin', sensitive: false }],
        config: { binaryPath: 'codex' }
      }
    }});
    yield* client['server.refreshProviders']({ instanceId, fresh: true });
  }).pipe(Effect.scoped));
  await t3.open('/settings/providers?instanceId=codex');
  await screen.getByText('v0.164.0', { exact: true }).last().waitFor({ timeout: 60000 });
  await browser.evaluate(() => { document.querySelector('[data-settings-page-scroll]')?.scrollTo(0, 0); });
  await new Promise(resolve => setTimeout(resolve, 1500));
  await app.screenshot('provider-settings');
  await screen.getByRole('button', 'Update available, view details', { exact: true }).last().tap();
  await screen.getByRole('dialog', 'Update available', { exact: true }).waitFor();
  await new Promise(resolve => setTimeout(resolve, 1000));
  await app.screenshot('stable-update-target');
  await new Promise(resolve => setTimeout(resolve, 500));
  await app.screenshot('codex-update-target');
  expect(await screen.getByRole('button', 'Update now', { exact: true }).isVisible(), 'The cwd launcher must not offer an update of the later /usr/local npm installation').toBe(false);
});
