import { promises as fs } from "node:fs";

export interface ChecksumEntry {
  key: string;
  checksum: string;
}

export async function updateChecksums(
  filePath: string,
  checksumEntries: ChecksumEntry[],
): Promise<void> {
  const deduplicatedEntries = new Map<string, string>();

  for (const entry of checksumEntries) {
    if (deduplicatedEntries.has(entry.key)) {
      continue;
    }

    deduplicatedEntries.set(entry.key, entry.checksum);
  }

  const body = [...deduplicatedEntries.entries()]
    .map(([key, checksum]) => `  "${key}":\n    "${checksum}"`)
    .join(",\n");

  const content =
    "// AUTOGENERATED_DO_NOT_EDIT\n" +
    "export const KNOWN_CHECKSUMS: { [key: string]: string } = {\n" +
    body +
    (body === "" ? "" : ",\n") +
    "};\n";

  await fs.writeFile(filePath, content);
}
