"""Compare two adjacent teleport receivers with the other channel idle or active."""
import getpass
import logging
import math
import random
import sys
import time
import traceback
from collections import Counter, defaultdict
from pathlib import Path

from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2
from scipy.stats import norm

OUT = Path(__file__).resolve().parent
PRIOR = Path.home() / "Documents/Codex/2026-11-19/tonight-we-will-be-doing-actual/outputs"
sys.path.insert(0, str(PRIOR))
import graph156
from graph156 import save
from run_switch_puzzles import compile_map, execute, load
from teleport_ascii_a import circuit, prepare

MAP = OUT / "Neighbor-fresh-map.json"
SIM = OUT / "Neighbor-simulator.json"
HW = OUT / "Neighbor-Kingston.json"
STATUS = OUT / "Neighbor-status.json"
TAG = "adjacent-receivers-20261120-v1"
CASES = ("0-", "1-", "-0", "-1", "00", "01", "10", "11")
BLOCKS, REPS, SEED = 4, 64, 35621


def fresh_map(service, backend):
    rec = load(MAP)
    native = []
    if not rec:
        geo, native = compile_map(backend)
        ideal = AerSimulator(method="stabilizer").run(
            graph156.circuits(geo), shots=256, seed_simulator=SEED).result().get_counts()
        assert graph156.analyze(geo, ideal)["correct_by_qubit"] == [256]*156
        rec = dict(backend=backend.name, geometry=geo, shots_per_setting=256,
                   ideal_checks_passed=True, coordinates=backend.configuration().coords)
    rec = execute(service, backend, MAP, TAG+"-map", rec, lambda: native)
    rec["analysis"] = graph156.analyze(rec["geometry"], rec["counts"])
    save(MAP, rec)
    return rec


def select(rec, backend):
    hits = rec["analysis"]["correct_by_qubit"]
    neighbors = defaultdict(set)
    err = {}
    for a,b in rec["geometry"]["edges"]:
        gate = backend.target["cz"].get((a,b)) or backend.target["cz"].get((b,a))
        if gate and gate.error is not None and 0 <= gate.error < 1:
            neighbors[a].add(b)
            neighbors[b].add(a)
            err[a,b] = err[b,a] = gate.error
    routes = defaultdict(list)
    for end in neighbors:
        for helper in neighbors[end]:
            for source in neighbors[helper] - {end}:
                path = (source, helper, end)
                cost = -sum(math.log((hits[q]+0.5)/257) for q in path)
                cost -= math.log1p(-err[source,helper]) + math.log1p(-err[helper,end])
                routes[end].append((cost,path))
    candidates = [(ca+cb,pa,pb) for a in neighbors for b in neighbors[a] if a<b
                  for ca,pa in routes[a] for cb,pb in routes[b] if set(pa).isdisjoint(pb)]
    score,a,b = min(candidates)
    return dict(A=a, B=b, map_passes=[[hits[q] for q in p] for p in (a,b)],
                candidate_pairs=len(candidates), score=score,
                criterion="Disjoint triples, adjacent receiver qubits. Minimize summed negative log smoothed map pass fractions and CZ successes.")


def inputs(case):
    return [(i,int(ch)) for i,ch in enumerate(case) if ch!="-"]


def tally(case, counts):
    active = inputs(case)
    correct = Counter()
    for s,n in counts.items():
        assert len(s)==3*len(active)
        bits = int(s,2) >> (2*len(active))
        ok = [((bits>>j)&1)==value for j,(_,value) in enumerate(active)]
        for (route,_),success in zip(active,ok):
            correct["AB"[route]] += n*success
        correct["all"] += n*all(ok)
    return dict(correct)


def simulate(selected, output=SIM):
    circuits = []
    for case in CASES:
        active = inputs(case)
        value = sum(bit<<i for i,(_,bit) in enumerate(active))
        circuits.append(circuit("teleport", value=value, width=len(active)))
    res = AerSimulator(method="stabilizer").run(circuits, shots=256, seed_simulator=SEED).result()
    counts = dict(zip(CASES, res.get_counts(),strict=True))
    assert all(tally(k,v)["all"] == 256 for k,v in counts.items())
    save(output, dict(map_job=load(MAP).get("job_id"),selection=selected,counts=counts,
                   shots_per_case=256,correct={k:tally(k,v) for k,v in counts.items()}))


def compare(service, backend, mapped, *, selection=None, result_path=HW, sim_path=SIM, tag=TAG):
    rec = load(result_path)
    if rec.get("stage")=="done":
        return
    if not rec:
        if selection is None:
            selection = select(mapped, backend)
        simulate(selection, sim_path)
        compiled = {}
        native_counts = {}
        for case in CASES:
            active = inputs(case)
            value = sum(bit<<i for i,(_,bit) in enumerate(active))
            paths = [selection["AB"[idx]] for idx,_ in active]
            _,_,circuits = prepare(backend, paths, ("teleport",), value)
            compiled[case] = circuits[0]
            native_counts[case] = dict(circuits[0].count_ops())
        rec = dict(backend=backend.name, map_job=mapped["job_id"], selection=selection,
                   native_counts=native_counts, tag=tag)
    else:
        compiled = {}
    run_blocks(service,backend,result_path,tag,rec,compiled,CASES,tally,contrasts)


def run_blocks(service,backend,result_path,tag,rec,compiled,cases,score,summarize):
    if rec.get("stage")=="done":
        return
    if not rec.get("stage"):
        rng = random.Random(SEED)
        order = [case for _ in range(BLOCKS) for case in rng.sample(cases,len(cases))]
        rec.update(stage="submitting", order=order, shots_per_block=REPS, shots_per_case=BLOCKS*REPS)
        sampler=SamplerV2(mode=backend,options={"max_execution_time":30,"environment":{"job_tags":[tag]},
                          "twirling":{"enable_measure":False,"enable_gates":False},"dynamical_decoupling":{"enable":False}})
        import json
        with result_path.open("x") as f:
            json.dump(rec,f,indent=2)
        job = sampler.run([compiled[k] for k in order],shots=REPS)
    elif rec.get("job_id"):
        job = service.job(rec["job_id"])
    else:
        found = service.jobs(job_tags=[tag],limit=2)
        if len(found)!=1:
            raise RuntimeError("Reconcile pending submission")
        job = found[0]
    rec.update(stage="submitted",job_id=job.job_id())
    save(result_path, rec)
    pubs = job.result()
    blocks = [pub.data.c.get_counts() for pub in pubs]
    assert len(blocks)==len(cases)*BLOCKS and all(sum(v.values())==REPS for v in blocks)
    counts = {k:Counter() for k in cases}
    for k,v in zip(rec["order"],blocks,strict=True):
        counts[k].update(v)
    assert all(sum(v.values())==256 for v in counts.values())
    rows = {k:score(k,v) for k,v in counts.items()}
    rec.update(counts_by_block=blocks,correct=rows, contrasts=summarize(rows))
    save(result_path, rec)
    for _ in range(24):
        metrics = job.metrics()
        if metrics.get("usage",{}).get("status")=="complete":
            break
        time.sleep(5)
    rec.update(stage="done",metrics=metrics)
    save(result_path, rec)


def contrasts(rows):
    # Balanced mixtures of input bits in both arms. Bonferroni for the two primary route comparisons.
    z = norm.ppf(1-.05/4)
    def wilson(p,n):
        den=1+z*z/n
        mid=(p+z*z/(2*n))/den
        half=z*math.sqrt(p*(1-p)/n+z*z/(4*n*n))/den
        return mid-half,mid+half
    out={}
    for route in "AB":
        solo=sum(v.get(route,0) for k,v in rows.items() if "-" in k)
        both=sum(v[route] for k,v in rows.items() if "-" not in k)
        p,q=both/1024,solo/512
        pl,ph=wilson(p,1024)
        ql,qh=wilson(q,512)
        d=p-q
        out[route]=dict(alone=solo,together=both,difference=d,
                        familywise_95_interval=[d-math.hypot(p-pl,qh-q),d+math.hypot(ph-p,q-ql)])
    return out


def run():
    if load(HW).get("stage")=="done":
        return
    save(STATUS,{"stage":"waiting for key"})
    key=getpass.getpass("IBM Cloud API key for Kingston map and path comparison (hidden): ").strip()
    if not key:
        save(STATUS,{"stage":"cancelled"})
        return
    save(STATUS,{"stage":"mapping"})
    service=QiskitRuntimeService(channel="ibm_quantum_platform",token=key,plans_preference=["open"],region="us-east")
    backend=service.backend("ibm_kingston")
    mapped=fresh_map(service,backend)
    save(STATUS,{"stage":"path selection and comparison"})
    compare(service,backend,mapped)
    save(STATUS,{"stage":"finished"})


if __name__=="__main__":
    logging.disable(logging.CRITICAL)
    try:
        run()
    except Exception as exc:
        save(STATUS,{"stage":"error","type":type(exc).__name__,"frames":[f.name for f in traceback.extract_tb(exc.__traceback__)]})
        raise SystemExit(1)
