"""Fetch public control sources and run only the inspected Agrippa demo script.

Requires Python 3, Node.js, and internet access. The full poem and third-party
implementation are fetched for local verification, not bundled with our report.
The source hash is pinned before any third-party JavaScript is evaluated.
"""
from pathlib import Path
import hashlib
import json
import re
import shutil
import subprocess
import urllib.request

ROOT = Path(__file__).resolve().parent
SOURCES = {
    'agrippa_in_action.html': 'https://agrippa.english.ucsb.edu/wp-content/uploads/images/cracked-code/submissions/files/agrippa_in_action.html',
    'agrippa_memory_plain.bin': 'https://agrippa.english.ucsb.edu/wp-content/uploads/images/emulation/diskimage-analysis/freek/agrippa-poem-extracted-from-diskimage.txt',
}


def main():
    hashes = json.loads((ROOT/'agrippa_source_hashes.json').read_text())
    for name, url in SOURCES.items():
        data = urllib.request.urlopen(url, timeout=30).read()
        assert hashlib.sha256(data).hexdigest() == hashes[name], 'Public source changed: '+name
        (ROOT/name).write_bytes(data)
    html = (ROOT/'agrippa_in_action.html').read_text()
    script = re.findall(r'<script language="javascript">(.*?)</script>', html, re.S)[0]
    # Only the first inline algorithm/demo script, not analytics or other scripts.
    harness = "const fs=require('fs');\nconst document={forms:[{ct:{value:''},pt:{value:''},pt2ct:{},ct2pt:{}}]};\n"
    harness += script
    harness += "\nfuncs[2](); fs.writeFileSync('agrippa_js_plain.bin',Buffer.from(f.pt.value,'latin1')); fs.writeFileSync('agrippa_cipher.bin',Buffer.from(poem.replace(/[^0-9A-F]/g,''),'hex'));\n"
    (ROOT/'agrippa_reference_harness.cjs').write_text(harness)
    node = shutil.which('node')
    if not node:
        raise RuntimeError('Node.js is required for the published reference control')
    subprocess.run([node, str(ROOT/'agrippa_reference_harness.cjs')], cwd=ROOT, check=True, timeout=10)
    print('Pinned control sources prepared; run python3 agrippa_pass.py')


if __name__ == '__main__':
    main()
