{{ header }}import { spawn } from 'child_process';
import { resolve } from 'path';

let serverProcess;

export async function setup() {
  // Mock server binary must be pre-built (e.g. by CI or `cargo build --manifest-path e2e/rust/Cargo.toml --bin mock-server --release`)
  serverProcess = spawn(
    resolve(__dirname, '../rust/target/release/mock-server'),
    [resolve(__dirname, '../../fixtures')],
    { stdio: ['pipe', 'pipe', 'inherit'] }
  );

  const url = await new Promise<string>((resolve, reject) => {
    let foundUrl = false;

    serverProcess.stdout.on('data', (data) => {
      const dataStr = data.toString();

      const urlMatch = dataStr.match(/MOCK_SERVER_URL=(.*)/);
      if (urlMatch) {
        process.env.MOCK_SERVER_URL = urlMatch[1].trim();
        foundUrl = true;
      }

      const serversMatch = dataStr.match(/MOCK_SERVERS=({.*})/);
      if (serversMatch) {
        try {
          const servers = JSON.parse(serversMatch[1]);
          for (const [fixtureId, fixtureUrl] of Object.entries(servers)) {
            process.env[`MOCK_SERVER_${fixtureId.toUpperCase()}`] = fixtureUrl as string;
          }
        } catch {
          // Ignore JSON parse errors
        }
      }

      if (foundUrl) resolve(process.env.MOCK_SERVER_URL as string);
    });
    setTimeout(() => reject(new Error('Mock server startup timeout')), 30000);
  });
}

export async function teardown() {
  if (serverProcess) {
    serverProcess.stdin.end();
    serverProcess.kill();
  }
}
