"""Rule 90 on a physical chain, starting from a single central live cell."""
import getpass
import json
import logging
import math
import sys
import time
import traceback
from datetime import datetime, timezone
from pathlib import Path

from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit_ibm_runtime import QiskitRuntimeService, SamplerV2

ROOT = Path(__file__).resolve().parent
N, LAST, SHOTS, SEED = 19, 8, 256, 1936
MID = N//2
SIM, HW = ROOT/"Rule90-simulator.json", ROOT/"Rule90-hardware.json"
TAG = "rule90-one-seed-19cells-20261119"


def save(path, data):
    tmp = path.with_suffix(".tmp")
    tmp.write_text(json.dumps(data,indent=2),encoding="utf8")
    tmp.replace(path)


def circuits():
    result = []
    for generation in range(LAST+1):
        qc = QuantumCircuit(N,N,name=f"rule90_g{generation}")
        qc.x(MID)
        for step in range(generation):
            # Only one parity can be live with this seed. The other parity is
            # the zero-initialized destination. Missing neighbors contribute zero.
            sources = range((MID+step)%2, N, 2)
            for offset in (-1,1):
                for i in sources:
                    if 0<=i+offset<N:
                        qc.cx(i,i+offset)
            qc.reset(list(sources))
            qc.barrier()
        qc.measure(range(N),range(N))
        result.append(qc)
    return result


def expected(g):
    # Closed form from Pascal's triangle mod 2, independent of the gate circuit.
    value = [0]*N
    for k in range(g+1):
        value[MID-g+2*k] = math.comb(g,k)%2
    return value


def analyze(counts):
    assert len(counts)==LAST+1
    results = []
    for generation, row in enumerate(counts):
        assert sum(row.values())==SHOTS
        ideal = expected(generation)
        hits = [0]*N
        for bits,n in row.items():
            assert len(bits)==N and set(bits)<={"0","1"}
            for i,v in enumerate(reversed(bits)):
                if v=="1":
                    hits[i] += n
        key = "".join(str(x) for x in reversed(ideal))
        results.append({"generation":generation,"expected":ideal,"live_counts":hits,
                        "exact_row_shots":row.get(key,0),
                        "majority_matches":all((2*n-SHOTS)*(2*v-1)>0 for n,v in zip(hits,ideal))})
    return results


def simulate():
    sim = AerSimulator(method="stabilizer")
    counts = sim.run(circuits(),shots=SHOTS,seed_simulator=SEED).result().get_counts()
    rows = analyze(counts)
    assert all(r["exact_row_shots"]==SHOTS for r in rows)
    save(SIM,{"engine":"Qiskit Aer ideal stabilizer","shots_per_generation":SHOTS,
              "boundaries":"fixed zero outside the chain","counts":counts,"rows":rows})
    print("Verified all nine generations against Pascal's triangle mod 2.")


def choose_chain(backend):
    p = backend.properties(refresh=True)
    bad = set(p.faulty_qubits())
    bad_edges = {tuple(sorted(g.qubits)) for g in p.faulty_gates() if len(g.qubits)==2}
    edges = {tuple(sorted(e)) for e in backend.coupling_map.get_edges()}
    readout = {i:p.readout_error(i) for i in range(backend.num_qubits) if i not in bad}
    neighbors = {i:[] for i in readout}
    for a,b in sorted(edges-bad_edges):
        if a in bad or b in bad:
            continue
        props = backend.target["cz"].get((a,b)) or backend.target["cz"].get((b,a))
        if props is not None and props.error is not None:
            neighbors[a].append((b,props.error))
            neighbors[b].append((a,props.error))
    # Weight each link for eight uses in the longest circuit, and each readout once.
    best_cost, best = math.inf, None
    def extend(path, cost):
        nonlocal best, best_cost
        if cost>=best_cost:
            return
        if len(path)==N:
            best_cost,best = cost,path.copy()
            return
        for q,err in neighbors[path[-1]]:
            if q not in path:
                extend(path+[q], cost+LAST*err+readout[q])
    for q in sorted(readout,key=readout.get):
        extend([q],readout[q])
    if best is None:
        raise ValueError("No healthy 19-site path")
    return best,best_cost


def prepare(backend):
    path,cost=choose_chain(backend)
    isa=transpile(circuits(),backend,initial_layout=path,optimization_level=1,
                  routing_method="none",seed_transpiler=SEED,num_processes=1)
    path_edges={tuple(sorted(e)) for e in zip(path,path[1:])}
    for g,qc in enumerate(isa):
        backend.check_faulty(qc)
        edges=[tuple(sorted(qc.find_bit(q).index for q in op.qubits)) for op in qc.data
               if len(op.qubits)==2 and op.operation.name!="barrier"]
        measured={qc.find_bit(op.clbits[0]).index:qc.find_bit(op.qubits[0]).index
                  for op in qc.data if op.operation.name=="measure"}
        assert set(edges)<=path_edges and measured==dict(enumerate(path))
    return path,cost,isa


def hardware():
    if not SIM.exists() or not sys.stdin.isatty():
        raise RuntimeError("Run the simulator and open a private console")
    rec=json.loads(HW.read_text()) if HW.exists() else {}
    if rec.get("stage") in ("done","terminal_error"):
        return
    key=getpass.getpass("IBM Cloud API key (hidden): ").strip()
    if not key:
        return
    service=QiskitRuntimeService(channel="ibm_quantum_platform",token=key,plans_preference=["open"],region="us-east")
    if "job_id" in rec:
        job=service.job(rec["job_id"])
    elif rec.get("stage")=="submitting":
        jobs=service.jobs(job_tags=[TAG],limit=2)
        if len(jobs)!=1:
            raise RuntimeError("Reconcile the previous submission")
        job=jobs[0]
    else:
        devices={b.name:b for b in service.backends(simulator=False,min_num_qubits=N) if not b.is_mock}
        compiled={}
        while True:
            queues={k:b.status().to_dict() for k,b in devices.items()}
            active=[k for k,s in queues.items() if s["operational"] and s["status_msg"].lower()=="active"]
            name=min(active,key=lambda k:(queues[k]["pending_jobs"],k))
            if name in compiled:
                break
            compiled[name]=prepare(devices[name])
        path,cost,isa=compiled[name]
        rec={"stage":"submitting","backend":name,"queues":queues,"queue_snapshot_utc":datetime.now(timezone.utc).isoformat(),
             "chain":path,"chain_calibration_score":cost,"generations":list(range(LAST+1)),"shots_per_generation":SHOTS,
             "tag":TAG,"native_counts":[dict(q.count_ops()) for q in isa]}
        sampler=SamplerV2(mode=devices[name],options={"max_execution_time":30,"environment":{"job_tags":[TAG]},
                          "twirling":{"enable_measure":False,"enable_gates":False},"dynamical_decoupling":{"enable":False}})
        with HW.open("x",encoding="utf8") as f:
            json.dump(rec,f,indent=2)
        job=sampler.run(isa,shots=SHOTS)
    rec.update(stage="submitted",job_id=job.job_id())
    save(HW,rec)
    while True:
        status=str(job.status())
        if status!=rec.get("ibm_status"):
            rec["ibm_status"]=status
            save(HW,rec)
        if status in ("DONE","CANCELLED","ERROR"):
            break
        time.sleep(5)
    if status=="DONE":
        counts=[pub.data.c.get_counts() for pub in job.result()]
        rec.update(stage="measured",counts=counts,rows=analyze(counts))
        save(HW,rec)
    else:
        rec["ibm_error"]=str(job.error_message())[:1400]
    for _ in range(120):
        metrics=job.metrics()
        if metrics.get("usage",{}).get("status")=="complete":
            break
        time.sleep(5)
    rec.update(stage="done" if status=="DONE" else "terminal_error",metrics=metrics)
    save(HW,rec)


if __name__=="__main__":
    if sys.argv[1:]==["simulate"]:
        simulate()
    elif sys.argv[1:]==["hardware"]:
        logging.disable(logging.CRITICAL)
        try:
            hardware()
        except Exception as exc:
            frames=[[Path(f.filename).name,f.lineno,f.name] for f in traceback.extract_tb(exc.__traceback__)]
            save(ROOT.parent/"work"/"rule90-error.json",{"type":type(exc).__name__,"frames":frames})
            print(type(exc).__name__)
        input("Press Enter to close.")
