"""Fetch one public artifact with explicit status, type and digest checks."""

import argparse
import hashlib
from pathlib import Path
import urllib.error
import urllib.request


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--url', required=True)
    parser.add_argument('--out', type=Path, required=True)
    parser.add_argument('--sha256', required=True)
    parser.add_argument('--type', required=True)
    arguments = parser.parse_args()
    request = urllib.request.Request(arguments.url, headers={'User-Agent': 'Fieldnotes-Artifact-Reader/1.0', 'Accept': arguments.type})
    try:
        with urllib.request.urlopen(request, timeout=45) as response:
            if response.status != 200:
                raise ValueError(f'HTTP {response.status}; access is not available')
            actual_type = response.headers.get_content_type()
            if actual_type != arguments.type:
                raise ValueError(f'Expected {arguments.type}, received {actual_type}; refusing an error/login page')
            data = response.read()
    except urllib.error.HTTPError as error:
        raise SystemExit(f'HTTP {error.code}: public artifact access failed; no local/private fallback was used.') from error
    actual_hash = hashlib.sha256(data).hexdigest()
    if actual_hash != arguments.sha256:
        raise SystemExit(f'Digest mismatch: expected {arguments.sha256}, received {actual_hash}')
    if arguments.type == 'application/zip' and not data.startswith(b'PK\x03\x04'):
        raise SystemExit('Payload is not a ZIP archive')
    arguments.out.parent.mkdir(parents=True, exist_ok=True)
    arguments.out.write_bytes(data)
    print(f'{actual_hash}  {arguments.out}')


if __name__ == '__main__':
    main()
