// Run the test gate: `cargo test --workspace` + `bun test`.
// Returns { green, output } — output is last ~4KB of combined stdout/stderr.

import { spawn } from "node:child_process";

const REPO_ROOT = "/home/profit/lakehouse";
const TEST_TIMEOUT_MS = 15 * 60 * 1000; // 15 min cargo + 2 min bun, generous

export async function runTests(): Promise<{ green: boolean; output: string }> {
  const cargoOut = await runCmd("cargo", ["test", "--workspace", "--quiet", "--", "--test-threads=1"], REPO_ROOT, TEST_TIMEOUT_MS);
  if (cargoOut.code !== 0) {
    return { green: false, output: tail(`cargo test (${cargoOut.code}):\n${cargoOut.combined}`) };
  }

  const bunOut = await runCmd("bun", ["test", "tests/multi-agent"], REPO_ROOT, 120000);
  const bunGreen = bunOut.code === 0;
  const combined = [
    `cargo test: OK`,
    `bun test (${bunOut.code}):`,
    bunOut.combined,
  ].join("\n");
  return { green: bunGreen, output: tail(combined) };
}

function tail(s: string, n = 4096): string {
  return s.length > n ? "…" + s.slice(-n) : s;
}

function runCmd(
  cmd: string,
  args: string[],
  cwd: string,
  timeoutMs: number,
): Promise<{ code: number; combined: string }> {
  return new Promise(resolveP => {
    const child = spawn(cmd, args, { cwd, env: { ...process.env } });
    let combined = "";
    child.stdout.on("data", d => { combined += d.toString(); });
    child.stderr.on("data", d => { combined += d.toString(); });
    const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
    child.on("close", code => {
      clearTimeout(timer);
      resolveP({ code: code ?? -1, combined });
    });
  });
}
