import json
import logging
import os
import shutil
import yaml


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

    # Find the radicle-smoke binary from cargo target directory.
    default_target = os.path.join(srcdir, "target")
    target = os.environ.get("CARGO_TARGET_DIR", default_target)
    debug = os.path.join(target, "debug")
    adapter = os.path.join(debug, "radicle-ci-ambient")
    assert os.path.exists(adapter)

    # Copy the radicle-smoke binary to a bin directory, add that to $PATH.
    bin = os.path.abspath("bin")
    os.mkdir(bin)
    shutil.copy2(adapter, bin)
    runcmd_prepend_to_path(ctx, dirname=bin)


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 only_html_log_contains(ctx, directory=None, text=None):
    assert_eq = globals()["assert_eq"]

    projects = os.listdir(directory)
    assert_eq(len(projects), 1)

    project = os.path.join(directory, projects[0])
    logs = os.listdir(project)
    html = [x for x in logs if x.endswith(".html")]
    logging.debug(f"HTML logs: {html}")
    assert_eq(len(html), 1)

    filename = os.path.join(project, html[0])
    log = open(filename).read()

    indented = indent_log_lines(log)
    logging.debug(f"HTML log: {indented}")
    assert text in log


def indent_log_lines(s):
    out = ""
    for line in s.splitlines():
        out += f"    {line}\n"
    return out
