"""Lectura por lotes de CPG preprocesados, con integridad y offsets comprobados."""
import hashlib
import json
from pathlib import Path
import numpy as np
import torch
from torch_geometric.data import Data

FILES=('x.bin','edges.bin','types.bin','index.jsonl')
def sha256(path):
    with Path(path).open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()

class BinaryStore:
    def __init__(self,directory,identity):
        self.directory=Path(directory)
        self.manifest=json.loads((self.directory/'manifest.json').read_text(encoding='utf-8'))
        if not self.manifest.get('complete') or self.manifest['identity']!=identity:
            raise ValueError('Cache de otra fuente o incompleta')
        for name in FILES:
            path=self.directory/name;info=self.manifest['files'][name]
            if path.stat().st_size!=info['bytes'] or sha256(path)!=info['sha256']:
                raise ValueError(f'Cache alterada: {name}')
        with (self.directory/'index.jsonl').open(encoding='utf-8') as stream:
            records=[json.loads(line) for line in stream]
        self.records={int(r['index']):r for r in records}
        if len(self.records)!=len(records) or len(records)!=self.manifest['graphs']:
            raise ValueError('Índices duplicados o incompletos')
        previous=-1;x_offset=e_offset=t_offset=0
        for record in records:
            index,n,e=int(record['index']),int(record['nodes']),int(record['edges'])
            if (index<=previous or n<1 or e<0 or record['label'] not in (0,1)
                    or record['x_offset']!=x_offset or record['edges_offset']!=e_offset or record['types_offset']!=t_offset):
                raise ValueError('Índice, dimensiones u offsets inválidos')
            previous=index;x_offset+=n*9*8;e_offset+=2*e*8;t_offset+=e*8
        if (x_offset!=self.manifest['files']['x.bin']['bytes']
                or e_offset!=self.manifest['files']['edges.bin']['bytes']
                or t_offset!=self.manifest['files']['types.bin']['bytes']):
            raise ValueError('Offsets y tamaños no coinciden')
        self.maps={name:np.memmap(self.directory/name,dtype='<i8',mode='r') for name in FILES[:3]}
    def get(self,index):
        record=self.records[index];nodes=int(record['nodes']);edges=int(record['edges'])
        def read(name,offset,count,shape):
            if offset%8:raise ValueError('Offset desalineado')
            start=offset//8;values=self.maps[name][start:start+count]
            if len(values)!=count:raise ValueError('Datos binarios truncados')
            return torch.from_numpy(np.array(values,copy=True).reshape(shape))
        return Data(x=read('x.bin',record['x_offset'],nodes*9,(nodes,9)),
                    edge_index=read('edges.bin',record['edges_offset'],2*edges,(2,edges)),
                    edge_type=read('types.bin',record['types_offset'],edges,(edges,)),
                    y=torch.tensor([record['label']],dtype=torch.float32),idx=torch.tensor([index]))

class BinaryDataset(torch.utils.data.Dataset):
    def __init__(self,store,indices):self.store,self.indices=store,list(indices)
    def __len__(self):return len(self.indices)
    def __getitem__(self,index):return self.store.get(self.indices[index])
