#!/usr/bin/env python3
"""Download the public data archive and verify every SHA-256. No app/account required.

MIT License — Copyright (c) 2026 MiniLabs.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to
do so, subject to the following conditions: The above copyright notice and
this permission notice shall be included in all copies or substantial portions
of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import hashlib
import json
from pathlib import Path
import sys
from urllib.parse import urljoin
from urllib.request import Request, urlopen


def open_public(url, timeout):
    # Use an identifiable compatible client; generic Python user agents can be
    # rejected by hosting security despite the files being publicly accessible.
    return urlopen(Request(url, headers={'User-Agent': 'Mozilla/5.0 DictionaryDataDownloader/1.0'}), timeout=timeout)


def download(manifest_url):
    with open_public(manifest_url, timeout=60) as response:
        manifest = json.load(response)
    final = Path('dictionary-data-' + manifest['release'] + '.tar.gz')
    temporary = final.with_suffix('.partial')
    if final.exists() or temporary.exists():
        raise FileExistsError('Move the existing archive or partial file before downloading again.')
    total = hashlib.sha256()
    try:
        with temporary.open('xb') as out:
            for part in manifest['parts']:
                digest, size = hashlib.sha256(), 0
                with open_public(urljoin(manifest_url, part['name']), timeout=120) as response:
                    while chunk := response.read(1024 * 1024):
                        digest.update(chunk); total.update(chunk); out.write(chunk); size += len(chunk)
                if size != part['bytes'] or digest.hexdigest() != part['sha256']:
                    raise ValueError('Part verification failed: ' + part['name'])
        if total.hexdigest() != manifest['archiveSHA256']:
            raise ValueError('Archive verification failed')
        temporary.replace(final)
    except BaseException:
        temporary.unlink(missing_ok=True)
        raise
    print(str(final))


if __name__ == '__main__':
    download(sys.argv[1])
