import * as path from "path";
import * as fs from "fs";
import * as archiver from "archiver";
import * as mkdirp from "mkdirp";
import * as rimraf from "rimraf";
import { v4 as uuidv4 } from "uuid";
import { ExportOptions } from "./types";
import { downloadS3Folder, getCourseMetadata } from "./shared";

export async function exportToZip(options: ExportOptions): Promise<string> {
  const { courseSlug, bucket, outDir } = options;

  // 1. Create temporary folder
  const tmpName = uuidv4();
  const zipOutDir = path.join(outDir, tmpName);
  rimraf.sync(zipOutDir);
  mkdirp.sync(zipOutDir);

  // 2. Download all course files from bucket to temporary directory
  await downloadS3Folder(bucket, `courses/${courseSlug}/`, zipOutDir);

  // 3. Create ZIP file
  const zipName = `${courseSlug}.zip`;
  const zipPath = path.join(outDir, zipName);

  // Remove existing zip file if it exists
  if (fs.existsSync(zipPath)) {
    fs.unlinkSync(zipPath);
  }

  const output = fs.createWriteStream(zipPath);
  const archive = archiver("zip", { zlib: { level: 9 } });

  return new Promise((resolve, reject) => {
    output.on("close", () => {
      console.log(`✅ ZIP export completed: ${archive.pointer()} total bytes`);
      // Clean up temporary directory
      rimraf.sync(zipOutDir);
      resolve(zipPath);
    });

    archive.on("error", (err) => {
      console.error("❌ ZIP creation error:", err);
      rimraf.sync(zipOutDir);
      reject(err);
    });

    archive.pipe(output);

    // Add all files from the temporary directory to the ZIP
    archive.directory(zipOutDir, false);

    archive.finalize();
  });
}
