import os
from random import getrandbits
import subprocess

# from codegen_sources.preprocessing.timeout import timeout

BABEL_MINIFY_PATH = "{}/../../../javascript_obfuscator/obfuscator.sh".format(
    os.path.dirname(os.path.realpath(__file__))
)


# @timeout(60)
def obfuscate_for_pretraining(s):
    original_javascript_file = f"/tmp/jsobf_{getrandbits(128)}.js"
    with open(original_javascript_file, "w", errors="ignore") as f:
        f.write(s)

    token_replacement_map = original_javascript_file.replace(".js", ".map")

    map = {}

    proc = subprocess.run(
        [BABEL_MINIFY_PATH, original_javascript_file, token_replacement_map],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        timeout=20,
    )
    if proc.returncode == 0:
        minified_content = proc.stdout.decode("utf-8")
        with open(token_replacement_map, "r", errors="ignore") as f:
            for l in f.readlines():
                tok, rep = l.strip().split(" ", 1)
                if rep in minified_content:
                    map[rep] = tok
        os.remove(original_javascript_file)
        os.remove(token_replacement_map)
        return minified_content, map
    else:
        raise JavaScriptObfuscatorError(
            f"error running javascript obfuscator stdout: {proc.stdout} stderr: {proc.stderr}"
        )
    return "", map


class JavaScriptObfuscatorError(Exception):
    pass
