import json
import os
import shutil


def install_ambient(ctx):
    runcmd_prepend_to_path = globals()["runcmd_prepend_to_path"]
    srcdir = globals()["srcdir"]

    # Add the directory where the binaries have been installed to PATH.
    bindir = os.environ.get("BINDIR")
    if bindir is None:
        raise Exception("set BINDIR to point to directory with Ambient binaries")
    if not os.path.exists(bindir):
        error = f"$BINDIR point to an existing directory: {bindir} does not exist"
        raise Exception(error)

    ctx["driver"] = os.path.join(bindir, "ambient")
    ctx["executor"] = os.path.join(bindir, "ambient-execute-plan")
    for bin in [ctx["driver"], ctx["executor"]]:
        if not os.path.exists(bin):
            raise Exception(f"{bin} MUST exist")
        shutil.copy(bin, ".")

    runcmd_prepend_to_path(ctx, dirname=os.path.abspath("."))


def install_vm_image(ctx, filename=None):
    assert "/" not in filename

    image = os.environ.get("IMAGE")
    if image is None:
        raise Exception("set IMAGE in environment to path to Ambient image to use")
    if not os.path.exists(image):
        raise Exception("$IMAGE MUST point to an existing file")

    os.symlink(image, filename)


def json_file_has_key_value(ctx, filename=None, key=None, value=None):
    assert_eq = globals()["assert_eq"]

    assert "/" not in filename
    with open(filename) as f:
        obj = json.load(fp=f)
    for k in key.split("."):
        actual = obj[k]
        obj = obj[k]
    actual = str(actual)  # We get expected value as a string from the step
    assert_eq(value, actual)
