#!/usr/bin/env python3
"""Verify the archived public evidence index. Python 3.9+, standard library only.

  python3 verify.py
  python3 verify.py --root /path/to/downloaded/evidence/day357
  python3 verify.py --remote-files

The default checks the hosted evidence directory, archive member indexes, citation
ledger and release metadata. --remote-files also streams the original deposited
files and release assets. The publisher's manifest contains SHA-256 digests.
For a separately obtained manifest pass --manifest-sha256 HEX.
"""
import argparse
import csv
import gzip
import hashlib
import io
import time
import zipfile
from urllib.error import URLError
import json
import re
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import quote
from urllib.request import Request, urlopen
BASE='https://getswiftapi.com/evidence/day357/'
def fetch(url):
    return urlopen(Request(url,headers={'User-Agent':'SwiftAPI-public-evidence-verifier/1.0','Accept-Encoding':'identity'}),timeout=60)
def download(url):
    for attempt in range(3):
        try:
            with fetch(url) as response:return response.read()
        except (URLError, TimeoutError, ConnectionError) as error:
            if attempt==2:raise RuntimeError('Could not download '+url) from error
            time.sleep(2**attempt)
def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--root',type=Path)
    parser.add_argument('--remote-files',action='store_true')
    parser.add_argument('--manifest-sha256')
    args=parser.parse_args()
    bundle=None
    if not args.root:
        bundle=zipfile.ZipFile(io.BytesIO(download('https://getswiftapi.com/evidence/day357-replay.zip')))
    def read(name):
        if name.startswith('/') or '..' in Path(name).parts:raise ValueError('Untrusted file path')
        if args.root:return (args.root/name).read_bytes()
        return bundle.read(name)
    manifest=read('SHA256SUMS.txt')
    if bundle and download(BASE+'SHA256SUMS.txt')!=manifest:raise ValueError('Archive and hosted manifest differ')
    if args.manifest_sha256 and hashlib.sha256(manifest).hexdigest()!=args.manifest_sha256:
        raise ValueError('Manifest digest mismatch')
    checks={}
    for line in manifest.decode().splitlines():
        h,name=line.split('  ',1)
        if not re.fullmatch(r'[a-f0-9]{64}',h) or name in checks:raise ValueError('Invalid manifest entry')
        checks[name]=h
    if bundle and sorted(bundle.namelist())!=sorted([*checks,'SHA256SUMS.txt']):raise ValueError('Unexpected archive member list')
    def one(entry):
        name,h=entry
        data=read(name)
        if hashlib.sha256(data).hexdigest()!=h:raise ValueError('Checksum mismatch: '+name)
        if name.endswith('.json.gz'):
            doc=json.loads(gzip.decompress(data))
            if 'files' not in doc or any(len(f)!=3 for f in doc['files']):raise ValueError('Invalid file index '+name)
        return name
    with ThreadPoolExecutor(max_workers=6) as pool:list(pool.map(one,checks.items()))
    catalog=json.loads(read('catalog.json')); archives=json.loads(read('archives.json'))
    pubs=catalog['publications'];repos=catalog['repositories']
    deposits=[f for p in pubs for f in p['files']]
    assets=[f for r in repos for t in r['releases'] for f in t['assets']]
    assert len({p['doi'] for p in pubs})==len(pubs)==44 and len({r['name'] for r in repos})==len(repos)==102
    assert len(deposits)==65 and len(assets)==114
    assert all(re.fullmatch('[a-f0-9]{64}',f['sha256']) for f in deposits+assets)
    known={f['sha256'] for f in deposits+assets}
    for r in repos:
        if r['index']:
            name=r['index'].split('/day357/')[1]
            assert name in checks and r['commit'] and r['fileCount']
    for a in archives:
        assert a['sha256'] in known
        if a.get('index'):assert checks[a['index'].split('/day357/')[1]]==a['indexSha256']
    claims=list(csv.DictReader(io.StringIO(read('claims.csv').decode())))
    assert len(claims)==112 and all(row['source_url'].startswith('https://') and re.fullmatch('[a-f0-9]{64}',row['source_sha256']) for row in claims)
    matrix=json.loads(read('matrix-recount.json'))
    assert sum(matrix['classes'].values())==matrix['completed']==31430
    assert sum(matrix['classes'].get(k,0) for k in ('V0','V1','V2','VU'))==11658
    assert matrix['classes']['V0']+matrix['classes']['V2']==9093 and (matrix['nullVoids'],matrix['controlVoids'],matrix['strictPairs'])==(2505,0,4290)
    gemini=json.loads(read('gemini-replay.txt'))
    assert gemini['verified_provider_responses']==1200 and gemini['verdicts']=={'P1':'PASSED','P2':'FAILED'}
    if args.remote_files:
        downloads={}
        for p in pubs:
            for f in p['files']:
                url='https://zenodo.org/records/'+p['id']+'/files/'+quote(f['name'],safe='')+'?download=1'
                downloads[(url,f['sha256'])]=f['bytes']
        for f in assets:downloads[(f['url'],f['sha256'])]=f['bytes']
        def verify_remote(item):
            (url,h),expected=item
            digest=hashlib.sha256();size=0
            with fetch(url) as response:
                while True:
                    buf=response.read(1048576)
                    if not buf:break
                    digest.update(buf);size+=len(buf)
            if digest.hexdigest()!=h or size!=expected:raise ValueError('Original artifact mismatch: '+url)
        with ThreadPoolExecutor(max_workers=4) as pool:list(pool.map(verify_remote,downloads.items()))
    print(f'PASS: {len(checks)} source-index files; {len(pubs)} DOI records; {len(repos)} repositories; {len(deposits)} deposited files; {len(assets)} release assets; {len(claims)} citation-ledger entries.')
    print('Manifest SHA-256:',hashlib.sha256(manifest).hexdigest())
if __name__=='__main__':main()

