import networkx
from pathlib import Path
import sys
import subprocess


def browse_graph_ml(filename=None):
    graph = networkx.readwrite.graphml.read_graphml(filename)

    header = "choose a node by typing. Ctrl-c to quit"
    p = subprocess.Popen(
        ["fzf", "--header", header], stdin=subprocess.PIPE, stdout=subprocess.PIPE
    )
    chosen = p.communicate("\n".join(graph.nodes).encode("utf-8"))[0].decode("utf-8")
    stack = [chosen]

    if chosen:
        while True:
            if chosen.startswith("parent: ") or chosen.startswith("child: "):
                chosen = chosen[chosen.find(" ") + 1 :]
            chosen = chosen.strip()
            lines = []
            for child in reversed(sorted(graph.successors(chosen))):
                lines.append(f"child: {child}")
            lines.append("")
            for parent in reversed(sorted(graph.predecessors(chosen))):
                lines.append(f"parent: {parent}")
            lines = "\n".join(lines)
            header = f"Examining: {chosen}"
            p = subprocess.Popen(
                ["fzf", "--header", header],
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
            )
            chosen = p.communicate(lines.encode("utf-8"))[0].decode("utf-8")
            if not chosen:
                if len(stack) > 1:
                    chosen = stack.pop()
                    chosen = stack.pop()
                else:
                    break
            else:
                if not stack or stack[-1] != chosen:
                    stack.append(chosen)


def cli_browse_graph_ml():
    try:
        filename = sys.argv[1]
    except IndexError:
        print("ppg2_browse_graph_ml <path_to_.graphml>")
        sys.exit(1)
    browse_graph_ml(filename)


def record_as_generated_file(filename, history):
    import pypipegraph2 as ppg2

    if not filename.exists():
        raise FileNotFoundError(filename)

    present = filename in history
    print("already present?", present)
    if present:
        had_input = bool(history[filename][0])
        had_output = bool(history[filename][1])
        print("had output", had_output)
        print("had input", had_input)
    if not present or (not had_output) and (not had_input):
        print("ok, fixing,", filename)
        history[filename] = (
            {},
            {str(filename): ppg2.hashers.hash_file(filename)},
        )
    else:
        print("skipping", filename)


def cli_record_as_generated_file():
    """Record <filename> (relative path) as if it was
    done by a filegenerating job - provided it wasn't recorded
    previously, and it had no input.

    This should not be necessary in almost all circumstances.

    """
    import pypipegraph2 as ppg2

    if len(sys.argv) <= 1:
        print("ppg2_record_as_generated_file <filename>")
        print("Records this file as if it had been generated by the pipegraph")
        print("(only useful if the job in question is not being invalidated")
        sys.exit(1)
    else:
        g = ppg2.new()
        history = g._load_history()

        for filename in sys.argv[1:]:
            record_as_generated_file(Path(filename), history)
        g._save_history(history)
