import { execFileSync } from "node:child_process";
import { readFile, stat } from "node:fs/promises";
import { createHash } from "node:crypto";
import { join } from "node:path";
export const generated = path => path === "lib/source-manifest.json" || path === ".source-version.json" || path === "public/source.json" || path.startsWith("public/git-assets/") || path.startsWith("public/source.git/") || /^public\/[^/]+\.(tar\.gz|bundle)$/.test(path);
export async function sourceFiles(root) {
  const paths = execFileSync("git", ["ls-files", "-z"], { cwd: root }).toString().split("\0").filter(Boolean).filter(path => !generated(path));
  const files = new Map();
  for (const path of [...new Set(paths)].sort()) {
    let content;
    try { content = await readFile(join(root, path)); } catch (error) { if (error.code === "ENOENT") continue; throw error; }
    if (path === ".openai/hosting.json") { const config = JSON.parse(content); delete config.project_id; content = Buffer.from(JSON.stringify(config) + "\n"); }
    const mode = (await stat(join(root, path))).mode & 0o111 ? 0o755 : 0o644;
    files.set(path, { content, mode });
  }
  return files;
}
export function sourceDigest(files) {
  const hash = createHash("sha256");
  for (const [path, { content, mode }] of files) hash.update(path).update("\0").update(String(mode)).update("\0").update(String(content.length)).update("\0").update(content);
  return hash.digest("hex");
}
