import os,re,sys,collections
root=sys.argv[1]
imp=re.compile(r'^\s*(?:public\s+)?(?:meta\s+)?import\s+(?:all\s+)?([\w.]+)',re.M)
deps={}
for dp,_,fs in os.walk(root):
    for f in fs:
        if f.endswith('.lean'):
            p=os.path.join(dp,f); m=os.path.relpath(p,root)[:-5].replace('/','.')
            txt=open(p,encoding='utf-8',errors='replace').read(20000)
            deps[m]=[x for x in imp.findall(txt.split('\n/-')[0] if False else txt)]
targets=sys.argv[2:]
seen=set();st=list(targets);ext=collections.Counter()
while st:
    m=st.pop()
    if m in seen: continue
    seen.add(m)
    for d in deps.get(m,[]):
        if d in deps: st.append(d)
        else: ext[d.split('.')[0]]+=1
print('local modules',len(deps),'closure',len(seen))
print('external roots',ext.most_common(10))
# depth (longest chain)
import functools
sys.setrecursionlimit(1000000)
memo={}
order=[]
# iterative longest path
depth={}
def dfs(m):
    stack=[(m,0)]
    while stack:
        n,i=stack.pop()
        if n in depth: continue
        ds=[d for d in deps.get(n,[]) if d in deps]
        if i<len(ds):
            stack.append((n,i+1))
            if ds[i] not in depth: stack.append((ds[i],0))
        else:
            depth[n]=1+max([depth[d] for d in ds],default=0)
for t in targets: dfs(t)
print('critical path length (files)',max(depth[t] for t in targets))
lines=sum(sum(1 for _ in open(os.path.join(root,m.replace('.','/')+'.lean'),errors='replace')) for m in seen)
print('closure lines',lines)
