"""Download the selected upstream materials for a released film. Python 3.11+."""
import argparse
import hashlib
import json
import tempfile
from pathlib import Path, PurePosixPath
from urllib.parse import urlsplit
from urllib.request import urlopen


def fetch(record_url, destination):
    origin = urlsplit(record_url)
    if origin.scheme not in ('https','http') or not origin.hostname or origin.username or origin.password:
        raise ValueError('Give the film record’s HTTP or HTTPS address.')
    if destination.exists():
        raise ValueError('Choose a new output directory.')
    destination.parent.mkdir(parents=True,exist_ok=True)
    with urlopen(record_url,timeout=60) as response:
        record = json.load(response)
    if record.get('status') != 'released':
        raise ValueError('Expected a release record.')
    with tempfile.TemporaryDirectory(dir=destination.parent) as temp:
        root = Path(temp)/'sources'
        root.mkdir()
        for item in record['materials']:
            url = item['url']
            path = PurePosixPath(url)
            if str(path) != url or path.parts[:2] not in (('/','assets'),('/','kit')) or '..' in path.parts:
                raise ValueError('Unexpected source path: '+url)
            target = root.joinpath(*path.parts[1:])
            target.parent.mkdir(parents=True,exist_ok=True)
            sha = hashlib.sha256()
            with urlopen(f'{origin.scheme}://{origin.netloc}'+url,timeout=120) as response, target.open('xb') as disk:
                while chunk := response.read(1024*1024):
                    disk.write(chunk)
                    sha.update(chunk)
            if sha.hexdigest() != item['sha256']:
                raise ValueError('Source checksum differs: '+url)
        (root/'record.json').write_text(json.dumps(record,ensure_ascii=False,indent=2)+'\n')
        root.rename(destination)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('record_url')
    parser.add_argument('new_directory',type=Path)
    args = parser.parse_args()
    fetch(args.record_url,args.new_directory)
