"""One exact optional SDSS download, with declared length and SHA-256; no retry."""
from pathlib import Path
import argparse,hashlib,json,urllib.request

def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--out',type=Path,default=Path('spec-2068-53386-0316.fits'));args=parser.parse_args()
    manifest=json.loads((Path(__file__).resolve().parent/'input-manifest.json').read_text())['sdss']
    if args.out.exists():raise FileExistsError('Refusing to replace an existing file')
    temporary=args.out.with_suffix(args.out.suffix+'.partial');digest=hashlib.sha256();total=0
    if temporary.exists():raise FileExistsError('Retained partial file already exists')
    request=urllib.request.Request(manifest['url'],headers={'User-Agent':'SandboxPhysics-science-tutorial/1'})
    with urllib.request.urlopen(request,timeout=30) as response,temporary.open('xb') as stream:
        declared=response.headers.get('Content-Length')
        if declared is not None and int(declared)!=manifest['bytes']:raise ValueError('Declared length changed; stop for source review')
        while True:
            body=response.read(min(65536,manifest['bytes']-total+1))
            if not body:break
            total+=len(body)
            if total>manifest['bytes']:raise ValueError('Response exceeds fixed input size')
            stream.write(body);digest.update(body)
    if total!=manifest['bytes'] or digest.hexdigest()!=manifest['sha256']:raise ValueError('Fixed source identity mismatch; retained partial is not admitted')
    temporary.rename(args.out);print(json.dumps(dict(path=str(args.out),bytes=total,sha256=digest.hexdigest())))
if __name__=='__main__':main()
