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

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

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

function resolveFlagSource() {
  const projectRequire = createRequire(path.join(root, "package.json"));
  const flagPackagePath = projectRequire.resolve("flag-icons/package.json");
  const flagRoot = path.dirname(flagPackagePath);
  return path.join(flagRoot, "flags");
}

function copyFromZip(zipBackedPath, target, tmpParent) {
  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(tmpParent, ".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;
}

function copyFlagAssetsTo(dest, options = {}) {
  const src = resolveFlagSource();
  const clean = options.clean !== false;
  const tmpParent = options.tmpParent || path.dirname(dest);

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

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

  return dest;
}

function createTempFlagAssets() {
  const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), "mvframe-flags-"));
  const flagsRoot = path.join(tmpRoot, "flags");

  copyFlagAssetsTo(flagsRoot, {
    tmpParent: tmpRoot,
  });

  return {
    flagsRoot,
    tmpRoot,
    cleanup() {
      fs.rmSync(tmpRoot, { recursive: true, force: true });
    },
  };
}

module.exports = {
  copyFlagAssetsTo,
  createTempFlagAssets,
};
