"""Public inputs, golden observations, and the file exchange format."""
import copy
import json
import re
from pathlib import Path

from wire import Binding, Invalid, PROFILE, b64, canonical, digest, no_duplicates, require, unpack


def read(path):
    return json.loads(Path(path).read_bytes(), object_pairs_hook=no_duplicates)


def save(path, value):
    with Path(path).open("x", encoding="ascii") as target:
        json.dump(value, target, sort_keys=True, indent=2, ensure_ascii=True)
        target.write("\n")


def identity(name, build):
    require(all(isinstance(s, str) and re.fullmatch(r"[A-Za-z0-9._-]{1,96}", s)
                for s in (name, build)), "bad implementation identity")
    return {"id": name, "build": build}


class Corpus:
    def __init__(self, folder):
        base = Path(folder)
        self.suite_hash = digest((base / "manifest.json").read_bytes())
        manifest = read(base / "manifest.json")
        names = [f"cases/{i:02d}.json" for i in range(1, 12)]
        require(manifest["profile"] == PROFILE and
                set(manifest["files"]) == set(names) | {"fixtures.json", "schema.json"}, "wrong corpus")
        for name, fingerprint in manifest["files"].items():
            require(digest((base / name).read_bytes()) == fingerprint, f"altered fixture {name}")
        self.fx = read(base / "fixtures.json")
        self.binding = Binding(self.fx, read(base / "schema.json"))
        self.cases = [read(base / name) for name in names]
        self.clock = self.fx["clock"]

    def generate(self):
        objects = {name: self.binding.token(item["claims"], item["signer"])
                   for name, item in self.fx["objects"].items()}
        packets = {}
        def message(name):
            if name in packets:
                return packets[name]
            entry = self.fx["messages"][name]
            template = entry["input"]
            if "source" in template:
                raw = message(template["source"])[0]
                old, new = (template[k].encode("ascii") for k in ("oldAscii", "newAscii"))
                require(raw.count(old) == 1, "ambiguous transport mutation")
                result = (raw.replace(old, new), None)
            else:
                body = copy.deepcopy(template["body"])
                req = None
                if entry["type"] == "request":
                    body["chain"] = [objects[ref] for ref in body["chain"]]
                    body["appraisal"] = objects[body["appraisal"]]
                else:
                    req = message(entry["request"])[1]
                    body["requestRef"] = digest(req.signature.encode("ascii"))
                    if body["evidence"] is not None:
                        body["evidence"] = objects[body["evidence"]]
                result = self.binding.build(body, entry["created"], template["signer"],
                                            template.get("path"), template.get("status"), req)
            packets[name] = result
            return result
        messages = {name: b64(message(name)[0]) for name in self.fx["messages"]}
        return {"objects": objects, "messages": messages}

    def packet_hashes(self, packets):
        require(set(packets) == {"objects", "messages"}, "missing packet group")
        by_name = {}
        for group in ("objects", "messages"):
            require(set(packets[group]) == set(self.fx[group]), "missing or extra packets")
            by_name[group] = {}
            for name, value in packets[group].items():
                raw = value.encode("ascii") if group == "objects" else unpack(value)
                by_name[group][name] = digest(raw)
        return {"root": by_name["objects"]["root"], "request": by_name["messages"]["charge-a"],
                "response": by_name["messages"]["completed"], "catalog": digest(canonical(by_name))}

    def golden(self):
        return {"objects": {k: v["compact"] for k, v in self.fx["objects"].items()},
                "messages": {k: v["wireB64"] for k, v in self.fx["messages"].items()}}

    def emit(self, who):
        generated = self.generate()
        require(generated == self.golden(), "encoder output differs from the public wire bytes")
        return {"profile": PROFILE, "suiteHash": self.suite_hash, "producer": who, "packets": generated}

    def peer(self, bundle):
        require(set(bundle) == {"profile", "suiteHash", "producer", "packets"} and bundle["profile"] == PROFILE
                and bundle["suiteHash"] == self.suite_hash, "incompatible suite")
        require(set(bundle["producer"]) == {"id","build"}, "producer identity shape")
        identity(bundle["producer"]["id"],bundle["producer"]["build"])
        packets = bundle["packets"]
        require(self.packet_hashes(packets) == self.packet_hashes(self.golden()), "unexpected peer packet bytes")
        return Peer(self, packets)

    def expected_runs(self):
        expected = {}
        for case in self.cases[:10]:
            for run in case["runs"]:
                key = f"{case['case']:02d}/{run['name']}"
                expected[key] = {"decisions": [step["expect"] for step in run["steps"]], "final": run["final"],
                                 "checkpoints": {str(i): s["observe"] for i,s in enumerate(run["steps"],1) if "observe" in s},
                                 "races": {str(i): s["results"] for i,s in enumerate(run["steps"],1) if "results" in s}}
        return expected

    def compare(self, a, b):
        expected = self.expected_runs()
        digests = self.packet_hashes(self.golden())
        for r in (a, b):
            require(set(r) == {"profile","suiteHash","producer","consumer","packetHashes","runs","liveRace"}
                    and r["profile"] == PROFILE and r["suiteHash"] == self.suite_hash, "suite or report format")
            for party in (r["producer"],r["consumer"]):
                require(set(party) == {"id","build"}, "identity shape")
                identity(party["id"],party["build"])
            require(all(r["producer"][k] != r["consumer"][k] for k in ("id","build")), "same identity or build")
            require(r["packetHashes"] == digests, "packet hashes")
            require(canonical(r["runs"]) == canonical(expected), "scenario observations")
            live = r["liveRace"]
            limits = self.cases[10]["liveRace"]
            require(live["winner"] in limits["permittedWinners"] and
                    canonical(live) == canonical({**{k: limits[k] for k in ("available","charges","settled")},
                                                  "winner":live["winner"]}), "race outcome")
        require(a["producer"] == b["consumer"] and b["producer"] == a["consumer"], "reciprocal identities")
        return "MATCH"


class Peer:
    """The consumers below receive peer bytes. They never synthesize a replacement packet."""
    def __init__(self, suite, packets):
        self.suite = suite
        self.binding = suite.binding
        self.objects = packets["objects"]
        self.raw = {name: unpack(value) for name, value in packets["messages"].items()}

    def claim(self, label, kind):
        require(label in self.objects, "missing peer object")
        return self.binding.open_token(self.objects[label], kind)

    def message(self, label, now, associated=None):
        context = None
        if associated is not None:
            issued = self.suite.fx["messages"][associated]["created"]
            require(issued <= now, "request context is in the future")
            context = self.binding.receive(self.raw[associated], issued)
        return self.binding.receive(self.raw[label], now, context)

    def audit_catalog(self):
        invalid_objects, invalid_messages = [], []
        for label, compact in self.objects.items():
            try:
                claims = self.binding.open_token(compact)
            except Invalid:
                invalid_objects.append(label)
            else:
                require(claims == self.suite.fx["objects"][label]["claims"], "claim mismatch")
        for label, entry in self.suite.fx["messages"].items():
            try:
                msg = self.message(label, entry["created"], entry["request"])
            except Invalid:
                invalid_messages.append(label)
            else:
                require(b64(msg.base) == entry["baseB64"], "signature base mismatch")
        require(sorted(invalid_objects) == ["wrong-issuer"], "unexpected JWS trust results")
        require(sorted(invalid_messages) == ["bad-content","bad-host","bad-status","wrong-outcome","wrong-recipient"],
                "unexpected HTTP results")
        return {"signedObjects":len(self.objects),"httpMessages":len(self.raw),
                "rejectedObjectLabels":sorted(invalid_objects),"rejectedHttpLabels":sorted(invalid_messages)}

