#!/usr/bin/env python3
"""Check a trusted Lean project locally and export its source for Fermat Studio."""
import argparse, hashlib, json, os, pathlib, re, shutil, subprocess, tempfile, datetime
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('project',type=pathlib.Path)
p.add_argument('--module',required=True,help='Module containing the theorem, e.g. MyProject.Main')
p.add_argument('--theorem',required=True,help='Fully qualified theorem name')
p.add_argument('--output',type=pathlib.Path,default=pathlib.Path('proof.fermat.json'))
a=p.parse_args();root=a.project.resolve()
for value in (a.module,a.theorem):
    if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_'.]*",value):p.error('Use a simple qualified Lean identifier for module and theorem.')
lake=shutil.which('lake') or str(pathlib.Path.home()/'.elan/bin/lake')
subprocess.run([lake,'build'],cwd=root,check=True)
fd,name=tempfile.mkstemp(prefix='FermatAudit',suffix='.lean',dir=root)
try:
    with os.fdopen(fd,'w') as f:f.write(f'import {a.module}\n#print axioms {a.theorem}\n')
    result=subprocess.run([lake,'env','lean',name],cwd=root,check=True,capture_output=True,text=True)
finally:pathlib.Path(name).unlink(missing_ok=True)
print(result.stdout)
match=re.search(r'depends on axioms:\s*\[([^\]]*)\]',result.stdout)
if not match and 'does not depend on any axioms' not in result.stdout:raise SystemExit('Could not read the axiom report. No verified bundle was written.')
axioms=[x.strip() for x in match[1].split(',') if x.strip()] if match else []
if 'sorryAx' in axioms:raise SystemExit('The theorem depends on sorryAx. Complete the proof before exporting it as checked.')
files=[]
for directory,dirs,names in os.walk(root):
    dirs[:]=[d for d in dirs if not d.startswith('.') and d not in ('node_modules','build','dist')]
    for n in sorted(names):
        if not n.endswith('.lean'):continue
        f=pathlib.Path(directory)/n
        if f.is_symlink():continue
        source=f.read_text();files.append({'path':str(f.relative_to(root)),'source':source,'sha256':hashlib.sha256(source.encode()).hexdigest()})
bundle={'schema':'fermat-bundle-v1','files':files,'verification':{'status':'local-report','module':a.module,'theorem':a.theorem,'axioms':axioms,'leanToolchain':(root/'lean-toolchain').read_text().strip(),'checkedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'command':'lake build; lake env lean (axiom audit)','report':result.stdout}}
a.output.write_text(json.dumps(bundle,ensure_ascii=False));print(f'Wrote {len(files)} source files to {a.output}. Open this bundle at https://fermat.studio/.')
