"""Reproducible scientific diagrams from retained configuration and test metadata.

No invented neural activity, anatomical reconstruction or generated microscopy.
"""
from pathlib import Path
import json
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, FancyBboxPatch, FancyArrowPatch

ROOT=Path(__file__).resolve().parent
OUT=ROOT/'figures';OUT.mkdir(exist_ok=True)
PAPER,INK,VIOLET,MUTED,LINE='#fcfaf7','#28222d','#6240ab','#776e7d','#d8cfdf'
plt.rcParams.update({'font.family':'STIXGeneral','font.size':13,
    'text.color':INK,'axes.labelcolor':INK,'xtick.color':MUTED,'ytick.color':MUTED,
    'axes.edgecolor':LINE,'axes.spines.top':False,'axes.spines.right':False})


def canvas(title,subtitle):
    f=plt.figure(figsize=(12.8,8),dpi=150,facecolor=PAPER)
    f.text(.065,.94,'felisyn  /  research notes 09–10',color=VIOLET,fontsize=14)
    f.text(.065,.875,title,fontsize=29)
    f.text(.065,.822,subtitle,color=MUTED,fontsize=15)
    return f


def save(f,name):
    f.savefig(OUT/(name+'.png'),dpi=150,facecolor=PAPER)
    f.savefig(OUT/(name+'.svg'),facecolor=PAPER)
    plt.close(f)


def geometry():
    rows=json.loads((ROOT/'recording-comparison.json').read_text())
    r=next(x for x in rows if x['population']=='l4_cortex_exc')
    a=r['archive']['2']['params'];b=r['param_spont']['2']['params']
    f=canvas('The recording window matters','An analog-recording example from the cat visual-cortex model')
    for left,data,title in [(.07,a,'Archived run'),(.40,b,'Released spontaneous recipe')]:
        ax=f.add_axes([left,.34,.285,.405],facecolor=PAPER)
        size,spacing=data['size']/1000,data['spacing']/1000
        grid=np.arange(0,data['size'],data['spacing'])/1000-size/2
        x,y=np.meshgrid(grid,grid)
        ax.scatter(x,y,s=4,color=VIOLET,alpha=.72)
        ax.add_patch(Rectangle((-size/2,-size/2),size,size,fill=False,ec=VIOLET,lw=1.3))
        ax.set(xlim=(-1.1,1.1),ylim=(-1.1,1.1),aspect='equal',xlabel='Cortical position (mm)')
        if left<.1:ax.set_ylabel('Cortical position (mm)')
        ax.set_xticks([-1,0,1]);ax.set_yticks([-1,0,1]);ax.set_title(title,fontsize=15,pad=14)
        f.text(left,.225,f'{size:g} mm square · {data["spacing"]:g} µm spacing',fontsize=14)
        f.text(left,.19,f'{len(grid)**2} grid locations before nearest-neuron selection',fontsize=11,color=MUTED)
    f.text(.755,.665,'10×',fontsize=44,color=VIOLET)
    f.text(.755,.617,'the side length',fontsize=15)
    f.text(.755,.51,'100×',fontsize=44,color=VIOLET)
    f.text(.755,.462,'the nominal area',fontsize=15)
    f.text(.755,.34,'Same plotting scale.\nDots are grid locations,\nnot neuron positions.',fontsize=13,linespacing=1.5)
    f.text(.065,.115,'Shown: L4 excitatory analog grids. All four cortical populations match the general param recipe.',fontsize=12)
    f.text(.065,.080,'L4 and L2/3 inhibitory archived grids use 20 µm spacing. Grid sites are deduplicated to neuron IDs.',fontsize=11,color=MUTED)
    f.text(.065,.045,'Source: authors’ public Arkheia run + LSV1M v1.0 · Antolík et al. (2024) · configuration diagram',fontsize=11,color=MUTED)
    save(f,'01-recording-geometry')


def binning():
    result=json.loads((ROOT/'checks/analysis-parity.json').read_text())
    s=result['populations'][0]['spike_metrics']
    c=result['grating_bin_controls'][0]
    f=canvas('A “10 ms” bin can be 10.5 ms wide','A binning detail found while connecting the analysis to saved recordings')
    ax=f.add_axes([.085,.28,.84,.43],facecolor=PAPER)
    for y,duration,n,label,color in [(1,s['window_ms'][1]-s['window_ms'][0],s['bin_count'],'Saved spontaneous segment',VIOLET),
                                    (0,c['duration_ms'],c['bins'],'Saved grating segment',MUTED)]:
        edges=np.linspace(0,duration,n+1)
        for i in range(n):ax.add_patch(Rectangle((edges[i],y-.14),edges[i+1]-edges[i],.28,fc=color,alpha=.16 if i%2 else .29,ec=color,lw=1))
        ax.text(0,y+.30,label,fontsize=15)
        ax.text(duration+5,y,f'{duration:g} ms\n{n} bins × {duration/n:g} ms',va='center',fontsize=14,color=color)
    ax.set(xlim=(0,292),ylim=(-.48,1.62),yticks=[],xlabel='Time within each recorded segment (ms)')
    ax.set_xticks([0,50,100,150,200]);ax.spines['left'].set_visible(False)
    f.text(.085,.725,'Original rule: round(duration / nominal width), then divide the entire recording range.',fontsize=13,color=MUTED)
    f.text(.085,.16,'We preserve every sample and report both nominal and effective bin width.',fontsize=16,color=VIOLET)
    f.text(.085,.108,'Full published protocol: 40,320 ms / 4,032 bins = 10 ms. That full-model run is still pending.',fontsize=12)
    f.text(.085,.057,'Source: pinned Mozaik PSTH helper and retained small-run timestamps · method diagram, not neural activity',fontsize=11,color=MUTED)
    save(f,'02-time-binning')


def pipeline():
    r=json.loads((ROOT/'checks/analysis-parity.json').read_text())
    f=canvas('One recording. Two calculation paths.','A numerical check of our analysis against the original Figure 4 statistics')
    ax=f.add_axes([0,0,1,.81]);ax.set(xlim=(0,1),ylim=(0,1));ax.axis('off')
    def box(x,y,w,h,title,body,color=VIOLET):
        ax.add_patch(FancyBboxPatch((x,y),w,h,boxstyle='round,pad=0.01,rounding_size=0.008',fc=PAPER,ec=color,lw=1.3))
        ax.text(x+w/2,y+h*.69,title,ha='center',va='center',fontsize=17,color=color)
        ax.text(x+w/2,y+h*.30,body,ha='center',va='center',fontsize=12,linespacing=1.3)
    def arrow(a,b):ax.add_patch(FancyArrowPatch(a,b,arrowstyle='-|>',mutation_scale=13,color=MUTED,lw=1.2))
    box(.32,.755,.36,.17,'Retained simulation data','Four cortical populations · 105 ms each')
    box(.065,.415,.38,.18,'Original analysis','Pinned framework + unchanged\nFigure 4 numerical statements')
    box(.555,.415,.38,.18,'Felisyn metric helpers','Explicit IDs, windows and units\nSame saved inputs')
    arrow((.40,.745),(.255,.605));arrow((.60,.745),(.745,.605))
    ax.text(.5,.656,'Neuron IDs and signal timing checked',ha='center',fontsize=12,color=MUTED)
    box(.26,.14,.48,.19,f'{r["passed"]} / {r["total"]} comparisons agree','Six metrics × mean and SD × four populations')
    arrow((.255,.405),(.38,.34));arrow((.745,.405),(.62,.34))
    f.text(.065,.072,'Numerical tolerance: absolute 1e-10 + relative 1e-12. Input datastore hashes remained unchanged.',fontsize=12,color=MUTED)
    f.text(.065,.032,'Analysis agreement on a small saved run. No new neural simulation, full-model reproduction or biological validation.',fontsize=11,color=MUTED)
    save(f,'03-analysis-paths')


if __name__=='__main__':
    geometry();binning();pipeline()
    print('Saved three source-driven diagrams in',OUT)
