"""Descarga los JSONL de PrimeVul v0.1 desde un espejo fijado y calcula SHA256."""
import argparse, hashlib, json, urllib.request
from pathlib import Path
REV='4fd7158322872d711e90f091dbd8673ef32cb1be'
SIZES={'train':470918175,'valid':63564497,'test':66064689}
EXPECTED={'train':'5cadee7f3383124cc26ef6e67c8dd76c321e5461c94bef399a2f03a28767e6f5',
          'valid':'7f0b4d05b063c20d5cf57478128538b8c0c36354e8def7f2d4febe6773b9dc7c',
          'test':'c9dcab5ee897da36eccf0dbb3b510de2dab66a7dec681af29a7a28c8a53331c4'}
p=argparse.ArgumentParser(); p.add_argument('--root',type=Path,default=Path.home()/'.cache'/'oryon'/'datasets'/'PrimeVul'); a=p.parse_args(); a.root.mkdir(parents=True,exist_ok=True)
manifest={'source':'https://huggingface.co/datasets/colin/PrimeVul','revision':REV,'files':{}}
for part,size in SIZES.items():
    name=f'primevul_{part}.jsonl'; path=a.root/name; partial=path.with_suffix('.jsonl.partial'); url=f'https://huggingface.co/datasets/colin/PrimeVul/resolve/{REV}/{name}'
    if not path.exists() or path.stat().st_size!=size:
        if path.exists() and not partial.exists(): path.replace(partial)
        offset=partial.stat().st_size if partial.exists() else 0
        if offset>=size: raise ValueError(f'Archivo parcial incompatible: {partial}')
        request=urllib.request.Request(url,headers={'Range':f'bytes={offset}-'} if offset else {})
        with urllib.request.urlopen(request,timeout=120) as response:
            append=offset>0 and response.status==206 and response.headers.get('Content-Range','').startswith(f'bytes {offset}-')
            with partial.open('ab' if append else 'wb') as out:
                while data:=response.read(1024*1024): out.write(data)
        if partial.stat().st_size!=size: raise ValueError(f'Tamaño inesperado {partial}: {partial.stat().st_size} != {size}')
        partial.replace(path)
    with path.open('rb') as stream: digest=hashlib.file_digest(stream,'sha256').hexdigest()
    if digest!=EXPECTED[part]: raise ValueError(f'SHA256 distinto del publicado para {name}: {digest}')
    manifest['files'][name]={'bytes':size,'sha256':digest}; print(name,size,digest,flush=True)
(a.root/'manifest.json').write_text(json.dumps(manifest,indent=2),encoding='utf-8')
