import { spawn } from "node:child_process";
import { once } from "node:events";
import path from "node:path";

import { defineTool } from "@flue/runtime";
import * as v from "valibot";

const repositoryRoot = path.resolve(process.cwd(), "../..");

export const paseoCli = defineTool({
  description:
    "Run the locally installed Paseo CLI. Pass every argument exactly as it should appear after the paseo executable.",
  input: v.object({
    args: v.array(v.string()),
  }),
  name: "paseo_cli",
  output: v.object({
    exitCode: v.number(),
    stderr: v.string(),
    stdout: v.string(),
  }),
  async run({ input, signal }) {
    const process = spawn("paseo", input.args, {
      cwd: repositoryRoot,
      signal,
      stdio: ["ignore", "pipe", "pipe"],
    });
    const stderrChunks: Buffer[] = [];
    const stdoutChunks: Buffer[] = [];

    process.stderr.on("data", (chunk: Buffer) => stderrChunks.push(chunk));
    process.stdout.on("data", (chunk: Buffer) => stdoutChunks.push(chunk));

    const [code] = await once(process, "close");
    const exitCode = typeof code === "number" ? code : 1;

    return {
      exitCode,
      stderr: Buffer.concat(stderrChunks).toString(),
      stdout: Buffer.concat(stdoutChunks).toString(),
    };
  },
});
