"""Draw execution evidence from the locally recorded notebook and formal audit."""
from pathlib import Path
import json
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
R=Path(__file__).resolve().parents[1];F=R/'research_figures';V=R/'lean_verification'
index=[f for f in json.loads((F/'index.json').read_text()) if f['id'] not in ['13-trace','14-trust','15-gate']]
def save(fig,name,title,caption,rel):
 fig.savefig(F/(name+'.png'),dpi=150,bbox_inches='tight');fig.savefig(F/(name+'.svg'),bbox_inches='tight');plt.close(fig)
 index.append({'id':name,'title':title,'caption':caption,'source':rel})
trace=json.loads((R/'model_session/run_trace.json').read_text());rows=trace['notebook_cells'];start=trace['started_ms']
fig,(ax,bx)=plt.subplots(2,1,figsize=(8,4.8),height_ratios=[1.1,2],layout='constrained')
fig.patch.set_facecolor('#faf9f0')
for r in rows:
 color='#24705f' if r['status']=='completed' else '#ba6533';a=(r['start_ms']-start)/60000;duration=(r['end_ms']-r['start_ms'])/1000
 ax.vlines(a,0,1,color=color,lw=2);bx.bar(r['index'],duration,color=color,width=.72)
ax.set(yticks=[],xlabel='Minutes from the first model request',ylim=(0,1));ax.set_title('Recorded notebook executions',loc='left',weight='bold')
bx.set(xlabel='Notebook cell in execution order',ylabel='Duration (seconds)');bx.grid(axis='y',alpha=.18)
for a in (ax,bx):a.spines[['right','top']].set_visible(False)
save(fig,'13-trace','Recorded notebook executions','Positions show when cells started during the single research session. Green indicates completion and amber a failed cell. Blank intervals include model inference and other work.','model_session/run_trace.json')
trust=json.loads((V/'status.json').read_text())
if trust['local_build']=='passed':
 checks=trust['endpoints'];fig,ax=plt.subplots(figsize=(7.6,3.5),layout='constrained');fig.patch.set_facecolor('#faf9f0')
 ax.set_xlim(-.5,2.5);ax.set_ylim(len(checks)-.5,-.5);ax.set_xticks(range(3),['propext','Classical.choice','Quot.sound']);ax.set_yticks(range(len(checks)),[x.split('.')[-1] for x in checks])
 for i,(name,axioms) in enumerate(checks.items()):
  for k,axm in enumerate(['propext','Classical.choice','Quot.sound']):
   if axm in axioms:ax.add_patch(Rectangle((k-.41,i-.31),.82,.62,fc='#c5dcc8',ec='#719780'));ax.text(k,i,'reported',ha='center',va='center',fontsize=9)
 ax.set_title('Axioms reported for each public theorem',loc='left',weight='bold');ax.spines[:].set_visible(False);ax.tick_params(length=0)
 save(fig,'14-trust','Axioms reported for each public theorem','This matrix is populated only from the local #print axioms output. Every listed endpoint was checked with the pinned Lean toolchain.','lean_verification/status.json')
gate=[(0,0.,0.),(1,1/8,1/8),(2,24*36864/113246208,(1/8)/16)]
fig,ax=plt.subplots(figsize=(7.5,3.8),layout='constrained');fig.patch.set_facecolor('#faf9f0');ax.bar(['Stage 1','Stage 2'],[g[1] for g in gate[1:]],color=['#246958','#ac753b'])
ax.set(yscale='log',ylabel='Admissible γ = 24 L τ');ax.set_title('The tower tightens its second error budget',loc='left',weight='bold')
for i,g in enumerate(gate[1:]):ax.text(i,g[1],f'{g[1]:.6f}',ha='center',va='bottom');ax.spines[['top','right']].set_visible(False)
data={'first':{'L':1,'tau':'1/192','gamma':'1/8'},'second':{'L':36864,'tau':'1/113246208','gamma':'1/128'},'basis':'Equation in §4, with mu1=1/8'}
(R/'numerical_results/tower_budget.json').write_text(json.dumps(data,indent=2)+'\n')
save(fig,'15-gate','The tower tightens its second error budget','Analytic choices for the first two steps in §4. The second budget uses the exact first-stage Reach constant. Only the first tower matrix was instantiated.','numerical_results/tower_budget.json')
(F/'index.json').write_text(json.dumps(index,indent=2)+'\n')
