import json
import os
import urllib.request

from setuptools import setup
from setuptools.command.build_py import build_py


def get_latest_npm_version(package):
    url = f"https://registry.npmjs.org/{package}/latest"
    with urllib.request.urlopen(url, timeout=10) as response:
        data = json.loads(response.read())
    return data["version"]


PACKAGES_TO_PIN = []  # deck.gl and chroma-js are now in the vendor bundle


class BuildPyCommand(build_py):
    def run(self):
        super().run()
        js_path = os.path.join(self.build_lib, "holoviz_utils", "deckgl.js")
        if not os.path.exists(js_path):
            return
        with open(js_path) as f:
            content = f.read()
        for package in PACKAGES_TO_PIN:
            version = get_latest_npm_version(package)
            content = content.replace(f"{package}@latest", f"{package}@{version}")
            print(f"Pinned {package} to version {version}")
        with open(js_path, "w") as f:
            f.write(content)


setup(cmdclass={"build_py": BuildPyCommand})
