"""
Utilities for managing Node.js packages.
"""
import subprocess
from pathlib import Path
from sys import stderr

from termcolor import colored


def install_packages(prefix: Path) -> None:
    """
    Install Node.js packages.

    Args:
        prefix: The directory prefix to use for ``node_modules``. It must exist and contain a
            ``package.json`` and ``package-lock.json`` file.

    .. tip:: The lockfile can be generated by executing the following:

        .. code-block:: bash

            rm -rf node_modules/ package-lock.json
            npm install --package-lock-only

    """
    if not (prefix / 'node_modules').exists():
        for file in [prefix / 'package.json', prefix / 'package-lock.json']:
            if not file.exists():
                raise RuntimeError(f'Missing Node.js package file "{file}"')
        print(colored('Installing Node.js packages', 'yellow', attrs=['bold']), file=stderr)
        args = ['--no-save', '--no-audit', '--no-fund']
        command = ['npm', 'install', *args, '--prefix', str(prefix)]
        subprocess.run(command, text=True, check=True)  # nosec: secure, not using untrusted input
