"""Download MovieLens 32M from GroupLens and check it. python fetch.py [destination folder]

The archive is not part of this study (the ratings are never copied into it). This script fetches it from the source,
checks the sha256 below, and unpacks it into the destination (default data/downloads/, which .gitignore excludes).
If your system cannot verify the server's certificate chain, download the archive in a browser from SOURCE_URL, put
it at <destination>/ml-32m.zip and run the script again: it checks the file either way and never skips the check.
"""
from __future__ import annotations

import hashlib
import sys
import urllib.request
import zipfile
from pathlib import Path

SOURCE_URL = 'https://files.grouplens.org/datasets/movielens/ml-32m.zip'
SHA256 = 'e4a68655d7386b8f95f2f2424b2ff975dfdd15ffd59e0d864a14dca43e99d6ee'
SIZE = 238_950_008
MEMBER_MD5 = {'ml-32m/ratings.csv': 'cf12b74f9ad4b94a011f079e26d4270a', 'ml-32m/movies.csv': '0df90835c19151f9d819d0822e190797',
              'ml-32m/links.csv': '8f033867bcb4e6be8792b21468b4fa6e', 'ml-32m/tags.csv': '963bf4fa4de6b8901868fddd3eb54567'}


def sha256(path: Path) -> str:
    h = hashlib.sha256()
    with path.open('rb') as f:
        for chunk in iter(lambda: f.read(1 << 20), b''):
            h.update(chunk)
    return h.hexdigest()


def main() -> int:
    dest = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent / 'data' / 'downloads'
    dest.mkdir(parents=True, exist_ok=True)
    archive = dest / 'ml-32m.zip'
    if not archive.exists():
        tmp = archive.with_suffix('.part')
        try:
            with urllib.request.urlopen(SOURCE_URL, timeout=120) as r, tmp.open('wb') as f:
                while chunk := r.read(1 << 20):
                    f.write(chunk)
        except OSError as exc:
            print(f'download failed: {exc}')
            print(f'Download {SOURCE_URL} in a browser, save it as {archive}, and run this script again.')
            print('VERDICT: FAIL (no archive)')
            return 1
        tmp.replace(archive)
    digest = sha256(archive)
    if archive.stat().st_size != SIZE or digest != SHA256:
        print(f'VERDICT: FAIL (archive does not match: {archive.stat().st_size} bytes, sha256 {digest})')
        return 1
    with zipfile.ZipFile(archive) as z:
        for name, md5 in MEMBER_MD5.items():
            if hashlib.md5(z.read(name)).hexdigest() != md5:
                print(f'VERDICT: FAIL ({name} does not match the md5 in the MovieLens README)')
                return 1
        z.extractall(dest)
    print(f'VERDICT: PASS (ml-32m.zip sha256 {SHA256}; unpacked into {dest / "ml-32m"})')
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
