/**
 * Smoke test: exercise the agentos sandbox adapter through Flue's
 * createSandboxSessionEnv wrapper — the same path the zopu agent uses.
 *
 * Run:  bun --env-file=../../.env packages/agents/scripts/agentos-adapter-test.ts
 */
import { agentos } from "../src/sandboxes/agentos";

const main = async () => {
  const factory = agentos();

  // Flue calls this once per harness initialization.
  const env = await factory.createSessionEnv({ id: "smoke-test" });

  let pass = 0;
  let fail = 0;
  const assert = (label: string, condition: boolean) => {
    if (condition) {
      pass += 1;
      console.log(`  ✓ ${label}`);
    } else {
      fail += 1;
      console.log(`  ✗ ${label}`);
    }
  };

  console.log("\n=== File operations ===");

  await env.writeFile("test.txt", "hello from Flue adapter");
  assert("writeFile", true);

  const content = await env.readFile("test.txt");
  assert(
    "readFile returns written content",
    content === "hello from Flue adapter"
  );

  const stat = await env.stat("test.txt");
  assert("stat isFile", stat.isFile === true);
  assert("stat size", stat.size === "hello from Flue adapter".length);

  assert("exists true", (await env.exists("test.txt")) === true);
  assert("exists false for missing", (await env.exists("nope.txt")) === false);

  console.log("\n=== Directory operations ===");

  await env.mkdir("subdir", { recursive: true });
  await env.writeFile("subdir/a.ts", "export const a = 1;");
  await env.writeFile("subdir/b.ts", "export const b = 2;");
  const entries = await env.readdir("subdir");
  assert(
    "readdir returns names",
    entries.length === 2 && entries.includes("a.ts")
  );

  await env.rm("subdir/b.ts");
  const after = await env.readdir("subdir");
  assert("rm removes file", after.length === 1 && after[0] === "a.ts");

  await env.rm("subdir", { recursive: true });
  assert("rm recursive removes dir", (await env.exists("subdir")) === false);

  console.log("\n=== Shell exec ===");

  const echoRes = await env.exec("echo 'adapter shell works'");
  assert("exec echo exit code", echoRes.exitCode === 0);
  assert("exec echo stdout", echoRes.stdout.trim() === "adapter shell works");

  const pipeRes = await env.exec("echo 'hello' | tr a-z A-Z");
  assert("exec pipe", pipeRes.stdout.trim() === "HELLO");

  const lsRes = await env.exec("ls", { cwd: "/workspace" });
  assert("exec with cwd", lsRes.stdout.includes("test.txt"));

  const envRes = await env.exec("echo $TEST_VAR", {
    env: { TEST_VAR: "injected" },
  });
  assert("exec with env", envRes.stdout.trim() === "injected");

  console.log(`\n=== ${pass} passed, ${fail} failed ===`);
  if (fail > 0) {
    process.exit(1);
  }
};

try {
  await main();
} catch (error) {
  console.error(error);
  process.exit(1);
}
