"""Verify a Proof of Foresight round without trusting Where in Russia.
  python verify.py ROUND_DIR            (a folder with commitment.json and what the round published next to it)
Checks, each reported on its own:
  1 hash        commitment.json hashes to commitment.sha256
  2 timestamps  every RFC 3161 token in tsr/ covers these bytes (needs openssl; FreeTSA's CA files ship with the round)
  3 rekor       the Sigstore bundle verifies against the one-time key (needs cosign)
  4 attestation the platform's Ed25519 signature over the hash (needs the 'cryptography' package and network access)
  5 replication every forecast is recomputed from inputs.csv.gz with the code in this folder
Integrity is not accuracy: a round can pass every check here and still forecast badly (see the scores)."""
import urllib.error, base64, csv, gzip, hashlib, json, os, shutil, subprocess, sys, tempfile, urllib.request
HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE)

def run(cmd):
    p = subprocess.run(cmd, capture_output=True, text=True); return p.returncode, (p.stdout + p.stderr).strip()

def main(d):
    res = {}
    body = open(os.path.join(d, 'commitment.json'), 'rb').read(); h = hashlib.sha256(body).hexdigest()
    want = open(os.path.join(d, 'commitment.sha256')).read().split()[0]
    res['hash'] = {'ok': h == want, 'sha256': h}
    c = json.loads(body)
    ts = []
    tdir = os.path.join(d, 'tsr')
    for f in sorted(os.listdir(tdir)) if os.path.isdir(tdir) else []:
        if not f.endswith('.tsr'): continue
        name = f[:-4]; ca = os.path.join(tdir, f'{name}-ca.pem'); unt = os.path.join(tdir, f'{name}-tsa.pem')
        if not shutil.which('openssl'): ts.append({'tsa': name, 'ok': None, 'note': 'openssl not installed'}); continue
        cmd = ['openssl', 'ts', '-verify', '-data', os.path.join(d, 'commitment.json'), '-in', os.path.join(tdir, f)]
        cmd += ['-CAfile', ca] if os.path.exists(ca) else ['-CApath', '/etc/ssl/certs']
        if os.path.exists(unt): cmd += ['-untrusted', unt]
        rc, out = run(cmd); _, txt = run(['openssl', 'ts', '-reply', '-in', os.path.join(tdir, f), '-text'])
        gt = next((l.split(':', 1)[1].strip() for l in txt.splitlines() if l.startswith('Time stamp:')), None)
        ts.append({'tsa': name, 'ok': rc == 0 and 'Verification: OK' in out, 'time': gt})
    res['timestamps'] = ts
    rb, pub = os.path.join(d, 'rekor.bundle'), os.path.join(d, 'cosign.pub')
    if os.path.exists(rb) and shutil.which('cosign'):
        rc, out = run(['cosign', 'verify-blob', '--key', pub, '--bundle', rb, os.path.join(d, 'commitment.json')]); res['rekor'] = {'ok': rc == 0}
    else: res['rekor'] = {'ok': None, 'note': 'cosign not installed or no bundle'}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        b64 = lambda s: base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
        ua = {'User-Agent': 'wir-foresight-verify/1.0 (+https://whereinrussia.com/foresight/)'}
        att = json.load(urllib.request.urlopen(urllib.request.Request(f"https://whereinrussia.com/api/foresight/attest?round={c['round']}", headers=ua), timeout=30))
        jwks = json.load(urllib.request.urlopen(urllib.request.Request(c['issuer']['jwks'], headers=ua), timeout=30))
        hd, pl, sg = att['jws'].split('.'); kid = json.loads(b64(hd)).get('kid'); claim = json.loads(b64(pl))
        k = next(k for k in jwks['keys'] if k.get('kid') == kid)
        Ed25519PublicKey.from_public_bytes(b64(k['x'])).verify(b64(sg), f'{hd}.{pl}'.encode())
        res['attestation'] = {'ok': claim.get('sha256') == h and claim.get('round') == c['round'], 'kid': kid}
    except ImportError: res['attestation'] = {'ok': None, 'note': "install 'cryptography' to check the Ed25519 attestation"}
    except urllib.error.URLError as e: res['attestation'] = {'ok': None, 'note': f'not reachable: {e}'[:200]}
    except Exception as e: res['attestation'] = {'ok': False, 'note': f'{type(e).__name__}: {e}'[:200]}
    # 5 replication with the round's own frozen code (rounds/<R>/code/) when it is published, else with this folder;
    #   the code files are first checked against the SHA-256 values fixed in the commitment
    cdir = os.path.join(d, 'code') if os.path.isdir(os.path.join(d, 'code')) else HERE
    res['code'] = {'folder': 'round' if cdir != HERE else 'verifier', 'files': {f: (hashlib.sha256(open(os.path.join(cdir, f), 'rb').read()).hexdigest() == v) if os.path.exists(os.path.join(cdir, f)) else None
                                                                              for f, v in c['code']['sha256'].items()}}
    pp = os.path.join(cdir, 'PROTOCOL.md')
    res['code']['files']['PROTOCOL.md'] = (hashlib.sha256(open(pp, 'rb').read()).hexdigest() == c['protocol']['sha256']) if os.path.exists(pp) else None
    res['code']['ok'] = all(x is not False for x in res['code']['files'].values()) if cdir != HERE else None
    sys.path.insert(0, cdir)
    for m in ('commit', 'model', 'rosstat', 'match', 'regions'): sys.modules.pop(m, None)
    import commit as C
    H = {}
    with gzip.open(os.path.join(d, 'inputs.csv.gz'), 'rt', encoding='utf-8') as f:
        for r in csv.DictReader(f): H[(r['period'], r['region'], r['series'])] = float(r['value'])
    with tempfile.TemporaryDirectory() as t:
        r2, _ = C.build('sim-replicate', H, sorted({k[0] for k in H}), c['information_set']['file'], t)
    key = lambda f: (f['u'], f['s'], f['h'])
    a = {key(f): f for f in c['forecasts']}; b = {key(f): f for f in r2['forecasts']}
    diff = [k for k in a if k not in b or any(abs(x - y) > 0.011 for x, y in zip([a[k]['b0'], a[k]['b1']] + a[k]['m1'], [b[k]['b0'], b[k]['b1']] + b[k]['m1']))]
    res['replication'] = {'ok': not diff and len(a) == len(b), 'forecasts': len(a), 'differences': len(diff)}
    return res

if __name__ == '__main__':
    r = main(sys.argv[1] if len(sys.argv) > 1 else '.')
    print(json.dumps(r, indent=1, ensure_ascii=False))
    sys.exit(0 if all(v.get('ok') is not False for k, v in r.items() if isinstance(v, dict)) and all(t.get('ok') is not False for t in r['timestamps']) else 1)
