"""Run the released Node participant as a process, exchange files, and retain replayable evidence."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import copy
import importlib.metadata
from pathlib import Path
import platform
import shutil
import sqlite3
import subprocess
import sys
import tempfile
from zipfile import ZipFile, ZIP_DEFLATED

from corpus import Corpus, read, save
from wire import Invalid, PROFILE, canonical, digest, require
from w1 import MODULES, build_id, execute_cases, utc

HERE = Path(__file__).resolve().parent


def command(parts):
    return subprocess.run(list(map(str,parts)),capture_output=True,text=True)


def successful(parts):
    result = command(parts)
    if result.returncode:
        raise RuntimeError(f"{Path(str(parts[0])).name} exited {result.returncode}: {result.stderr.strip()}")
    return result.stdout.strip()


def mutate(original, operations):
    changed = copy.deepcopy(original)
    for patch in operations:
        path = [k.replace("~1","/").replace("~0","~") for k in patch["path"].split("/")[1:]]
        parent = changed
        for k in path[:-1]:
            parent = parent[k]
        if patch["op"] == "remove":
            del parent[path[-1]]
        elif patch["op"] == "replace":
            require(path[-1] in parent,"missing comparison control target")
            parent[path[-1]] = patch["value"]
        else:
            raise ValueError("unexpected comparison control")
    return changed


def observer(sql_dir, out, report, py_evidence):
    # A fresh process has exited. Open the actual stores with read-only handles.
    from contextlib import closing
    def sql(path, query):
        with closing(sqlite3.connect(path.resolve().as_uri()+"?mode=ro",uri=True)) as db:
            return [list(r) for r in db.execute(query)]
    checked = {}
    for key in [*report["runs"],"live-race"]:
        directory = sql_dir/key
        provider,authority = directory/"provider.sqlite",directory/"authority.sqlite"
        data = sql(provider,"SELECT op,units FROM terminal WHERE kind='outcome' ORDER BY op")
        count = sql(provider,"SELECT COUNT(*) FROM egress")[0][0]
        rows = sql(provider,"SELECT rowID,op,kind,units,at FROM terminal ORDER BY op")
        debits = sql(authority,"SELECT COALESCE(SUM(units),0) FROM operations WHERE status='settled'")[0][0]
        epoch, fence, revoked = sql(authority,"SELECT epoch,fence,revoked FROM policy")[0]
        expected = py_evidence["liveRace"]["final"] if key == "live-race" else report["runs"][key]["final"]
        require(data == expected["rows"] and count == expected["releasedRecords"] and debits == expected["settled"]
                and epoch == expected["epoch"] and bool(revoked) == expected["revoked"],"read-only observer "+key)
        checked[key] = {"providerEvents":rows,"releasedRecords":count,"settled":debits,"epoch":epoch,"fence":fence,
                        "revoked":bool(revoked)}
    checks = {}
    with ZipFile(out/"sqlite-stores.zip","x",compression=ZIP_DEFLATED) as z:
        for path in sorted(sql_dir.rglob("*.sqlite")):
            require(sql(path,"PRAGMA quick_check") == [["ok"]],"SQLite integrity "+path.name)
            rel = path.relative_to(sql_dir).as_posix()
            checks[rel] = digest(path.read_bytes())
            z.write(path,rel)
    save(out/"observer.json",{"method":"fresh read-only SQLite connections after the consumer exited",
                             "stores":checks,"scenarios":checked})
    return checked


def controls(case11, kit, temporary, comparators):
    examples = case11["examples"]
    original_a = kit/examples["reportAB"]
    original_b = read(kit/examples["reportBA"])
    results = []
    for test in case11["controls"]:
        modified = temporary/(test["variant"]+".json")
        save(modified,mutate(original_b,test["patch"]))
        observed = {}
        for label, compare in comparators.items():
            res = command([*compare,original_a,modified])
            observed[label] = "MATCH" if res.returncode == 0 else "INVALID"
        results.append({"control":test["variant"],"expected":test["expect"],"observed":observed})
    return results


def check_inputs_only(inputs, temporary, peer_bundle, observed):
    # Repeat the consumer without the public answers. The UI must still specify
    # which steps require intermediate readings, so retain those field names.
    blind = Corpus(inputs)
    peer = blind.peer(peer_bundle)
    for obj in blind.fx["objects"].values():
        del obj["compact"]
    for message in blind.fx["messages"].values():
        for name in ("wireB64","baseB64","wireSha256"):
            del message[name]
    del blind.fx["recoveryImage"]
    require(blind.generate() == peer_bundle["packets"], "unsigned-only generation differed")
    for case in blind.cases[:10]:
        for run in case["runs"]:
            del run["final"]
            for step in run["steps"]:
                del step["expect"]
                for marker in ("observe","results"):
                    if marker in step:
                        step[marker] = None
    replayed,_ = execute_cases(peer,temporary/"without-answers")
    require(canonical(replayed) == canonical(observed),"answer-free execution differed")
    return {"withoutGoldenPackets":"same 70 generated packets","withoutExpectedDecisionsStatesOrRecoveryImage":
            "same 19 scenario reports from newly initialized databases"}


def narrative(out, agreement, evidence):
    py = agreement["nodeToPythonRace"]
    node = agreement["pythonToNodeRace"]
    ms = int(evidence["liveRace"]["overlapNs"])/1e6
    stages = agreement["cases"]
    labels = [
        "Matching approval admitted once. Three altered roots denied.",
        "Only the properly restricted child was granted.",
        "Bound request and response accepted. Changed inputs and incorrect associations rejected.",
        "Missing lineage, unknown policy and retired key denied. Provider veto blocked commitment.",
        "One six-credit row, one settlement and four available. The delayed reply passed before its expiry.",
        "Standard and backend export calls both denied. Zero project records released.",
        "Each forced order produced one winner, one six-credit charge and four remaining.",
        "Eligible in-flight permit committed during isolation. Fence, expiry and clock-boundary checks stopped later effects.",
        "Authorized retry found the existing row. Unrelated inquiry denied. Only signed terminal closure released the reservation.",
        "Older primary held. Trusted recovery entered epoch 2 and retained revocation and the six-credit charge.",
    ]
    match_count = sum(v["agree"] for v in stages)
    intro = ("Both consumers agreed with each other and the public outcomes for every measured case."
             if match_count == 11 else f"{match_count} of the 11 measured cases agreed.")
    lines = ["# HTTP6 W1 reciprocal exchange", "", intro, "",
             "Two local processes exchanged newly generated bundles for profile "+PROFILE+". "
             "The Python participant used libsodium for signatures and SQLite transactions for authorization, "
             "resource commitment and recovery. The released Node.js participant used its public command-line interface.",
             "", "| Case | Node as consumer | Python as consumer | Observation |","| --- | --- | --- | --- |"]
    for index,(case,detail) in enumerate(zip(stages[:10],labels),1):
        lines.append(f"| {index:02d}. {case['title']} | {case['node']} | {case['python']} | "+
                     (detail if case["agree"] else "See the recorded mismatches.")+" |")
    last = "The byte catalog, reports, and five comparison controls agreed." if stages[-1]["agree"] else "Review the comparison records."
    lines.append(f"| 11. Reciprocal exchange | {stages[-1]['node']} | {stages[-1]['python']} | {last} Independent administration remains open. |")
    lines += ["", "## What was measured", "",
              f"Each producer generated {agreement['objects']} signed objects and {agreement['messages']} HTTP messages. "
              f"Each consumer processed {agreement['scenarioCount']} reset scenarios with {agreement['decisionCount']} step decisions, "
              f"{agreement['checkpointCount']} intermediate observations, two forced race orders and a final observation for each scenario. "
              "The two comparators also checked the complete actual reports against the published outcomes.",
              "", "In an additional run, the Python producer regenerated the entire catalog after the golden wire and signature bytes were removed. "
              "The consumer reproduced the 19 scenario reports after the expected decisions, balances and published recovery image were removed. "
              "It received the peer's signed messages and the public scenario inputs in that run.",
              "", f"In the overlapping run, Python recorded winner `{py['winner']}` and Node recorded winner `{node['winner']}`. "
              f"Python recorded {py['charges']} charge, {py['settled']} settled and {py['available']} available. "
              f"Node recorded {node['charges']} charge, {node['settled']} settled and {node['available']} available. "
              f"The two Python call intervals overlapped by {ms:.3f} ms at the shared SQLite reservation service. "
              "Those intervals include admission, waiting for the write transaction, and return. Node reports its resulting counters. "
              "The public Node interface supplies no request-interval trace or independently readable durable provider store.",
              "", "The Python observer reopened the provider and authority databases after the consumer exited. "
              "For the denied export it also verified that a synthetic disclosure was visible to the observer before the test, "
              "then reset the sink. The rollback test physically restored only the authority database. "
              "The provider database, keeper journal, and signed checkpoint remained available.",
              "", "## Scope of the result", "",
              "The measured part of case 11 covers the reciprocal exchange and equivalence of observations. "
              "Both participants ran on one host under one operator. This assistant previously worked on the reference kit and wrote "
              "the new participant from the public specification and test data. The new implementation has separate source and "
              "runtime code. Independent team authorship and separately administered deployments remain unverified. "
              "The transport exercise exchanged signed HTTP/1.1 bytes by file. A live TLS session between organizations, "
              "production agent identity and attestation, and cross-host durability remain outside this run.",
              "", "## Evidence", "",
              "- [Case results, comparator controls and packet hashes](agreement.json)",
              "- [Node producer bundle](from-node.json) and [Python producer bundle](from-python.json)",
              "- [Node to Python report](node-to-python.json) and [Python to Node report](python-to-node.json)",
              "- [Python step observations and race intervals](python-evidence.json)",
              "- [Read-only observer results and database hashes](observer.json) and [SQLite snapshots](sqlite-stores.zip)",
              "- [Build identities, execution environment and checksums](provenance.json)", "",
              "Reproduce the experiment with the commands in the [implementation guide](../README.md).", ""]
    (out/"REPORT.md").write_text("\n".join(lines),encoding="ascii")


def exchange(kit, out):
    kit, out = kit.resolve(), out.resolve()
    out.mkdir(parents=True,exist_ok=False)
    started = utc()
    names = sorted(("check.mjs","model.mjs","wire.mjs"))
    ref_hashes = {n:digest((kit/n).read_bytes()) for n in names}
    listing = "".join(n+" "+ref_hashes[n]+"\n" for n in names)
    ref_id = "sha256-"+digest(listing.encode("ascii"))
    ref = ["node",str(kit/"check.mjs")]
    with tempfile.TemporaryDirectory() as tmp:
        tmp = Path(tmp)
        inputs = tmp/"inputs"; (inputs/"cases").mkdir(parents=True)
        for name in ("manifest.json","fixtures.json","schema.json",*(f"cases/{i:02d}.json" for i in range(1,12))):
            shutil.copyfile(kit/name,inputs/name)
        suite = Corpus(inputs)
        py = [sys.executable,"-B",str(HERE/"w1.py"),"--vectors",str(inputs)]
        tasks = [(ref+["emit","node-w1",ref_id,out/"from-node.json"]),
                 (py+["emit",out/"from-python.json"])]
        with ThreadPoolExecutor(2) as pool:
            list(pool.map(successful,tasks))
        sql_dir = tmp/"state"
        tasks = [ref+["consume","node-w1",ref_id,out/"from-python.json",out/"python-to-node.json"],
                 py+["consume",out/"from-node.json",out/"node-to-python.json",out/"python-evidence.json",sql_dir]]
        with ThreadPoolExecutor(2) as pool:
            list(pool.map(successful,tasks))
        files = [out/"node-to-python.json",out/"python-to-node.json"]
        a,b = map(read,files)
        evidence = read(out/"python-evidence.json")
        observer(sql_dir,out,a,evidence)
        public_input_checks = check_inputs_only(inputs,tmp,read(out/"from-node.json"),a["runs"])
        compares = {"node":ref+["compare"],"python":py+["compare"]}
        comparator_evidence = {}
        for name, program in compares.items():
            result = command([*program,*files])
            comparator_evidence[name] = {"result":"MATCH" if result.returncode == 0 else "INVALID",
                                         "exitCode":result.returncode,"output":(result.stdout+result.stderr).strip()}
        control_results = controls(suite.cases[-1],kit,tmp,compares)
        expected = suite.expected_runs()
        stages = []
        for case in suite.cases[:10]:
            keys = [k for k in expected if k.startswith(f"{case['case']:02d}/")]
            def mismatches(r):
                return [k for k in keys if k not in r["runs"] or canonical(r["runs"][k]) != canonical(expected[k])]
            py_bad, node_bad = mismatches(a), mismatches(b)
            agree = not py_bad and not node_bad
            stages.append({"case":case["case"],"title":case["title"],"agree":agree,
                           "node":"PASS" if not node_bad else "FAIL","python":"PASS" if not py_bad else "FAIL",
                           "mismatchingNodeRuns":node_bad,"mismatchingPythonRuns":py_bad,"runs":keys})
        all_packets = read(out/"from-node.json")["packets"] == read(out/"from-python.json")["packets"]
        checks = {participant: (all_packets and comparator_evidence[participant]["result"] == "MATCH" and
                                all(t["expected"] == t["observed"][participant] for t in control_results))
                  for participant in compares}
        stages.append({"case":11,"title":"Reciprocal interchange","agree":all(checks.values()),
                       **{k:"PASS" if value else "FAIL" for k,value in checks.items()},
                       "qualification":"one operator and one host; independent administration unverified"})
        agreement = {"profile":PROFILE,"suiteHash":suite.suite_hash,"cases":stages,"comparators":comparator_evidence,
                     "publicInputChecks":public_input_checks,
                     "case11Controls":control_results,"allPeerPacketsByteIdentical":all_packets,"packetHashes":a["packetHashes"],
                     "objects":len(suite.fx["objects"]),"messages":len(suite.fx["messages"]),"scenarioCount":len(expected),
                     "decisionCount":sum(len(r["decisions"]) for r in expected.values()),
                     "checkpointCount":sum(len(r["checkpoints"]) for r in expected.values()),
                     "nodeToPythonRace":a["liveRace"],"pythonToNodeRace":b["liveRace"]}
        save(out/"agreement.json",agreement)
        versions = read_versions(ref)
        provenance = {"profile":PROFILE,"startedUtc":started,"finishedUtc":utc(),"suiteHash":suite.suite_hash,
                      "node":{"identity":b["consumer"],"sourceSha256":ref_hashes,"runtime":versions},
                      "python":{"identity":build_id(),"sourceSha256":{n:digest((HERE/n).read_bytes()) for n in MODULES},
                                "runtime":platform.python_version(),"sqlite":sqlite3.sqlite_version,
                                "libsodium":suite.binding.crypto.lib.sodium_version_string().decode("ascii"),
                                "jsonschema":importlib.metadata.version("jsonschema")},
                      "coordinatorSha256":digest(Path(__file__).read_bytes()),"platform":platform.system()+" "+platform.machine(),
                      "hostCount":1,"operatorCount":1,"transport":"file interchange of HTTP/1.1 wire bytes",
                      "buildHashRecipe":"SHA-256 of sorted ASCII filename, one space, lowercase hex file SHA-256, LF",
                      "inputsAvailableToPython":sorted(str(p.relative_to(inputs)) for p in inputs.rglob("*") if p.is_file())}
        narrative(out,agreement,evidence)
        provenance["outputSha256"] = {p.name:digest(p.read_bytes()) for p in sorted(out.iterdir()) if p.is_file()}
        save(out/"provenance.json",provenance)
        return all(case["agree"] for case in stages)


def read_versions(ref):
    return successful([ref[0],"--version"])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--vectors",required=True,type=Path)
    parser.add_argument("--out",required=True,type=Path)
    args = parser.parse_args()
    try:
        passed = exchange(args.vectors,args.out)
    except (RuntimeError, Invalid, OSError) as error:
        sys.exit(str(error))
    print("MATCH" if passed else "MISMATCH",args.out/"REPORT.md")
    sys.exit(0 if passed else 1)

