import logging
import os


def install_jt(ctx):
    runcmd_prepend_to_path = globals()["runcmd_prepend_to_path"]
    runcmd_run = globals()["runcmd_run"]
    runcmd_exit_code_is_zero = globals()["runcmd_exit_code_is_zero"]
    srcdir = globals()["srcdir"]

    target = os.environ.get("CARGO_TARGET_DIR", os.path.join(srcdir, "target"))
    bindir = os.path.join(target, "debug")
    runcmd_prepend_to_path(ctx, bindir)

    # Configure git.

    runcmd_run(ctx, ["git", "config", "--global", "user.name", "J. Random Hacker"])
    runcmd_exit_code_is_zero(ctx)

    runcmd_run(ctx, ["git", "config", "--global", "user.email", "subplot@example.com"])
    runcmd_exit_code_is_zero(ctx)


def create_script(ctx, filename=None):
    get_file = globals()["get_file"]
    text = get_file(filename)
    open(filename, "wb").write(text)
    os.chmod(filename, 0o755)


def run_jt_init(ctx, dirname=None, journalname=None, title=None):
    runcmd_run = globals()["runcmd_run"]
    runcmd_run(ctx, [_binary("jt"), "init", dirname, journalname, title])


def run_jt_list_journals(ctx):
    runcmd_run = globals()["runcmd_run"]
    runcmd_run(ctx, [_binary("jt"), "list-journals"])


def run_jt_is_journal(ctx, dirname=None):
    runcmd_run = globals()["runcmd_run"]
    runcmd_run(ctx, [_binary("jt"), "is-journal", dirname])


def run_jt_new(ctx, title=None, dirname=None):
    runcmd_run = globals()["runcmd_run"]
    runcmd_run(
        ctx, [_binary("jt"), "new", title, "--dirname", dirname, "--editor=none"]
    )


def run_jt_edit(ctx, editor=None, dirname=None):
    runcmd_run = globals()["runcmd_run"]
    env = dict(os.environ)
    env["JT_LOG"] = "jt"
    runcmd_run(
        ctx, [_binary("jt"), "edit", "--dirname", dirname, "--editor", editor], env=env
    )


def run_jt_finish(ctx, dirname=None):
    runcmd_run = globals()["runcmd_run"]
    runcmd_run(ctx, [_binary("jt"), "finish", "--dirname", dirname])


def _binary(name):
    srcdir = globals()["srcdir"]
    return os.path.join(srcdir, "target", "debug", "jt")


def output_contains(ctx, pattern=None):
    assert_eq = globals()["assert_eq"]
    logging.debug("checking if %r contains", ctx["stdout"], pattern)
    assert_eq(pattern in ctx["stdout"], True)


def journal_has_no_drafts(ctx, dirname=None):
    _journal_has_n_drafts(ctx, 0, dirname=dirname)


def journal_has_one_draft(ctx, dirname=None):
    _journal_has_n_drafts(ctx, 1, dirname=dirname)


def journal_has_two_drafts(ctx, dirname=None):
    _journal_has_n_drafts(ctx, 2, dirname=dirname)


def _journal_has_n_drafts(ctx, n, dirname=None):
    assert_eq = globals()["assert_eq"]
    logging.debug(f"checking {dirname} has {n} drafts")
    drafts = os.path.join(dirname, "drafts")
    assert_eq(len(_find_files(drafts)), n)


def journal_has_no_entries(ctx, dirname=None):
    assert_eq = globals()["assert_eq"]
    logging.debug(f"checking {dirname} has no entries")
    entries = os.path.join(dirname, "entries")
    assert_eq(_find_files(entries), [])


def journal_has_one_entry(ctx, dirname=None, variable=None):
    assert_eq = globals()["assert_eq"]
    logging.debug(
        f"checking {dirname} has one entry, whose filename is remembered as {variable}"
    )
    entries = os.path.join(dirname, "entries")
    files = _find_files(entries)
    assert_eq(len(files), 1)
    variables = ctx.get("variables", {})
    variables[variable] = files[0]
    ctx["variables"] = variables


def journal_has_two_entries(ctx, dirname=None, variable1=None, variable2=None):
    assert_eq = globals()["assert_eq"]
    logging.debug(f"checking {dirname} has two entries")
    entries = os.path.join(dirname, "entries")
    files = list(sorted(_find_files(entries)))
    assert_eq(len(files), 2)
    variables = ctx.get("variables", {})
    variables[variable1] = files[0]
    variables[variable2] = files[1]
    ctx["variables"] = variables


def _find_files(root):
    if not os.path.exists(root):
        return []

    files = []
    for dirname, _, basenames in os.walk(root):
        for basename in basenames:
            files.append(os.path.join(dirname, basename))
    return files


def draft_contains_string(ctx, dirname=None, draftno=None, pattern=None):
    logging.debug(f"checking draft {draftno} in {dirname} has contains {pattern!r}")
    draft = os.path.join(dirname, "drafts", f"{draftno}.md")
    with open(draft) as f:
        data = f.read()
        logging.debug(f"draft content: {data!r}")
        assert pattern in data


def draft_links_to_topic(ctx, dirname=None, draftno=None, topic=None):
    logging.debug(f"checking draft {draftno} in {dirname} links to {topic!r}")
    draft_contains_string(
        ctx, dirname=dirname, draftno=draftno, pattern=f'\n[[!meta link="{topic}"]]\n'
    )


def edit_draft(ctx, dirname=None, draftno=None, text=None):
    logging.debug(f"editing draft {draftno} in {dirname} to also contain {text!r}")
    draft = os.path.join(dirname, "drafts", f"{draftno}.md")
    with open(draft, "a") as f:
        f.write(text)


def file_contains(ctx, variable=None, pattern=None):
    logging.debug(f"checking {variable} contains {pattern!r}")

    variables = ctx.get("variables", {})
    logging.debug(f"variables: {variables!r}")

    filename = variables[variable]
    with open(filename) as f:
        data = f.read()
        logging.debug(f"file content: {data!r}")
        assert pattern in data


def file_name_has_suffix(ctx, varname=None, suffix=None):
    variables = ctx.get("variables", {})
    filename = variables[varname]
    assert filename.endswith(suffix)


def git_is_clean(ctx, dirname=None):
    runcmd_run = globals()["runcmd_run"]
    runcmd_exit_code_is_zero = globals()["runcmd_exit_code_is_zero"]
    runcmd_get_stdout = globals()["runcmd_get_stdout"]
    assert_eq = globals()["assert_eq"]

    runcmd_run(ctx, ["git", "status", "--porcelain"], cwd=dirname)
    runcmd_exit_code_is_zero(ctx)

    stdout = runcmd_get_stdout(ctx)
    assert_eq(stdout, "")
