from pathlib import Path
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
import os

import subprocess


class BuildScript(BuildHookInterface):
    PLUGIN_NAME = "build_injected_script"

    def initialize(self, version, build_data):
        script_dir = Path(os.path.dirname(os.path.abspath(__file__)))
        if (script_dir/"src"/"caserunner"/"inject"/"package.json").exists():
        # command = ['esbuild', 'src/caserunner/injected/injectedScript.ts', '--bundle', '--outfile=src/caserunner/injected/injectedScript.js']
            subprocess.run("npm install", check=True, cwd=(script_dir/"src"/"caserunner"/"inject").absolute(), shell=True)
            #command = ['esbuild', 'src/caserunner/inject/src/index.ts', '--bundle',
            #        '--outfile=src/caserunner/inject/inject-bundle.js', '--format=iife', '--minify']
            #subprocess.run(command, check=True, cwd=script_dir.absolute(), shell=True)
            subprocess.run("npm run build", check=True, cwd=(script_dir/"src"/"caserunner"/"inject").absolute(), shell=True)

        return super().initialize(version, build_data)
