"""Publish the frozen declared graphs and compare real public adjacency."""

import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import time

from corpus import ADMISSION, HERE, cases, manifest


def compare(case, observed):
    if observed["before"] != observed["after"]:
        raise RuntimeError("public reads changed application revision")
    identities = {}
    for node in observed["nodes"]:
        page = node["entity"]
        if page["coverage"]["state"] != "complete" or len(page["items"]) != 1:
            raise RuntimeError("exact entity observation incomplete")
        entity = page["items"][0]["record"]
        identities[ADMISSION.encoded(entity["record"]["metadata"]["id"])] = node["key"]
    comparisons = []
    for node in observed["nodes"]:
        for direction in ["outgoing", "incoming"]:
            found = []
            for adjacency in node["adjacency"]:
                if adjacency["direction"] != direction:
                    continue
                page = adjacency["page"]
                if page["omissions"] or page["coverage"]["state"] != "complete":
                    raise RuntimeError("adjacency has omissions")
                for item in page["items"]:
                    row = item["record"]
                    found.append(
                        {
                            "source": identities[ADMISSION.encoded(row["source"])],
                            "target": identities[
                                ADMISSION.encoded(row["edge"]["target"])
                            ],
                            "kind": row["edge"]["kind"],
                        }
                    )
            selected = "source" if direction == "outgoing" else "target"
            expected = [edge for edge in case["edges"] if edge[selected] == node["key"]]
            if sorted(found, key=ADMISSION.encoded) != sorted(
                expected, key=ADMISSION.encoded
            ):
                raise RuntimeError(
                    f"{case['label']} {node['key']} {direction}: edge mismatch"
                )
            comparisons.append(
                {"key": node["key"], "direction": direction, "edges": found}
            )
    if {n["key"] for n in observed["nodes"]} != {n["key"] for n in case["nodes"]}:
        raise RuntimeError("node membership mismatch")
    return comparisons


def run(args):
    root = Path(args.output).resolve()
    root.mkdir(exist_ok=True)
    declared = cases()
    frozen = root / "declared.json"
    expected_bytes = ADMISSION.encoded(declared)
    if frozen.exists() and frozen.read_bytes() != expected_bytes:
        raise RuntimeError("declared graph cases changed")
    frozen.write_bytes(expected_bytes)
    repository, home = root / "repository", root / "home"
    repository.mkdir(exist_ok=True)
    home.mkdir(exist_ok=True)
    subprocess.run(["git", "init", str(repository)], capture_output=True, check=True)
    location = repository / ".fettl/trellis/knowledge.v1.json"
    location.parent.mkdir(parents=True, exist_ok=True)
    env = {**os.environ, "HOME": str(home)}
    metadata_template = json.loads(
        (HERE.parent / "vsa-1310/inputs/metadata-template.json").read_bytes()
    )
    for case in declared:
        label = case["label"]
        target = root / (label if label.startswith("hub-") else "mixed")
        target.mkdir(exist_ok=True)
        if (root / f"{label}-comparison.json").exists():
            continue
        initial_path = target / "initial.json"
        if initial_path.exists():
            initial = json.loads(initial_path.read_bytes())
        else:
            initial = publish(
                args,
                env,
                repository,
                location,
                target,
                ADMISSION.empty_manifest(),
                "initial",
                True,
            )
            initial_path.write_bytes(ADMISSION.encoded(initial))
        metadata = dict(metadata_template)
        metadata["validity"] = {
            "valid_from": initial["new_revision"]["graph_revision"],
            "valid_through": None,
        }
        document = manifest(case, metadata)
        publication = publish(
            args, env, repository, location, target, document, label, False
        )
        options = {
            "state": str(target / "state"),
            "scope": initial["scope"],
            "nodes": case["nodes"],
            "deadline_seconds": args.deadline_seconds,
        }
        options_path = root / f"{label}-options.json"
        options_path.write_bytes(ADMISSION.encoded(options))
        started = time.perf_counter_ns()
        process = subprocess.run(
            [args.observer, str(options_path)], capture_output=True
        )
        (root / f"{label}-reader-receipt.json").write_bytes(
            ADMISSION.encoded(
                {
                    "exit": process.returncode,
                    "elapsed_ns": time.perf_counter_ns() - started,
                    "stderr": process.stderr.decode(),
                }
            )
        )
        (root / f"{label}-readback.json").write_bytes(process.stdout)
        if process.returncode:
            raise RuntimeError(f"{label}: {process.stderr.decode()}")
        observation = json.loads(process.stdout)
        comparison = compare(case, observation)
        (root / f"{label}-comparison.json").write_bytes(
            ADMISSION.encoded(
                {
                    "label": label,
                    "revision": observation["revision"],
                    "edges": comparison,
                    "publication": publication,
                    "read_revision_unchanged": True,
                }
            )
        )
        print(label, flush=True)


def publish(args, env, repository, location, target, document, label, create):
    encoded = ADMISSION.encoded(document)
    location.write_bytes(encoded)
    (target / f"{label}-manifest.json").write_bytes(encoded)
    argv = [
        args.fettl,
        "trellis",
        "manifest",
        "import",
        "--repository-root",
        str(repository),
        "--state-root",
        str(target / "state"),
        "--store-id",
        "research-1316",
        "--owner-identity",
        "research-1316",
        "--host-generation",
        "research-1316",
        "--max-anchor-bytes",
        str(len(encoded)),
        "--max-nesting",
        str(ADMISSION.depth(document)),
    ]
    if create:
        argv.append("--create-store")
    started = time.perf_counter_ns()
    process = subprocess.run(argv, env=env, capture_output=True)
    receipt = {
        "argv": argv,
        "exit": process.returncode,
        "stdout": process.stdout.decode(),
        "stderr": process.stderr.decode(),
        "elapsed_ns": time.perf_counter_ns() - started,
        "manifest_sha256": hashlib.sha256(encoded).hexdigest(),
    }
    (target / f"{label}-publication.json").write_bytes(ADMISSION.encoded(receipt))
    if process.returncode:
        raise RuntimeError(receipt)
    return json.loads(process.stdout)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--fettl", required=True)
    parser.add_argument("--observer", required=True)
    parser.add_argument("--deadline-seconds", required=True, type=int)
    parser.add_argument("--output", required=True)
    run(parser.parse_args())
