// src/packager.ts
// Creates a flat ZIP archive of an HLS output directory.
// Video segments (.ts) are already compressed, so zlib level 0 (store only)
// is used to avoid wasting CPU on content that won't compress further.

import archiver from "archiver";
import { createWriteStream } from "fs";

/**
 * Zip the contents of sourceDir (flat – no parent prefix inside the zip).
 * @returns Total bytes written to the zip file.
 */
export function createZipArchive(
  sourceDir: string,
  outputZipPath: string
): Promise<number> {
  return new Promise((resolve, reject) => {
    const output  = createWriteStream(outputZipPath);
    const archive = archiver("zip", {
      zlib: { level: 0 }, // store-only; .ts segments are already compressed
    });

    output.on("close", () => resolve(archive.pointer()));

    archive.on("error", reject);
    archive.on("warning", (err) => {
      if (err.code === "ENOENT") {
        console.warn("[Packager] Warning:", err.message);
      } else {
        reject(err);
      }
    });

    archive.pipe(output);
    // false = files land at the root of the zip, not inside a subdirectory.
    archive.directory(sourceDir, false);
    archive.finalize();
  });
}
