"""Verify the graph-state counts and draw them on the IBM chip coordinates."""
import csv
import json
import math
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import Normalize
from matplotlib.patches import Circle
import numpy as np

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


def main():
    record=json.loads((ROOT/"Graph156-hardware.json").read_text())
    nshots=record["shots_per_setting"]
    edges=record["geometry"]["edges"]
    colors=record["geometry"]["colors"]
    coords=record["coordinates"]
    if not coords:
        saved=json.loads((ROOT/"IBM-diagnostics-20261119T232201Z.json").read_text())
        config=next(p["configuration"] for p in saved["processors"] if p["name"]==record["backend"])
        coords=config["coords"]
    assert len(set(map(tuple,coords)))==156 and len(colors)==156
    neighbors=[[] for _ in colors]
    for a,b in edges:
        neighbors[a].append(b)
        neighbors[b].append(a)
    # Independent readout decoding directly from the printed binary strings.
    score=np.zeros(156,dtype=int)
    perfect=[]
    for setting,counts in enumerate(record["counts"]):
        ids=np.flatnonzero(np.array(colors)==setting)
        bits=np.array([[int(digit) for digit in s[::-1]] for s in counts],dtype=np.uint8)
        weights=np.array(list(counts.values()))
        assert weights.sum()==nshots
        ok=np.column_stack([bits[:,i]==np.bitwise_xor.reduce(bits[:,neighbors[i]],axis=1) for i in ids])
        score[ids]=weights@ok
        perfect.append(int(weights@ok.all(axis=1)))
    assert score.tolist()==record["analysis"]["correct_by_qubit"]
    assert perfect==record["analysis"]["all_correct_by_setting"]
    pct=score*100/nshots
    with (ROOT/"Graph156-per-qubit.csv").open("w",newline="",encoding="utf8") as f:
        writer=csv.writer(f)
        writer.writerow(["qubit","x_basis_setting","neighbors","correct","shots","percent_correct"])
        for i in range(156):
            writer.writerow([i,colors[i]," ".join(map(str,sorted(neighbors[i]))),score[i],nshots,pct[i]])
    coords=np.asarray(coords)
    lo=5*math.floor(pct.min()/5)
    norm=Normalize(min(95,lo),100)
    cmap=plt.get_cmap("viridis")
    fig,ax=plt.subplots(figsize=(13.8,12.7))
    fig.subplots_adjust(left=.035,right=.965,top=.915,bottom=.105)
    ax.add_collection(LineCollection([coords[[a,b]] for a,b in edges],linewidths=2.1,
                                     colors="#88949a",zorder=1))
    for i,((x,y),v) in enumerate(zip(coords,pct)):
        col=cmap(norm(v))
        linear=np.where(np.array(col[:3])<=.04045,np.array(col[:3])/12.92,((np.array(col[:3])+.055)/1.055)**2.4)
        ink="#ffffff" if linear@[.2126,.7152,.0722]<.179 else "#111315"
        ax.add_patch(Circle((x,y),.445,facecolor=col,edgecolor="#4a555b",linewidth=.6,zorder=2))
        ax.text(x,y-.095,f"Q{i}",color=ink,fontsize=8.5,fontweight="bold",ha="center",va="center")
        ax.text(x,y+.135,f"{v:.1f}%",color=ink,fontsize=7.8,ha="center",va="center")
    ax.set(xlim=(coords[:,0].min()-.52,coords[:,0].max()+.52),
           ylim=(coords[:,1].max()+.52,coords[:,1].min()-.52),aspect="equal")
    ax.axis("off")
    fig.suptitle("How often did the neighbors predict each qubit?",fontsize=22,y=.985)
    fig.text(.5,.943,f"{record['backend']}   ·   156-qubit graph state   ·   {nshots} predictions per qubit",
             ha="center",fontsize=13,color="#374951")
    cbax=fig.add_axes([.28,.066,.44,.014])
    bar=fig.colorbar(plt.cm.ScalarMappable(norm=norm,cmap=cmap),cax=cbax,orientation="horizontal")
    bar.set_label("Correct predictions (%)",fontsize=11)
    fig.savefig(ROOT/"Graph156-prediction-map.png",dpi=175,bbox_inches="tight",pad_inches=.24)
    plt.close(fig)
    print(record["backend"], record["job_id"], record["metrics"]["usage"])
    print("queues",{k:v["pending_jobs"] for k,v in record["queues"].items()})
    print("successes / total",score.sum(),nshots*156,"mean",pct.mean(),"median",np.median(pct),
          "all passed",perfect,"color sizes",np.bincount(colors))
    print("lowest",[(int(i),int(score[i])) for i in np.argsort(score)[:8]],
          "highest",[(int(i),int(score[i])) for i in np.where(score==score.max())[0]])


if __name__=="__main__":
    main()
