#!/usr/bin/env node
/**
 * Copy flag-icons SVG assets beside the built host bundle.
 * `src/style/chip/flag-icons.scss` points CSS URLs at `/assets/flags/...`.
 */

const fs = require("fs");
const path = require("path");
const { createRequire } = require("module");
const { execFileSync } = require("child_process");

const root = path.resolve(__dirname, "..");
const pnpPath = path.join(root, ".pnp.cjs");

if (fs.existsSync(pnpPath)) {
  require(pnpPath).setup();
}

const projectRequire = createRequire(path.join(root, "package.json"));
const flagPackagePath = projectRequire.resolve("flag-icons/package.json");
const flagRoot = path.dirname(flagPackagePath);
const src = path.join(flagRoot, "flags");
const dest = path.join(root, "dist", "assets", "flags");

function copyFromZip(zipBackedPath, target) {
  const marker = ".zip/";
  const splitAt = zipBackedPath.indexOf(marker);
  if (splitAt < 0) return false;

  const zipPath = zipBackedPath.slice(0, splitAt + ".zip".length);
  const innerPath = zipBackedPath.slice(splitAt + marker.length);
  const tmp = fs.mkdtempSync(path.join(root, ".tmp-flag-icons-"));

  try {
    execFileSync("unzip", ["-q", zipPath, `${innerPath}/*`, "-d", tmp], {
      stdio: "ignore",
    });
    const extracted = path.join(tmp, innerPath);
    fs.cpSync(extracted, target, { recursive: true });
  } finally {
    fs.rmSync(tmp, { recursive: true, force: true });
  }

  return true;
}

fs.rmSync(dest, { recursive: true, force: true });
fs.mkdirSync(path.dirname(dest), { recursive: true });

if (src.includes(".zip/")) {
  copyFromZip(src, dest);
} else if (fs.existsSync(src)) {
  fs.cpSync(src, dest, { recursive: true });
} else {
  throw new Error(`[copy-flag-assets] flag-icons assets not found: ${src}`);
}

console.log(`[copy-flag-assets] copied ${path.relative(root, dest)}`);
