"""Supplementary figures on numerical convergence, agent activity and method provenance."""
from datetime import date
import json
import numpy as np
from matplotlib.text import Text
from matplotlib.colors import BoundaryNorm, ListedColormap
from plate import Plate, INK, MUTED, ROOT
from make_figures import getdata, rows, result, series, ACC, MARK, NAMES

def save_si(plate, filename):
    """A 7 pt source label prints at 6.5 pt in the 168 mm SI text block."""
    for label in plate.f.findobj(Text):
        if label.get_fontsize() < 7:
            label.set_fontsize(7)
    plate.save(filename)


def sampling():
    p=Plate(81)
    p.panel(1,3,'a','Phonon sampling in the parent')
    p.panel(62,3,'b','Doubling the parent force cell')
    p.panel(124,3,'c','Sampling at linewidth 5 cm⁻¹')
    gamma = {float(r['sigma_cm1']): float(r['T1_us']) for r in series('SEED', 'gamma')}
    primitive = {float(r['sigma_cm1']): float(r['T1_us']) for r in series('SEED', 'dense')}
    supercell = {float(r['sigma_cm1']): float(r['T1_us']) for r in getdata('seed_sampling_convergence')
                 if r['run_label'] == 'dft2x1x1_dense_2x2x2'}
    ax=p.axes(13,17,40,42)
    for line,marker,color,fill,ls,label,size in [(gamma,'o','#77726c','white','--','Centre only',4.7),
                                                  (primitive,'s','#5363a7','#5363a7','-','2 × 2 × 2 grid',2.7)]:
        x=sorted(line)
        ax.plot(x,[line[v] for v in x],color=color,marker=marker,mfc=fill,ms=size,lw=.9,ls=ls,label=label)
    ax.set(xlim=(1,31),ylim=(1.56,2.80),xticks=[2,10,20,30],yticks=[1.6,2,2.4,2.8],ylabel='Spin lifetime (µs)',xlabel='Linewidth (cm⁻¹)')
    ax.legend(loc='center',bbox_to_anchor=(.49,-.39),ncol=2,handlelength=1.4,handletextpad=.4,columnspacing=.8)
    ax=p.axes(75,17,37,42)
    x=np.array(sorted(primitive.keys() & supercell.keys()))
    delta=np.array([100*(supercell[v]/primitive[v]-1) for v in x])
    ax.axhline(0,c='#a4abad',lw=.65)
    ax.vlines(x,0,delta,colors='#9daeb5',lw=1)
    ax.scatter(x,delta,s=21,color='#5363a7',zorder=3)
    ax.set(xlim=(1,31),ylim=(-.43,.43),xticks=[2,10,20,30],yticks=[-.4,0,.4],
           xlabel='Linewidth (cm⁻¹)',ylabel='Change in $T_1$ (%)')
    ax=p.axes(136,17,22,42)
    for k in ['R5_pI','R3_F','R2_NEt4']:
        vals=[result(k,5,sampling=s) for s in ['gamma','dense']]
        ax.plot([0,1],vals,marker=MARK.get(k,'o'),lw=1.05,ms=3.5,c=ACC.get(k,'#aa7546'))
        label=NAMES[k]+f'  {vals[1]:.2f}'
        ax.annotate(label,(1,vals[1]),xytext=(3,0),textcoords='offset points',va='center',fontsize=6)
        if k=='R2_NEt4':
            ax.annotate(f'{vals[0]:.2f}',(0,vals[0]),xytext=(2,4),textcoords='offset points',va='bottom',fontsize=6)
    ax.axhline(1,c='#869396',ls=(0,(2,2)),lw=.65)
    ax.set(xticks=[0,1],xticklabels=['Centre only','Matched grid'],xlim=(-.08,1.08),ylim=(.89,1.52),yticks=[1,1.2,1.4],ylabel='$T_1$ / parent $T_1$')
    save_si(p,'S7_sampling')

def communication():
    p=Plate(81)
    p.panel(1,3,'a','Logged specialist invocations per day')
    p.panel(120,3,'b','Tool calls across the network')
    start,end=date(2026,10,16),date(2026,11,19)
    names={'periodic_dft_expert':'Periodic DFT','computational_chemist':'Quantum chemistry',
        'geometry_generation':'Geometry','quantum_physics':'Cuántico','undermind_deep_research_expert':'Literature',
        'reaction_template_expert':'Reaction templates','hypothesis_generation_expert':'Hypotheses'}
    total={r['callee']:int(r['invocations']) for r in getdata('agent_communication/delegation_edges') if r['caller']=='molecular_discovery'}
    count=np.zeros((len(names),(end-start).days+1),int)
    for r in getdata('agent_communication/delegations_by_day'):
        if r['caller']=='molecular_discovery':
            count[list(names).index(r['callee']),(date.fromisoformat(r['date'])-start).days]+=int(r['invocations'])
    assert np.array_equal(count.sum(1),[total[k] for k in names])
    colors=['#f3f4f9','#d9ddee','#b4beda','#8391bb','#586ba0','#354473']
    bounds=[0,1,3,6,11,26,max(27,count.max()+1)]
    ax=p.axes(26,14,75,48)
    ax.pcolormesh(np.arange(count.shape[1]+1)-.5,np.arange(8)-.5,count,cmap=ListedColormap(colors),norm=BoundaryNorm(bounds,6),shading='flat')
    ax.set(xlim=(-.5,count.shape[1]-.5),ylim=(6.5,-.5))
    ax.set(yticks=range(len(names)),yticklabels=names.values(),xticks=[0,7,16,23,34],
           xticklabels=['16 Oct','23','1 Nov','8','19'])
    ax.tick_params(axis='y',length=0,pad=3)
    for spine in ax.spines.values():spine.set_visible(False)
    for j in range(1,7):ax.axhline(j-.5,c='white',lw=1.5)
    p.text(107,9,'Total',ha='right',fontsize=6)
    for j,k in enumerate(names):p.text(107,14+(j+.5)*48/7,str(total[k]),ha='right',fontsize=6.2)
    for j,label in enumerate(['0','1–2','3–5','6–10','11–25','26+']):
        x=23+14*j
        p.line(x,77,x+3.2,77,c=colors[j],lw=4.2,solid_capstyle='butt')
        p.text(x+4,77,label,fontsize=6)
    mapping={'submit_orca_displacement_sweep':'ORCA sweep','collect_periodic_dft_phonons':'Collect phonons',
        'run_periodic_dft_crystal_calculation':'Crystal DFT','collect_excited_state_couplings':'Collect couplings',
        'run_csp_funnel_workflow':'Packing search','compute_excited_state_spin_relaxation':'Relaxation','judge_t1_loop':'Validation'}
    ts={r['tool']:int(r['total_calls']) for r in getdata('agent_communication/science_tool_calls')}
    ax=p.axes(149,14,28,48)
    ax.barh(np.arange(7),[ts[k] for k in mapping],height=.39,color='#5363a7')
    for i,k in enumerate(mapping):
        ax.annotate(str(ts[k]),(ts[k],i),xytext=(2.3,0),textcoords='offset points',
                    ha='left',va='center',fontsize=6.15,annotation_clip=False)
    ax.set(yticks=range(7),yticklabels=mapping.values(),ylim=(6.5,-.5),xticks=[0,150,300],xlim=(0,330),xlabel='Calls')
    ax.spines['left'].set_visible(False);ax.tick_params(axis='y',length=0)
    save_si(p,'S8_communication')

def workflow():
    """Show the archived iodine handoff and a separately scoped resource comparison."""
    p=Plate(84)
    p.panel(1,3,'a','The forecast preceded the first packing run')
    p.panel(99,3,'b','Signed iodine result at the zone centre')
    p.text(6,10,'Time (UTC)',fontsize=6.15,color=MUTED)
    p.text(33,10,'Recorded action',fontsize=6.15,color=MUTED)
    p.line(6,13,94,13,c='#aab8bc',lw=.6)
    events=[
        ('6 Nov 22:36','Iodine test approved at any fold'),
        ('6 Nov 22:40','Discovery agent registered forecast'),
        ('6 Nov 22:51','Clari started the packing search'),
        ('12 Nov 00:12','Discovery agent requested ORCA results'),
        ('12 Nov 02:39','Validator signed result (5.2 days later)'),
    ]
    p.line(29,17,29,47,c='#d9b1c3',lw=.65)
    for i,(time,role) in enumerate(events):
        y=17+i*7.5
        p.text(6,y,time,fontsize=6.0)
        p.line(29,y,29,y,marker='o',ms=2.6,mfc='#c72c6a',mec='none')
        p.text(33,y,role,fontsize=6.5)
    receipt_file=ROOT/'preregistration'/'judge_receipt_R5_pI_rcpt-f0670a4fa30c.json'
    receipt=json.loads(receipt_file.read_text())
    detail=receipt['details']
    p.line(104,13,178,13,c='#aab8bc',lw=.6)
    for x,label in [(106,'Linewidth'),(131,'Spin lifetime'),(155,'Iodine / parent')]:
        p.text(x,18,label,fontsize=7,color=MUTED)
    for i,width in enumerate(['5','10','20']):
        lifetime=detail['t1_s'][width]*1e6
        ratio=detail['paired_ratio']['per_sigma'][width]
        y=24+6*i
        p.text(106,y,width+' cm⁻¹',fontsize=7.4)
        p.text(131,y,f'{lifetime:.3f} µs',fontsize=7.4)
        p.text(155,y,f'{ratio:.4f}×',fontsize=7.6,weight='bold',color=ACC['R5_pI'])
    p.line(104,41,178,41,c='#aab8bc',lw=.6)
    p.panel(1,55,'c','CPU core-hours in the variant pipelines, including the parent')
    data=[r for r in rows('methods/compute_by_salt_and_stage.csv') if r['variant']!='coordinator_studies']
    stages=[('Phonons','dft_phonons_core_h','#43538e'),
            ('Structures','dft_relax_rank_core_h','#8d99c3'),
            ('Electronic response','orca_gamma2_core_h','#b7678b')]
    totals=[sum(float(r[k]) for r in data) for _,k,_ in stages]
    ax=p.axes(38,60,110,16)
    ax.barh(range(3),totals,color=[color for _,_,color in stages],height=.52)
    for y,value in enumerate(totals):
        ax.annotate(f'{value:,.0f}',(value,y),xytext=(3,0),textcoords='offset points',va='center',fontsize=6.4)
    ax.set(yticks=range(3),yticklabels=[s[0] for s in stages],ylim=(2.5,-.5),xlim=(0,430000),
           xticks=[0,100000,200000,300000,400000],xticklabels=['0','100,000','200,000','300,000','400,000'])
    ax.tick_params(axis='y',length=0)
    ax.spines['left'].set_visible(False)
    save_si(p,'S3_network')
