import fs from "node:fs";
import path from "node:path";

const WRAPPER_PREFIX = '(()=>{ if (typeof window === "undefined") {} else {';
const WRAPPER_SUFFIX = "\n}\n})();\n";

function removeTgzFiles(cwd) {
  for (const entry of fs.readdirSync(cwd, { withFileTypes: true })) {
    if (entry.isFile() && entry.name.endsWith(".tgz")) {
      fs.rmSync(path.join(cwd, entry.name), { force: true });
    }
  }
}

function removeDemoAssets(cwd) {
  const demoPath = path.join(cwd, "assets", "demo");
  if (fs.existsSync(demoPath)) {
    fs.rmSync(demoPath, { recursive: true, force: true });
  }
}

function wrapPlayerBundle(cwd) {
  const bundlePath = path.join(cwd, "qiplayer.js");
  const content = fs.readFileSync(bundlePath, "utf8");

  if (content.startsWith(WRAPPER_PREFIX)) return;

  fs.writeFileSync(bundlePath, `${WRAPPER_PREFIX}${content}${WRAPPER_SUFFIX}`, "utf8");
}

function main() {
  const cwd = process.cwd();
  removeTgzFiles(cwd);
  removeDemoAssets(cwd);
  wrapPlayerBundle(cwd);
}

main();
