const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const pkg = require(path.join(__dirname, '../package.json'));

const abi = process.versions.modules; // Node ABI
let platform = process.platform;     // linux, darwin, win32
const isAlpine = fs.existsSync('/etc/alpine-release');
if (isAlpine) {
  platform = "alpine"
}

const arch = process.arch;             // x64, arm64, etc.
const version = pkg.version;
const isElectron = !!process.versions.electron;
const remote_url = "https://downloads.apryse.com/downloads/nodejs"

let prebuildUrl = `${remote_url}/${version}/pdfnet-addon-v${version}-node-v${abi}-${platform}-${arch}.tar.gz`;
if (isElectron) {
  electron_version = process.versions.electron;
  prebuildUrl = `${remote_url}/${version}/pdfnet-addon-v${version}-electron-v${electron_version}-${platform}-${arch}.tar.gz`;
}

console.log('Downloading prebuilt binary from:', prebuildUrl);

try {
  execSync(`npx prebuild-install --download ${prebuildUrl} --verbose`, { stdio: 'inherit' });

  const extractedFolder = `node-v${abi}-${platform}-${arch}`;
  const libFolder = path.join(extractedFolder, 'lib');
  const targetLibFolder = path.join(process.cwd(), 'lib');

  if (fs.existsSync(libFolder)) {
    if (!fs.existsSync(targetLibFolder)) fs.mkdirSync(targetLibFolder);

    console.log(`Copying contents of ${libFolder} to ${targetLibFolder}...`);

    function copyRecursive(src, dest) {
      if (fs.lstatSync(src).isDirectory()) {
        if (!fs.existsSync(dest)) fs.mkdirSync(dest);
        fs.readdirSync(src).forEach(file => {
          copyRecursive(path.join(src, file), path.join(dest, file));
        });
      } else {
        fs.renameSync(src, dest);
      }
    }

    copyRecursive(libFolder, targetLibFolder);

    function deleteFolderRecursive(folderPath) {
      if (fs.existsSync(folderPath)) {
        fs.readdirSync(folderPath).forEach(file => {
          const curPath = path.join(folderPath, file);
          if (fs.lstatSync(curPath).isDirectory()) {
            deleteFolderRecursive(curPath);
          } else {
            fs.unlinkSync(curPath);
          }
        });
        fs.rmdirSync(folderPath);
      }
    }

    deleteFolderRecursive(extractedFolder);
    console.log(`Cleanup complete: removed ${extractedFolder}`);
  } else {
    console.warn(`Lib folder not found at ${libFolder}, skipping move.`);
  }
} catch (err) {
  console.error('Error during prebuild-install:', err);
  process.exit(1);
}
