const fs = require("fs");
const path = require("path");

const BASE_URL = "https://cdn.jsdelivr.net/pyodide/v0.24.1/full/"

const { loadPyodide } = require("pyodide");

async function generateRepodata(wheels) {
  // fetch original pyodide-lock.json
  const response = await fetch(BASE_URL+"pyodide-lock.json");
  const data = await response.json();
  const ngs_data = JSON.parse(fs.readFileSync('pyodide-lock.json'))

  for (const pname in ngs_data.packages) {
    if (data.packages[pname] === undefined)
      data.packages[pname] = ngs_data.packages[pname]
  }

  fs.writeFileSync('pyodide-lock-ori.json', JSON.stringify(data, null, 2))

  let pyodide = await loadPyodide({lockFileURL: 'pyodide-lock-ori.json'});
  await pyodide.loadPackage(['micropip']);
  pyodide.runPython(`import micropip`);
  for(const wheel of wheels)
    await pyodide.runPythonAsync(`await micropip.install("${wheel}")`);
  const new_data = JSON.parse(pyodide.runPython(`micropip.freeze()`));

  for(const file of fs.readdirSync('.'))
    if(file.endsWith('.whl'))
      fs.rmSync(file)
  fs.rmSync('pyodide-lock-ori.json')

  for (const pname in new_data.packages) {
    const p = new_data.packages[pname];
    if(p.file_name.startsWith('file:'))
      p.file_name = p.file_name.slice(5)

    if(!p.file_name.startsWith("https://") && !p.file_name.startsWith('..') && !fs.existsSync(p.file_name))
      p.file_name = BASE_URL + p.file_name
  }

  for(const wheel of wheels) {
    const name = wheel.replace('file:wheels/', '').split('-')[0]
    const p = new_data.packages[name]
    if (p.imports.length === 0 )
      p.imports = [name]
  }

  return JSON.stringify(new_data, null, 2);
}


const dirname = path.dirname(process.argv[1])
const wheels = []
if(!fs.existsSync("wheels"))
  fs.mkdirSync("wheels");

for (const fpath of process.argv.slice(2)) {
  // copy file to local dir, if its not local already
  const fname = path.normalize(path.relative(dirname, fpath))
  const basename = path.basename(fname)
  wheels.push('file:wheels/'+basename)

  if (fname !== basename) {
    fs.copyFileSync(fpath, 'wheels/'+basename)
  }
}

generateRepodata(wheels).then((result) => {
  fs.writeFileSync('pyodide-lock.json', result);
}).catch((err) => {
    console.log("error", err)
    throw(err);
  });
