import * as fs from 'node:fs/promises';
import { expect } from 'e2e';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { run } from './shell.ts';
import { test, WEB, runPromise } from './t3.ts';

const pause = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

test('Hung automatic branch naming releases launch and freezes completed async setup durations', WEB, async ({ t3, app, browser }) => {
  await browser.addInitScript(() => {
    // Conceal only shell prompt/command rows that expose the synthetic workspace path.
    document.addEventListener('DOMContentLoaded', () => {
      const style = document.createElement('style');
      style.textContent = '[aria-label="Worktree setup"] pre > div:nth-child(-n+3) { visibility: hidden; }';
      document.head.append(style);
    });
  });
  const settingsFile = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsFile, 'utf8'));
  const stub = `${T3_HOME}/bin/hung-codex`;
  await fs.writeFile(stub, `#!/bin/sh\ncase "$1" in\n--version) echo 'codex-cli 0.156.1';;\nmcp) echo '[]';;\nexec) exec sleep 300;;\n*) exit 0;;\nesac\n`, { mode: 0o755 });
  settings.providerInstances.codex.config.binaryPath = stub;
  settings.textGenerationModelSelection = { instanceId: 'codex', model: 'gpt-6-luna' };
  settings.providerInstances.devReplay.enabled = true;
  settings.providerInstances.devReplay.config.enabled = true;
  const results: Array<{status: string | null, first: string, second: string, released: boolean, notice: boolean}> = [];
  const projects = [];
  for (const exit of [0, 7]) projects.push(await t3.project(`async-exit-${exit}`));
  for (const [index, exit] of [0, 7].entries()) {
    settings.defaultProjectScripts = [{ id: 'setup', name: 'Setup', command: `printf 'setup finished (exit ${exit})\\n'; (exit ${exit})`, icon: 'play', runOnWorktreeCreate: true, async: true }];
    await fs.writeFile(settingsFile, JSON.stringify(settings));
    await pause(1500);
    const { stdout } = await runPromise(run(process.execPath, ['apps/server/src/bin.ts', 'thread', 'start', projects[index]!, exit === 0 ? 'Add a hello world function' : 'Write a README section', '--title', `Async setup exit ${exit}`, '--worktree', 'main', '--provider', 'devReplay', '--model', 'multi-turn', '--json', '--base-dir', T3_HOME], { cwd: APP_DIR, env: {PATH: process.env.PATH, HOME: process.env.HOME} }));
    const thread = JSON.parse(stdout);
    await t3.open(thread);
    // Observe the same elapsed intervals on both commits, including before the naming deadline.
    await pause(4000);
    const row = browser.locator('[data-worktree-setup-stage="setup-script"]');
    const status = await row.getAttribute('data-worktree-setup-status');
    const first = await row.textContent() ?? '';
    await app.screenshot(`exit-${exit}-early-completion`);
    await pause(6000);
    const second = await row.textContent() ?? '';
    await app.screenshot(`exit-${exit}-duration-stays-fixed`);
    await pause(15000);
    const released = await browser.evaluate(() => document.body.innerText.includes('first fixture turn complete'));
    const notice = await browser.evaluate(() => document.body.innerText.includes('Could not rename the worktree branch'));
    if (notice) {
      await browser.evaluate(() => {
        const notice = Array.from(document.querySelectorAll<HTMLElement>('[role="button"], button')).find(button => button.getAttribute('aria-label')?.startsWith('Could not rename the worktree branch'));
        notice?.click();
      });
      await pause(600);
    }
    await app.screenshot(`exit-${exit}-agent-released`);
    results.push({status, first, second, released, notice});
  }
  // Both paths have been recorded even when base retains the first setup spinner.
  expect(results.map(r => r.status)).toEqual(['done', 'failed']);
  for (const result of results) {
    expect(result.second).toEqual(result.first);
    expect(result.released).toBe(true);
    expect(result.notice).toBe(true);
  }
});
