"""Run both existing W1 participants across hostname-verified loopback TLS 1.3."""
from contextlib import closing
from datetime import datetime, timezone
from pathlib import Path
import argparse
import hashlib
import json
import os
import selectors
import shutil
import sqlite3
import subprocess
import sys
import tempfile

HERE = Path(__file__).resolve().parent
read = lambda path: json.loads(path.read_bytes())
sha = lambda data: hashlib.sha256(data).hexdigest()


def check(ok, description):
    if not ok:
        raise RuntimeError(description)


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


def run(args):
    p = subprocess.run([str(a) for a in args],capture_output=True,text=True,timeout=120)
    if p.returncode:
        raise RuntimeError(f"{Path(str(args[0])).name}: {(p.stderr or p.stdout).strip()}")
    return p.stdout.strip()


def certs(work, role):
    openssl = shutil.which("openssl")
    ca_key, ca, key, csr, leaf, extensions = (work/(role+x) for x in ("-ca.key","-ca.pem",".key",".csr",".pem",".ext"))
    run([openssl,"req","-x509","-newkey","ec","-pkeyopt","ec_paramgen_curve:P-256","-noenc","-days","2",
         "-subj","/CN=W1 local "+role+" root","-addext","basicConstraints=critical,CA:TRUE",
         "-addext","keyUsage=critical,keyCertSign,cRLSign","-keyout",ca_key,"-out",ca])
    run([openssl,"req","-new","-newkey","ec","-pkeyopt","ec_paramgen_curve:P-256","-noenc",
         "-subj","/CN=compute.example","-keyout",key,"-out",csr])
    extensions.write_text("basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\n"
                          "extendedKeyUsage=serverAuth,clientAuth\nsubjectAltName=DNS:compute.example\n")
    run([openssl,"x509","-req","-in",csr,"-CA",ca,"-CAkey",ca_key,"-CAcreateserial","-days","1",
         "-extfile",extensions,"-out",leaf])
    run([openssl,"verify","-CAfile",ca,"-verify_hostname","compute.example",leaf])
    der = subprocess.check_output([openssl,"x509","-in",leaf,"-outform","DER"])
    return sha(der)


def direction(server, client, work, project):
    def args(role,mode):
        command = [sys.executable,"-B",str(HERE/"python_peer.py")] if role=="python" else ["node",str(HERE/"node_peer.mjs")]
        return command+[mode,str(project),str(work)]
    with (work/(server+"-stderr")).open("w+") as errors:
        proc = subprocess.Popen(args(server,"server"),stdout=subprocess.PIPE,stderr=errors,text=True)
        try:
            with selectors.DefaultSelector() as select:
                select.register(proc.stdout,selectors.EVENT_READ)
                check(select.select(45),"TLS peer did not report its listening port")
                port = proc.stdout.readline().strip()
            if not port.isdigit():
                errors.seek(0); raise RuntimeError("TLS listener failed: "+errors.read()[-1800:])
            try:
                run(args(client,"client")+[port])
            except RuntimeError as exc:
                errors.seek(0); raise RuntimeError(str(exc)+" / peer: "+errors.read()[-1800:]) from exc
            check(proc.wait(timeout=60)==0,"TLS peer failed")
        finally:
            if proc.poll() is None:
                proc.terminate()
                try: proc.wait(timeout=5)
                except subprocess.TimeoutExpired: proc.kill(); proc.wait()


def control_results(kit, work, comparators):
    controls = read(kit/"cases/11.json")
    a = kit/controls["examples"]["reportAB"]
    b = kit/controls["examples"]["reportBA"]
    outcomes = []
    for item in controls["controls"]:
        obj = read(b)
        for mutation in item["patch"]:
            parts = [s.replace("~1","/").replace("~0","~") for s in mutation["path"][1:].split("/")]
            parent = obj
            for p in parts[:-1]:
                parent = parent[p]
            if mutation["op"] == "replace": parent[parts[-1]] = mutation["value"]
            elif mutation["op"] == "remove": del parent[parts[-1]]
            else: raise ValueError("unrecognized comparator control")
        modified = work/("control-"+item["variant"]+".json")
        save(modified,obj)
        actual = {}
        for k,p in comparators.items():
            result = subprocess.run([*p,str(a),str(modified)],capture_output=True,timeout=45)
            actual[k] = "MATCH" if result.returncode==0 else "INVALID"
            check(actual[k]==item["expect"],"comparison control "+item["variant"])
        outcomes.append({"name":item["variant"],"expected":item["expect"],"observed":actual})
    return outcomes


def trial(project, output):
    project, output = project.resolve(), output.resolve()
    kit = project/"w1-public-vectors-00"
    probes = read(HERE/"probes.json")
    with tempfile.TemporaryDirectory(prefix="http6-tls-") as tmp:
        work=Path(tmp)
        peers={r:certs(work,r) for r in ("node","python")}
        check(peers["node"]!=peers["python"],"peer certificates must differ")
        started=datetime.now(timezone.utc).isoformat()
        for server,client in (("python","node"),("node","python")):
            direction(server,client,work,project)
        compares={"node":["node",str(kit/"check.mjs"),"compare"],
                  "python":[sys.executable,"-B",str(project/"w1-sqlite-00"/"w1.py"),"--vectors",str(kit),"compare"]}
        reports=[work/"node-to-python.json",work/"python-to-node.json"]
        outcomes={k:run([*cmd,*reports]) for k,cmd in compares.items()}
        check(all(line.startswith("MATCH") for line in outcomes.values()),"reciprocal comparison failed")
        controls=control_results(kit,work,compares)
        a,b=map(read,reports)
        check(a["producer"]==b["consumer"] and b["producer"]==a["consumer"] and
              a["runs"]==b["runs"] and a["packetHashes"]==b["packetHashes"],"peer report identity or results")
        cases = []
        for i in range(1,12):
            spec = read(kit/"cases"/f"{i:02d}.json")
            cases.append({"case":i,"name":spec["title"],"localCatalogComparison":"MATCH","separateAdminWasmer":"NOT RUN"})
        state={}
        connections={}
        for server,client in (("node","python"),("python","node")):
            sent=read(work/(client+"-client.json"))
            service=read(work/(server+"-server.json"))
            got=service["connections"]
            check(len(sent)==len(got)==len(probes)+1,"incomplete session set")
            for n,(left,right) in enumerate(zip(sent,got)):
                for key in ("requestSHA256","responseSHA256"):
                    check(left[key]==right[key],"transport bytes differed")
                for observation,peer in ((left,server),(right,client)):
                    t=observation["tls"]
                    check(t["version"]=="TLSv1.3" and t["alpn"]=="http/1.1" and
                          t["peerCertificateSHA256"]==peers[peer],"TLS certificate, version or ALPN")
                if n:
                    check(left["result"]==right["result"]==probes[n-1][3],"signed native decision differed")
            state[server]=service["final"]
            check(state[server]["rows"]==[["op-41",6]] and state[server]["available"]==4 and
                  state[server]["settlements"]==1 and state[server]["releasedRecords"]==0,"resource final state")
            connections[client+"-to-"+server]={"client":sent,"server":got}
        with closing(sqlite3.connect((work/"py-native-state"/"provider.sqlite").as_uri()+"?mode=ro",uri=True)) as db:
            observer=db.execute("SELECT rowID,op,units FROM terminal WHERE kind='outcome' ORDER BY op").fetchall()
            released=db.execute("SELECT COUNT(*) FROM egress").fetchone()[0]
        check(observer==[("row-op-41","op-41",6)] and released==0,"read-only SQLite observation")
        output.mkdir(parents=True,exist_ok=False)
        for report in reports:
            shutil.copyfile(report,output/report.name)
        proof={"scope":"single-host loopback; one administrator; zero Wasmer W1 connections",
               "utcStart":started,"utcEnd":datetime.now(timezone.utc).isoformat(),"applicationClock":"published W1 fixture time",
               "tlsClock":"system wall time","mutualTLS":True,"httpOrigin":"https://compute.example",
               "publicLeafSHA256":peers,"cases":cases,"comparators":outcomes,"controls":controls,
               "catalog":{"suiteHash":a["suiteHash"],"packetHashes":a["packetHashes"],"runs":len(a["runs"]),
                          "decisions":sum(len(x["decisions"]) for x in a["runs"].values()),
                          "nodeReceiverRace":b["liveRace"],"pythonReceiverRace":a["liveRace"]},
               "nativeTransactionsPerDirection":len(probes),"nativeProviderStates":state,
               "separatelyReadPythonRows":observer,"pythonReleasedRecords":released,"connections":connections}
        save(output/"preflight.json",proof)
        print("TLS 1.3 local preflight matched in both directions. Evidence:",output)


if __name__=="__main__":
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--project",type=Path,required=True)
    parser.add_argument("--out",type=Path,required=True)
    args=parser.parse_args()
    try: trial(args.project,args.out)
    except (RuntimeError,OSError,ValueError,subprocess.SubprocessError) as error: sys.exit(str(error))

