"""Render the new Kingston graph-state map and the selected routes."""
import json
from pathlib import Path

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

root=Path(__file__).resolve().parent
rec=json.loads((root/"Neighbor-fresh-map.json").read_bytes())
paths=json.loads((root/"Neighbor-simulator.json").read_bytes())["selection"]
xy=np.array(rec["coordinates"])
vals=np.array(rec["analysis"]["correct_by_qubit"])*100/256
edges=rec["geometry"]["edges"]
assert xy.shape==(156,2)
fig,(ax,zoom)=plt.subplots(1,2,figsize=(13.2,7.7),width_ratios=[2.15,1],layout="constrained")
def base(a):
    a.add_collection(LineCollection([xy[[i,j]] for i,j in edges],color="#bdc8cc",linewidth=.95,zorder=1))
    a.set_aspect("equal")
    a.axis("off")
base(ax)
colors={"A":"#9A3670","B":"#154D91"}
norm=Normalize(np.floor(min(95,vals.min())/5)*5,100)
sc=ax.scatter(*xy.T,c=vals,s=86,norm=norm,cmap="viridis",zorder=2)
for name,k in colors.items():
    arr=xy[paths[name]]
    ax.plot(*arr.T,color=k,linewidth=3,zorder=3)
    ax.scatter(*arr.T,s=124,facecolors="none",edgecolors=k,linewidths=1.9,zorder=4)
ax.set(xlim=(xy[:,0].min()-.6,xy[:,0].max()+.6),ylim=(xy[:,1].max()+.6,xy[:,1].min()-.6))
cb=fig.colorbar(sc,ax=ax,orientation="horizontal",shrink=.73,pad=.02)
cb.set_label("Neighbor predictions correct (%)")
ax.set_title("All 156 qubits",loc="left",fontweight="bold")
ids=paths["A"]+paths["B"]
box=xy[ids]
base(zoom)
line=xy[[paths["A"][-1],paths["B"][-1]]]
zoom.plot(*line.T,color="#38444b",linestyle="--",linewidth=2.5,zorder=2)
for name,k in colors.items():
    arr=xy[paths[name]]
    zoom.plot(*arr.T,color=k,linewidth=4,zorder=3)
    zoom.scatter(*arr.T,color=k,s=640,zorder=4)
    for i,(x,y) in zip(paths[name],arr):
        zoom.text(x,y,str(i),color="white",ha="center",va="center",fontsize=9,zorder=5)
zoom.set(xlim=(box[:,0].min()-.65,box[:,0].max()+.65),ylim=(box[:,1].max()+.65,box[:,1].min()-.65))
zoom.set_title("Two disjoint teleport routes",fontweight="bold")
for i,(name,k) in enumerate(colors.items()):
    zoom.text(.5,-.06-i*.08,f"{name}     "+" → ".join(map(str,paths[name])),ha="center",transform=zoom.transAxes,color=k,fontweight="bold")
fig.suptitle("Kingston  |  Fresh graph-state map",fontsize=18,fontweight="bold")
fig.savefig(root/"Neighbor-Kingston-map.png",dpi=160)
