"""Trace formal modules and reproduce the logical diagrams from the pinned sources."""
from pathlib import Path
import re,json,hashlib,collections
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
R=Path(__file__).resolve().parents[1];S=R/'sources/formalization';V=R/'lean_verification';F=R/'research_figures'
def dump(path,obj):path.write_text(json.dumps(obj,indent=2,ensure_ascii=False)+'\n')
def uncomment(t):
    out=[];depth=0;i=0
    while i<len(t):
        tok=t[i:i+2]
        if tok=='/-':depth+=1;i+=2;continue
        if depth and tok=='-/':depth-=1;i+=2;continue
        if not depth and tok=='--':
            i=t.find('\n',i)
            if i==-1:break
        if t[i]=='\n' or depth==0:out.append(t[i])
        else:out.append(' ')
        i+=1
    return ''.join(out)
mods={};edges=[]
for p in sorted(S.rglob('*.lean')):
    name='.'.join(p.relative_to(S).with_suffix('').parts)
    code=uncomment(p.read_text());imports=re.findall(r'^import\s+([\w.]+)',code,re.M)
    mods[name]={'path':str(p.relative_to(S)),'imports':imports,'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),
                'placeholder_lines':[k for k,l in enumerate(code.splitlines(),1) if re.search(r'\b(sorry|admit)\b',l)],
                'axiom_declarations':[k for k,l in enumerate(code.splitlines(),1) if re.match(r'\s*(?:private\s+)?(?:axiom|constant)\s+',l)]}
    edges += [(i,name) for i in imports]
closure=set()
def visit(m):
    if m in closure:return
    closure.add(m)
    for i in mods.get(m,{}).get('imports',[]):visit(i)
visit('Solution')
dump(V/'proof_dependency_graph.json',{'type':'Direct file imports, upstream project scope','root':'Solution','modules':mods,'edges':edges,'solution_import_closure':sorted(closure)})
assert 'Challenge' not in closure and all(not mods[m]['placeholder_lines'] and not mods[m]['axiom_declarations'] for m in closure if m in mods)
fig,ax=plt.subplots(figsize=(9,5.6),layout='constrained');bg='#faf8ec';fig.patch.set_facecolor(bg);ax.set_facecolor(bg)
pos={'Mathlib':(.06,.52),'Statement':(.32,.95),'Minimal.Blocks':(.22,.50),'Minimal.Lemma1':(.36,.68),'Minimal.Slots':(.36,.43),'Minimal.Lemma2Setup':(.50,.56),'Minimal.Lemma2Reach':(.63,.72),'Minimal.Lemma2Split':(.63,.44),'Minimal.Lemma2':(.75,.59),'Minimal.Tower':(.36,.15),'Minimal.Limit':(.66,.10),'Minimal.Construction':(.78,.30),'Minimal.Main':(.91,.24),'Solution':(.92,.91)}
for i,j in edges:
    if i in pos and j in pos:ax.annotate('',pos[j],pos[i],arrowprops=dict(arrowstyle='-|>',lw=.9,color='#8a998c',shrinkA=11,shrinkB=11,connectionstyle='arc3,rad=.035'))
for m,(x,y) in pos.items():
    ax.text(x,y,m.replace('Minimal.',''),fontsize=9,ha='center',va='center',bbox=dict(boxstyle='round,pad=.32',fc='#e4eada' if m!='Solution' else '#a3d1b5',ec='#8b9a89',lw=.7))
ax.axis('off');ax.set(xlim=(-.025,1.03),ylim=(0,1.06));ax.set_title('Imports leading to the public proof',loc='left',fontweight='bold')
fig.savefig(F/'11-imports.png',dpi=160);fig.savefig(F/'11-imports.svg');plt.close(fig)
steps=[
 ('Invariance','ξ ∈ M, ζ ⟂ M','Every polynomial q satisfies ⟨q(T)ξ,ζ⟩ = 0.','§5, opening paragraph'),
 ('Fibers','Reach on at least half of the sign sequences','Average the fiber operators to obtain Re ⟨Cv,w⟩ ≥ μ/2.','Minimal/Tower.lean · Tower.fibers'),
 ('Splitting','Approximate C by A in the unit ideal','Induct through the two endpoint slots, paying at most Σ γₘ.','Minimal/Tower.lean · Tower.splitting'),
 ('Limit','Transport the polynomial and take N large','The positive lower bound contradicts the vanishing pairing.','Minimal/Limit.lean · Tower.limit_step')]
dump(R/'theorem_dependency_map.json',{'paper':'2612.00240v1','prerequisites':{'Fibers':['Endpoint maps (3)','Chebyshev inequality','Reach 3.2(b)'],'Splitting':['Endpoint identity','Split 3.2(c)','Summable budget (2)'],'Limit':['Polynomial estimates (1)','Convergence (4)','Projection convergence','Fibers','Splitting']},'steps':steps})
fig,ax=plt.subplots(figsize=(8,4.4),layout='constrained');fig.patch.set_facecolor(bg);ax.axis('off')
for j,(title,formula,reason,ref) in enumerate(steps):
    y=.86-.24*j;ax.text(.015,y,title,color='#176351',weight='bold',fontsize=13);ax.text(.22,y,formula,fontsize=13);ax.text(.22,y-.08,reason,fontsize=10,color='#4f5c51')
ax.set_title('How a positive pairing forces a contradiction',loc='left',fontweight='bold')
fig.savefig(F/'12-proof.png',dpi=160);fig.savefig(F/'12-proof.svg');plt.close(fig)
index=json.loads((F/'index.json').read_text());index=[f for f in index if f['id'] not in ('11-imports','12-proof')]
index.extend([dict(id='11-imports',title='Imports leading to the public proof',caption='Each arrow goes from an imported module to its importer. Mathlib is collapsed to its root. This is a module graph, not a term-level kernel dependency trace.',source='lean_verification/proof_dependency_graph.json'),dict(id='12-proof',title='How a positive pairing forces a contradiction',caption='The local reconstruction follows the three named stages in §5. The complete proof needs the estimates established in §§2–4.',source='theorem_dependency_map.json')])
dump(F/'index.json',index)
