"""Download and verify the full audit recording from the public static site.

Usage: python download_recording.py https://dex-rubik-cube.yanjieze.com recording
Only the Python standard library is required.
"""
import argparse
import gzip
import hashlib
import json
from pathlib import Path
from urllib.parse import urljoin, urlsplit
from urllib.request import Request, urlopen


def download(base, output):
    output = output.resolve()
    output.mkdir(parents=True, exist_ok=True)
    origin = urlsplit(base)

    def fetch(path):
        url = urljoin(base, path)
        target = urlsplit(url)
        if (target.scheme, target.netloc) != (origin.scheme, origin.netloc):
            raise ValueError('Archive link must stay on the selected site')
        request=Request(url,headers={'User-Agent':'DexRubiksCube-Replay/1.0'})
        with urlopen(request, timeout=120) as response:
            return response.read()

    manifest = json.loads(fetch('/data/artifacts.json'))
    for item in manifest['files']:
        destination = (output / item['name']).resolve()
        if not destination.is_relative_to(output):
            raise ValueError('Unsafe archive filename')
        if destination.exists() and hashlib.sha256(destination.read_bytes()).hexdigest() == item['sha256']:
            continue
        parts = []
        for part in item['parts']:
            content = fetch(part['url'])
            if len(content) != part['bytes'] or hashlib.sha256(content).hexdigest() != part['sha256']:
                raise ValueError('Download integrity check failed: ' + part['url'])
            parts.append(content)
        content = b''.join(parts)
        if item['encoding'] == 'gzip':
            content = gzip.decompress(content)
        elif item['encoding'] != 'identity':
            raise ValueError('Unknown archive encoding')
        if len(content) != item['bytes'] or hashlib.sha256(content).hexdigest() != item['sha256']:
            raise ValueError('Reconstructed file hash mismatch: ' + item['name'])
        destination.parent.mkdir(parents=True, exist_ok=True)
        destination.write_bytes(content)
        print(item['name'], flush=True)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('site_url')
    parser.add_argument('output', type=Path)
    args = parser.parse_args()
    download(args.site_url, args.output)
