import fs from "node:fs";
import path from "node:path";
import { mkdir, writeFile } from "node:fs/promises";

export async function downloadToFile(url, destinationPath) {
  const response = await fetch(url, {
    headers: {
      "User-Agent": "codex-harness-cli"
    },
    redirect: "follow"
  });

  if (!response.ok) {
    throw new Error(`Failed to download ${url}: ${response.status} ${response.statusText}`);
  }

  await mkdir(path.dirname(destinationPath), { recursive: true });
  const buffer = Buffer.from(await response.arrayBuffer());
  await writeFile(destinationPath, buffer);
  return destinationPath;
}

export function fileExists(pathLike) {
  return fs.existsSync(pathLike);
}
