/// <reference lib="dom" />
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { mkdir, readFile } from 'node:fs/promises';
import { expect } from 'e2e';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { test, WEB, makeState, runPromise } from './t3.ts';

test('CPU and I/O share one overload heading and machine summary', WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project('demo');
  const thread = await t3.thread({project, title:'Pressure details', messages:['Start']});
  await t3.open(thread);
  const pill = browser.locator('[data-host-pressure]');
  await pill.waitFor({timeout:60000});
  await pill.tap();
  await screen.getByText('Work waits on disk reads and writes most of the time, so agents run slowly.', {exact:true}).waitFor();
  await screen.getByText('Syncing messages…',{exact:true}).waitFor({state:'hidden'});
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(a=>a.finished.catch(()=>{}))); return null; });
  await app.screenshot('single-machine-details');
  const singleTitles = await browser.evaluate(() => [...document.querySelectorAll('[role="dialog"] [data-slot="popover-title"]')].map(e => e.textContent));
  await browser.keyboard.press('Escape');
  const home = T3_HOME + '-environment-b-' + Date.now();
  await mkdir(home, {recursive:true});
  const child = spawn(process.execPath, ['apps/server/src/bin.ts', 'serve', '--host', '0.0.0.0', '--port', '13997', '--base-dir', home], {
    cwd: APP_DIR, env:{...process.env, T3CODE_DEV_SEED:'0', T3_PROOF_PRESSURE:'memory', T3CODE_ENVIRONMENT_LABEL:'Environment B'}, stdio:['ignore','pipe','pipe']
  });
  try {
    await new Promise<void>((resolve,reject) => {
      let output='';
      const onData = (data:Buffer) => { output+=data.toString(); if(output.includes('Listening on') || output.includes('Authentication required') || output.includes('pairingUrl:')) resolve(); };
      child.stdout.on('data',onData); child.stderr.on('data',onData);
      child.on('exit', code => reject(new Error('Second server exited '+code+' '+output)));
      setTimeout(()=>reject(new Error('Second server did not start '+output)),60000).unref();
    });
    const pairing = await runPromise(makeState(home).cli(['auth','pairing','create','--ttl','15m','--base-url','http://127.0.0.1:13997']));
    const url = /Pair URL:\s*(\S+)/.exec(pairing.stdout + pairing.stderr)![1];
    await t3.open('/settings/connections');
    await screen.getByRole('button','Add environment',{exact:true}).tap();
    await screen.getByRole('textbox','Host',{exact:true}).fill(url);
    await screen.getByRole('dialog').getByRole('button','Add environment',{exact:true}).tap();
    await screen.getByRole('dialog','Add Environment',{exact:true}).waitFor({state:'hidden',timeout:60000});
    await t3.open(thread);
    await screen.getByRole('button','2 machines need attention',{exact:true}).waitFor({timeout:60000});
    await screen.getByRole('button','2 machines need attention',{exact:true}).tap();
    await screen.getByText('Environment B',{exact:true}).waitFor();
    await browser.evaluate(async () => { await Promise.all(document.getAnimations().map(a=>a.finished.catch(()=>{}))); return null; });
    await app.screenshot('two-machine-details');
    const details = await browser.evaluate(() => document.querySelector('[role="dialog"]')?.textContent ?? '');
    expect(singleTitles.filter(t=>t==='Machine overloaded').length).toBe(1);
    expect(details).not.toContain('Machine overloaded · Machine overloaded');
  } finally {
    child.kill('SIGTERM');
    await once(child,'exit');
  }
});
