#!/usr/bin/env python3
"""Install the pinned Lean toolchain, check the submitted proof, and emit a certificate.

Linux and macOS are supported. On Windows, run this script in Ubuntu under WSL.
The standalone download uses only Python's standard library.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import platform
import re
try:
    import resource
except ImportError:
    resource=None
import shutil
import subprocess
import sys
import tarfile
import time
import urllib.request

#!/usr/bin/env python3
"""Recompute Lean-source statistics with Python's standard library only."""
import argparse
from collections import Counter, deque
import hashlib
import json
from pathlib import Path, PurePosixPath
import re
import tarfile
import time

DECLARATION = re.compile(rb'^\s*(?:(?:private|protected|noncomputable)\s+)*(theorem|lemma|def|abbrev|structure|class|instance|axiom|opaque)\b', re.M)


def import_header(text):
    """Read the import header, respecting nested Lean comments."""
    result=[]
    depth=0
    for line in text.splitlines():
        visible=[];i=0
        while i<len(line):
            if line.startswith('/-',i):depth+=1;i+=2
            elif depth and line.startswith('-/',i):depth-=1;i+=2
            elif depth:i+=1
            elif line.startswith('--',i):break
            else:visible.append(line[i]);i+=1
        value=''.join(visible).strip()
        if not value:continue
        if value in ('module','prelude'):continue
        match=re.match(r'(?:(?:public|private|meta)\s+)*import\s+(?:all\s+)?(.+)$',value)
        if not match:break
        result.extend(match.group(1).split())
    return result


def source_entries(source):
    source=Path(source)
    if source.is_file():
        with tarfile.open(source,'r|gz') as archive:
            for member in archive:
                parts=PurePosixPath(member.name).parts
                if not member.isfile():continue
                if len(parts)>2 and parts[:2]==('lean','src'):relative=PurePosixPath(*parts[2:])
                elif len(parts)>1 and parts[0]=='text':relative=PurePosixPath(*parts[1:])
                else:continue
                if relative.suffix not in ('.lean','.txt'):continue
                yield str(relative.with_suffix('.lean')),archive.extractfile(member).read()
    else:
        if (source/'src').is_dir():source=source/'src'
        elif (source/'lean/src').is_dir():source=source/'lean/src'
        elif (source/'text').is_dir():source=source/'text'
        for path in sorted(source.rglob('*')):
            if path.suffix not in ('.lean','.txt') or not path.is_file():continue
            if any(part in ('.lake','.git','node_modules','.tools') for part in path.relative_to(source).parts):continue
            yield str(PurePosixPath(*path.relative_to(source).parts).with_suffix('.lean')),path.read_bytes()


def analyze(source, progress=True):
    start=time.monotonic();cpu=time.process_time()
    rows=[];declarations=Counter();groups={}
    lines=nonblank=size=0
    for name,data in source_entries(source):
        split=data.splitlines();count=len(split);filled=sum(bool(line.strip()) for line in split)
        sha=hashlib.sha256(data).hexdigest();group=name.split('/')[0] if '/' in name else 'Entry points'
        category=groups.setdefault(group,{'files':0,'lines':0});category['files']+=1;category['lines']+=count
        declarations.update(word.decode() for word in DECLARATION.findall(data))
        rows.append({'path':name,'lines':count,'bytes':len(data),'sha256':sha,'imports':import_header(data.decode('utf-8'))})
        lines+=count;nonblank+=filled;size+=len(data)
        if progress and len(rows)%25000==0:print(f'Analyzed {len(rows):,} source files',flush=True)
    if not rows:raise ValueError('No Lean source files found in the selected input')
    rows.sort(key=lambda row:PurePosixPath(row['path']).parts)
    digest=hashlib.sha256()
    for row in rows:digest.update(row['path'].encode()+b'\0'+row['sha256'].encode()+b'\n')
    lookup={row['path'][:-5].replace('/','.'):i for i,row in enumerate(rows)}
    graph=[sorted({lookup[module] for module in row['imports'] if module in lookup}) for row in rows]
    depths=[-1]*len(rows);queue=deque()
    if 'Main' in lookup:depths[lookup['Main']]=0;queue.append(lookup['Main'])
    while queue:
        node=queue.popleft()
        for target in graph[node]:
            if depths[target]<0:depths[target]=depths[node]+1;queue.append(target)
    layers={}
    for i,row in enumerate(rows):
        if depths[i]<0:continue
        layer=layers.setdefault(depths[i],{'depth':depths[i],'files':0,'lines':0})
        layer['files']+=1;layer['lines']+=row['lines']
    return {'schema_version':1,'files':len(rows),'lines':lines,'nonblank_lines':nonblank,'blank_lines':lines-nonblank,'bytes':size,
            'source_tree_sha256':digest.hexdigest(),'declaration_counts_textual':dict(declarations),'groups':groups,
            'internal_import_edges':sum(map(len,graph)),'main_import_closure_files':sum(depth>=0 for depth in depths),
            'layers':[layers[key] for key in sorted(layers)],
            'counting_method':'Physical source lines, including comments and blanks; dependencies and generated files excluded. Declaration counts are textual. Import headers respect nested comments. Each layer is the shortest project-import distance from Main, with each file counted once.',
            'analysis_wall_seconds':round(time.monotonic()-start,3),'analysis_cpu_seconds':round(time.process_time()-cpu,3)}


def stats_cli():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('source',help='Extracted lean/, text/, or a downloaded .tar.gz source archive')
    parser.add_argument('--output',default='proof-statistics.json')
    args=parser.parse_args();value=analyze(args.source)
    Path(args.output).write_text(json.dumps(value,indent=2)+'\n')
    print(json.dumps({k:value[k] for k in ('files','lines','nonblank_lines','bytes','source_tree_sha256','declaration_counts_textual','internal_import_edges')},indent=2))
    print('Full report:',args.output)



_MANIFEST_JSON = '{\n  "schema_version": 1,\n  "source_url": "https://alpo.ge/remark.pdf",\n  "source_tree_sha256": "27bd2a2fc971307240174cb58dd094f5d433980641079871fd2e8d1c9381f089",\n  "source_files": 175187,\n  "source_lines": 17374215,\n  "toolchain": "leanprover/lean4:v4.33.1",\n  "mathlib_revision": "0df444a360eaa60ab8c11dca51a86af692955474",\n  "elan_release": "v4.4.0",\n  "parts": [\n    {\n      "file": "lean.tar.gz.part01",\n      "url": "https://alpo.ge/lean.tar.gz.part01",\n      "bytes": 18000000,\n      "sha256": "86974b1c242ca7b6748f3299df4fc64ee0f6e06c776ac964fb64888101a3de77"\n    },\n    {\n      "file": "lean.tar.gz.part02",\n      "url": "https://alpo.ge/lean.tar.gz.part02",\n      "bytes": 18000000,\n      "sha256": "1c2a2477354a9dfa97ff1ce54861e96ed885bd456fffbaaabc2028314a229c42"\n    },\n    {\n      "file": "lean.tar.gz.part03",\n      "url": "https://alpo.ge/lean.tar.gz.part03",\n      "bytes": 18000000,\n      "sha256": "1465a23b1b579a881e24e5ffaf7c4c3727af28ea24741f1ec80e1d67947530a3"\n    },\n    {\n      "file": "lean.tar.gz.part04",\n      "url": "https://alpo.ge/lean.tar.gz.part04",\n      "bytes": 18000000,\n      "sha256": "3929e327eecb4e2c5c7cae30e104e6a4a52fa6b82d28325bcda8e9da1c86893b"\n    },\n    {\n      "file": "lean.tar.gz.part05",\n      "url": "https://alpo.ge/lean.tar.gz.part05",\n      "bytes": 18000000,\n      "sha256": "f25d7e80f7c4ad6d674aa18b323ca760f848857c8755501c149317c38a66c75d"\n    },\n    {\n      "file": "lean.tar.gz.part06",\n      "url": "https://alpo.ge/lean.tar.gz.part06",\n      "bytes": 18000000,\n      "sha256": "a8c651a68327811b37dce3cca8eda5e0b2102fa227c0d395cbb7553e4dd69939"\n    },\n    {\n      "file": "lean.tar.gz.part07",\n      "url": "https://alpo.ge/lean.tar.gz.part07",\n      "bytes": 18000000,\n      "sha256": "65c7e502a9b236a0f68d9e0aa6e089d4c09b9fc7a0960a149384063ccbe5e869"\n    },\n    {\n      "file": "lean.tar.gz.part08",\n      "url": "https://alpo.ge/lean.tar.gz.part08",\n      "bytes": 18000000,\n      "sha256": "71b027ad6e4179c3a50ce72921e3fec0a2dd751ec7472ac2c644ad145a50ec7e"\n    },\n    {\n      "file": "lean.tar.gz.part09",\n      "url": "https://alpo.ge/lean.tar.gz.part09",\n      "bytes": 18000000,\n      "sha256": "47718977ebaa8613f1647e93134479780db9320c5fa911463fd312a6257b796f"\n    },\n    {\n      "file": "lean.tar.gz.part10",\n      "url": "https://alpo.ge/lean.tar.gz.part10",\n      "bytes": 18000000,\n      "sha256": "1d85ece78e0779cec26b0cce29c6462d9f90180e56d78120b152df101715240b"\n    },\n    {\n      "file": "lean.tar.gz.part11",\n      "url": "https://alpo.ge/lean.tar.gz.part11",\n      "bytes": 18000000,\n      "sha256": "cf83a159d1a9540012229c376562587dd966da10cd657cbcef53acfd03232448"\n    },\n    {\n      "file": "lean.tar.gz.part12",\n      "url": "https://alpo.ge/lean.tar.gz.part12",\n      "bytes": 18000000,\n      "sha256": "1aa5415bd2db83b2689afeeb946419303b3c4f599ae790ad74d38465f768b502"\n    },\n    {\n      "file": "lean.tar.gz.part13",\n      "url": "https://alpo.ge/lean.tar.gz.part13",\n      "bytes": 18000000,\n      "sha256": "2de4edbce8ebdbfd0b94bc89bab518c7294209f408ec5b14a7be9e4832d9da81"\n    },\n    {\n      "file": "lean.tar.gz.part14",\n      "url": "https://alpo.ge/lean.tar.gz.part14",\n      "bytes": 5275554,\n      "sha256": "53f8ea43a9b5dcab97b84a52f3ac2848711c844a5420a4c56418093bacb3c6f6"\n    }\n  ],\n  "config_sha256": {\n    "lean-toolchain": "3aac669c7a910ec2389f4e4f921b605adf6ebf2d1e0c9b9cd0be4d33f3f5db71",\n    "lakefile.toml": "b831ad8cac0babb7bf713433259bdfe5163e58c90734e86d71536d4e30ddec4c",\n    "lake-manifest.json": "fee57ee9ed399d0a638ca955e5ad40a37a36eeb9b6dfd9f5964114fa7bbe4774"\n  },\n  "elan_assets": {\n    "aarch64-apple-darwin": {\n      "url": "https://github.com/leanprover/elan/releases/download/v4.4.0/elan-aarch64-apple-darwin.tar.gz",\n      "sha256": "27af24edeace839730e8c9119783f12d5f694327d4771605021ca09db1ab0a87"\n    },\n    "aarch64-unknown-linux-gnu": {\n      "url": "https://github.com/leanprover/elan/releases/download/v4.4.0/elan-aarch64-unknown-linux-gnu.tar.gz",\n      "sha256": "45cde3006f82f98804c94cf2ca4949d117060a5f3cc8afa62f523759947ee21f"\n    },\n    "x86_64-apple-darwin": {\n      "url": "https://github.com/leanprover/elan/releases/download/v4.4.0/elan-x86_64-apple-darwin.tar.gz",\n      "sha256": "a5123096d662216ceaf69d68d6bbabb118c024d20d270bf0d639a830dd4ff97e"\n    },\n    "x86_64-unknown-linux-gnu": {\n      "url": "https://github.com/leanprover/elan/releases/download/v4.4.0/elan-x86_64-unknown-linux-gnu.tar.gz",\n      "sha256": "0e8250aa2be86c7af929ade68db617af9edc8b9ccf6eaf5ece228250d0d032e2"\n    }\n  }\n}\n'
THEOREMS=['riemannHypothesis','riemannZeta_eq_zero_re','LFunction_ne_zero_of_half_lt_re','LFunction_eq_zero_re','LFunction_eq_zero_re_of_isPrimitive']
STANDARD_AXIOMS={'propext','Classical.choice','Quot.sound'}


def sha_file(path):
    digest=hashlib.sha256()
    with Path(path).open('rb') as stream:
        for block in iter(lambda:stream.read(1024*1024),b''):digest.update(block)
    return digest.hexdigest()


def download(url,path,expected=None):
    path=Path(path)
    if path.exists() and (expected is None or sha_file(path)==expected):return path
    temporary=path.with_suffix(path.suffix+'.part');path.parent.mkdir(parents=True,exist_ok=True)
    request=urllib.request.Request(url,headers={'User-Agent':'Independent-Lean-Proof-Checker/1.0'})
    for attempt in range(3):
        try:
            with urllib.request.urlopen(request,timeout=120) as response,temporary.open('wb') as output:shutil.copyfileobj(response,output,1024*1024)
            if expected and sha_file(temporary)!=expected:raise ValueError('SHA-256 mismatch for '+url)
            temporary.replace(path);return path
        except Exception:
            if attempt==2:raise
            time.sleep(2*(attempt+1))


def safe_extract(archive,destination,proof=True):
    destination=Path(destination).resolve()
    with tarfile.open(archive,'r:gz') as source:
        for member in source:
            parts=PurePosixPath(member.name).parts
            if member.name.startswith('/') or '..' in parts or not (member.isfile() or member.isdir()):raise ValueError('Unsafe archive entry: '+member.name)
            if proof and member.isfile() and not (len(parts)>2 and parts[:2]==('lean','src') and parts[-1].endswith('.lean') or member.name in ('lean/lean-toolchain','lean/lakefile.toml','lean/lake-manifest.json')):raise ValueError('Unexpected proof archive entry: '+member.name)
            target=destination.joinpath(*parts)
            if not target.resolve().is_relative_to(destination):raise ValueError('Archive escapes the working directory')
            if member.isdir():target.mkdir(parents=True,exist_ok=True)
            else:
                target.parent.mkdir(parents=True,exist_ok=True)
                with source.extractfile(member) as data,target.open('wb') as output:shutil.copyfileobj(data,output)
                target.chmod(0o755 if not proof and target.name=='elan-init' else 0o644)


def ensure_system_tools(yes):
    missing=[name for name in ('git','cc','make') if not shutil.which(name)]
    if not missing:return
    if platform.system()=='Linux' and shutil.which('apt-get'):
        prefix=[] if os.geteuid()==0 else ['sudo'];commands=[prefix+['apt-get','update'],prefix+['apt-get','install','-y','git','curl','build-essential','zstd']]
    elif platform.system()=='Linux' and shutil.which('dnf'):
        prefix=[] if os.geteuid()==0 else ['sudo'];commands=[prefix+['dnf','install','-y','git','curl','gcc','gcc-c++','make','zstd']]
    elif platform.system()=='Darwin' and shutil.which('brew'):commands=[['brew','install','git','make']]
    else:raise RuntimeError('Install git and a C/C++ build toolchain first. On macOS run xcode-select --install; on Windows use Ubuntu in WSL.')
    print('Missing system tools:',', '.join(missing))
    for command in commands:print('  '+' '.join(command))
    if not yes and input('Install these missing dependencies? [y/N] ').strip().lower() not in ('y','yes'):raise RuntimeError('System dependency installation declined')
    for command in commands:subprocess.run(command,check=True)


def get_source(args,manifest,work):
    project=Path(args.source).expanduser().resolve() if args.source else work/'lean'
    if (project/'src').is_dir():return project
    if args.source:raise ValueError('--source must point to an extracted Lean project containing src/')
    archive=Path(args.archive).expanduser().resolve() if args.archive else work/'downloads/lean-sources.tar.gz'
    if not archive.exists():
        try:download(args.source_url,archive)
        except Exception as error:
            print('Website bundle unavailable; using the original pinned PDF links:',error,flush=True)
            def part(record):return download(record['url'],work/'downloads'/record['file'],record['sha256'])
            with ThreadPoolExecutor(max_workers=4) as executor:parts=list(executor.map(part,manifest['parts']))
            archive.parent.mkdir(parents=True,exist_ok=True)
            with archive.open('wb') as output:
                for path in parts:
                    with path.open('rb') as stream:shutil.copyfileobj(stream,output)
    print('Extracting the submitted proof source…',flush=True);safe_extract(archive,work)
    return project


def get_elan(work,manifest,env):
    local=work/'.tools/elan';env['ELAN_HOME']=str(local)
    executable=local/'bin/elan'
    if executable.exists():return str(executable)
    existing=shutil.which('elan')
    if existing:return existing
    system=platform.system();arch=platform.machine().lower()
    arch='aarch64' if arch in ('arm64','aarch64') else 'x86_64' if arch in ('x86_64','amd64') else arch
    target=arch+('-apple-darwin' if system=='Darwin' else '-unknown-linux-gnu')
    asset=manifest['elan_assets'].get(target)
    if not asset:raise RuntimeError('Unsupported installer platform: '+target+'. Use Linux, macOS, or Ubuntu in WSL.')
    archive=download(asset['url'],work/'downloads'/('elan-'+target+'.tar.gz'),asset['sha256'])
    unpack=work/'.tools/elan-installer';unpack.mkdir(parents=True,exist_ok=True);safe_extract(archive,unpack,proof=False)
    subprocess.run([str(unpack/'elan-init'),'-y','--no-modify-path','--default-toolchain','none'],env=env,check=True)
    return str(executable)


def save_certificate(output,certificate):
    value=dict(certificate)
    value['certificate_sha256']=hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()).hexdigest()
    temporary=output.with_suffix('.tmp');temporary.write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n');temporary.replace(output)


def main():
    if sys.version_info<(3,10):raise SystemExit('Python 3.10 or newer is required.')
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--work-dir',default='riemann-independent-check')
    parser.add_argument('--source',help='Use an existing extracted Lean project')
    parser.add_argument('--archive',help='Use a downloaded lean-sources.tar.gz')
    parser.add_argument('--source-url',default='https://riemann.rylandgross.com/downloads/lean-sources.tar.gz')
    parser.add_argument('--yes',action='store_true',help='Approve installing missing system packages')
    parser.add_argument('--jobs',type=int,default=1,help='Lean worker threads (default: 1)')
    parser.add_argument('--fresh',action='store_true',help='Remove only the project build cache before checking')
    parser.add_argument('--stats-only',action='store_true',help='Analyze sources without installing or running Lean')
    parser.add_argument('--plan',action='store_true',help='Show the steps without installing or checking anything')
    parser.add_argument('--name',default='Independent verifier',help='Optional public attribution in the certificate')
    args=parser.parse_args()
    if args.plan:
        print('1. Obtain and hash-check the exact source and configuration.\n2. Install missing Git/build tools and an isolated pinned Lean toolchain.\n3. Fetch pinned mathlib dependencies and their cache.\n4. Compile Main and every imported proof dependency.\n5. Print the five theorem types and audit their axioms.\n6. Reconfirm source hashes and write a certificate with logs and timings.\nA fresh run installs tools under the selected work directory. Interrupted builds can be resumed.');return 0
    if platform.system()=='Windows':raise SystemExit('Run this checker in Ubuntu under WSL on Windows.')
    if args.jobs<1:parser.error('--jobs must be positive')
    manifest=json.loads(_MANIFEST_JSON) if _MANIFEST_JSON else json.loads(Path(__file__).with_name('proof_manifest.json').read_text())
    work=Path(args.work_dir).expanduser().resolve();work.mkdir(parents=True,exist_ok=True)
    results=work/'results';results.mkdir(exist_ok=True);output=results/'certificate.json'
    certificate={'format':'lean-proof-check/v1','verifier':args.name,'created_at':datetime.now(timezone.utc).isoformat(),'status':'in_progress','source_tree_sha256':manifest['source_tree_sha256'],'toolchain':manifest['toolchain'],'mathlib_revision':manifest['mathlib_revision'],'runner_sha256':sha_file(__file__),'theorems':THEOREMS,'steps':[],'machine':{'system':platform.system(),'architecture':platform.machine(),'logical_cpus':os.cpu_count()},'report_scope':'A reproducible, self-reported local check. The digest detects changes to this report; it is not an identity signature or a substitute for independently rerunning Lean.'}
    began=time.monotonic();save_certificate(output,certificate)
    env=dict(os.environ,LEAN_NUM_THREADS=str(args.jobs))
    def run(label,command,cwd,kind='setup',allow_failure=False):
        print('\n'+label,flush=True);started=time.monotonic();before=resource.getrusage(resource.RUSAGE_CHILDREN)
        name=f'{len(certificate["steps"])+1:02d}-'+re.sub('[^a-z0-9]+','-',label.lower()).strip('-')+'.log';log_path=results/name
        with log_path.open('w') as log:code=subprocess.run(command,cwd=cwd,env=env,stdout=log,stderr=subprocess.STDOUT).returncode
        after=resource.getrusage(resource.RUSAGE_CHILDREN);cpu=after.ru_utime+after.ru_stime-before.ru_utime-before.ru_stime
        certificate['steps'].append({'label':label,'kind':kind,'exit_code':code,'wall_seconds':round(time.monotonic()-started,3),'cpu_seconds':round(cpu,3),'log':name,'log_sha256':sha_file(log_path)})
        save_certificate(output,certificate)
        if code and not allow_failure:raise RuntimeError(label+' failed; inspect '+str(log_path))
        return log_path
    try:
        project=get_source(args,manifest,work)
        stats=analyze(project);(results/'statistics.json').write_text(json.dumps(stats,indent=2)+'\n')
        certificate['observed_source_tree_sha256']=stats['source_tree_sha256']
        if stats['source_tree_sha256']!=manifest['source_tree_sha256']:raise RuntimeError('The source fingerprint differs from the submitted proof. No certificate of the original source will be issued.')
        for name,expected in manifest['config_sha256'].items():
            if sha_file(project/name)!=expected:raise RuntimeError('Pinned configuration mismatch: '+name)
        certificate['source_statistics']={key:stats[key] for key in ('files','lines','nonblank_lines','bytes','declaration_counts_textual','internal_import_edges')}
        if args.stats_only:certificate['status']='statistics_only';return 0
        ensure_system_tools(args.yes);elan=get_elan(work,manifest,env)
        run('Install pinned Lean',[elan,'toolchain','install',manifest['toolchain']],project)
        lean=[elan,'run',manifest['toolchain']]
        version=run('Record compiler version',lean+['lean','--version'],project)
        certificate['compiler_version']=version.read_text().strip()
        run('Fetch pinned dependency cache',lean+['lake','exe','cache','get'],project,allow_failure=True)
        revision=subprocess.check_output(['git','-C',str(project/'.lake/packages/mathlib'),'rev-parse','HEAD'],text=True).strip()
        if revision!=manifest['mathlib_revision']:raise RuntimeError('The mathlib checkout does not match the pinned commit')
        cache=project/'.lake/build';certificate['incremental_cache_reused']=cache.exists() and not args.fresh
        if args.fresh and cache.exists():shutil.rmtree(cache)
        run('Typecheck Main and all proof imports',lean+['lake','--rehash','--no-cache','build','+Main:olean'],project,'typecheck')
        audit=results/'theorem-certificate.lean'
        audit.write_text('import Main\n'+''.join('#check @'+name+'\n#print axioms '+name+'\n' for name in THEOREMS))
        audit_log=run('Check theorem statements and axioms',lean+['lake','env','lean',str(audit)],project,'typecheck')
        text=audit_log.read_text();matches=re.findall(r'depends on axioms:\s*\[([^\]]*)\]',text,re.S)
        if len(matches)+text.count('does not depend on any axioms')!=len(THEOREMS):raise RuntimeError('The axiom audit did not report all five declarations')
        axioms=sorted({name.strip() for group in matches for name in group.split(',') if name.strip()})
        certificate['axioms']=axioms;certificate['additional_axioms']=sorted(set(axioms)-STANDARD_AXIOMS)
        if any('sorryAx' in name for name in axioms):raise RuntimeError('The checked declarations depend on sorryAx; this is not a completed proof')
        after=analyze(project,progress=False)
        if after['source_tree_sha256']!=stats['source_tree_sha256']:raise RuntimeError('Source files changed during verification')
        certificate['status']='passed_with_additional_axioms' if certificate['additional_axioms'] else 'passed'
        print('\nCheck completed:',certificate['status'],flush=True)
        return 0
    except KeyboardInterrupt:
        certificate['status']='interrupted';certificate['error']='Interrupted; rerun the same command to resume the cached build.';return 130
    except Exception as error:
        certificate['status']='failed';certificate['error']=str(error);print('\n'+str(error),file=sys.stderr);return 1
    finally:
        certificate['finished_at']=datetime.now(timezone.utc).isoformat();certificate['wall_seconds']=round(time.monotonic()-began,3)
        certificate['typecheck_cpu_seconds']=round(sum(step['cpu_seconds'] for step in certificate['steps'] if step['kind']=='typecheck'),3)
        certificate['typecheck_cpu_hours']=certificate['typecheck_cpu_seconds']/3600
        save_certificate(output,certificate);print('Certificate:',output,flush=True)


if __name__=='__main__':
    sys.exit(main())
