"""Cache binaria CPG incremental con tensores int64 mapeables y hashes."""
import hashlib
import json
import os
import ctypes
from ctypes import wintypes
from pathlib import Path
import time
import numpy as np
import psutil
import torch
from torch_geometric.data import Data

FILES=('x.bin','edges.bin','types.bin','index.jsonl')
class MemoryStatus(ctypes.Structure):
    _fields_=[('dwLength',wintypes.DWORD),('dwMemoryLoad',wintypes.DWORD),
              ('ullTotalPhys',ctypes.c_ulonglong),('ullAvailPhys',ctypes.c_ulonglong),
              ('ullTotalPageFile',ctypes.c_ulonglong),('ullAvailPageFile',ctypes.c_ulonglong),
              ('ullTotalVirtual',ctypes.c_ulonglong),('ullAvailVirtual',ctypes.c_ulonglong),
              ('ullAvailExtendedVirtual',ctypes.c_ulonglong)]
def available_commit():
    if os.name=='nt':
        status=MemoryStatus();status.dwLength=ctypes.sizeof(status)
        if not ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):raise ctypes.WinError()
        return status.ullAvailPageFile
    meminfo=Path('/proc/meminfo')
    if meminfo.is_file():
        fields={line.split(':',1)[0]:int(line.split(':',1)[1].strip().split()[0])*1024
                for line in meminfo.read_text().splitlines() if ':' in line and line.split(':',1)[1].strip().split()[0].isdigit()}
        if 'CommitLimit' in fields and 'Committed_AS' in fields:return max(0,fields['CommitLimit']-fields['Committed_AS'])
    return psutil.virtual_memory().available
def process_memory(proc):
    info=proc.memory_info()
    return getattr(info,'private',info.rss)
def digest_prefix(path, length):
    h=hashlib.sha256();remaining=length
    with path.open('rb') as stream:
        while remaining:
            chunk=stream.read(min(1024*1024,remaining))
            if not chunk: raise ValueError(f'Archivo truncado: {path}')
            h.update(chunk);remaining-=len(chunk)
    return h
def atomic_json(path, data):
    temporary=path.with_name(path.name+'.tmp')
    temporary.write_text(json.dumps(data,indent=2,ensure_ascii=False),encoding='utf-8')
    os.replace(temporary,path)

def build_cache(store,indices,directory,identity,checkpoint_every=100,stop_after=None):
    """Convierte en orden fijo; reanuda solo prefijos con longitud/hash válidos."""
    directory=Path(directory);directory.mkdir(parents=True,exist_ok=True)
    indices=list(indices)
    if indices!=sorted(indices) or len(indices)!=len(set(indices)):raise ValueError('Índices no únicos u ordenados')
    if set(indices)!=set(store.locations):raise ValueError('Índices distintos del almacén fuente')
    manifest_path=directory/'manifest.json';progress_path=directory/'progress.json'
    if manifest_path.exists():raise ValueError('La cache ya está terminada; verificar antes de usar')
    if progress_path.exists():
        progress=json.loads(progress_path.read_text(encoding='utf-8'))
        if progress['identity']!=identity or progress['total']!=len(indices):raise ValueError('Progreso de otra conversión')
        completed=progress['completed'];hashers={}
        for name in FILES:
            path=directory/name;length=progress['files'][name]['bytes']
            h=digest_prefix(path,length)
            if h.hexdigest()!=progress['files'][name]['sha256']:raise ValueError(f'Prefijo alterado: {name}')
            with path.open('r+b') as stream:stream.truncate(length)
            hashers[name]=h
    else:
        if any((directory/name).exists() for name in FILES):raise ValueError('Archivos parciales sin progreso verificable')
        completed=0;hashers={name:hashlib.sha256() for name in FILES}
        for name in FILES:(directory/name).touch(exist_ok=False)
    streams={name:(directory/name).open('ab') for name in FILES}
    proc=psutil.Process();peak_private=max(process_memory(proc),progress.get('peak_private_bytes',0) if completed else 0)
    minimum_commit=min(available_commit(),progress.get('minimum_global_commit_bytes',2**63) if completed else 2**63)
    started=time.perf_counter()
    def checkpoint(count):
        nonlocal minimum_commit
        for stream in streams.values():stream.flush();os.fsync(stream.fileno())
        minimum_commit=min(minimum_commit,available_commit())
        data={'identity':identity,'total':len(indices),'completed':count,
              'peak_private_bytes':peak_private,'minimum_global_commit_bytes':minimum_commit,
              'files':{name:{'bytes':streams[name].tell(),'sha256':hashers[name].hexdigest()} for name in FILES}}
        atomic_json(progress_path,data)
        return data
    try:
        if completed==0:checkpoint(0)
        for position in range(completed,len(indices)):
            index=indices[position];data=store.get(index)
            n=int(data.x.shape[0]);e=int(data.edge_index.shape[1])
            if data.x.dtype!=torch.int64 or data.edge_index.dtype!=torch.int64 or data.edge_type.dtype!=torch.int64:
                raise ValueError('Dtype inesperado en grafo')
            if data.x.shape!=(n,9) or data.edge_index.shape!=(2,e) or data.edge_type.shape!=(e,):
                raise ValueError('Dimensión inesperada en grafo')
            record={'index':index,'nodes':n,'edges':e,'label':int(data.y.item()),
                    'x_offset':streams['x.bin'].tell(),'edges_offset':streams['edges.bin'].tell(),
                    'types_offset':streams['types.bin'].tell()}
            blobs={'x.bin':data.x.contiguous().numpy().astype('<i8',copy=False).tobytes(),
                   'edges.bin':data.edge_index.contiguous().numpy().astype('<i8',copy=False).tobytes(),
                   'types.bin':data.edge_type.contiguous().numpy().astype('<i8',copy=False).tobytes(),
                   'index.jsonl':(json.dumps(record,separators=(',',':'))+'\n').encode('utf-8')}
            for name,blob in blobs.items():streams[name].write(blob);hashers[name].update(blob)
            peak_private=max(peak_private,process_memory(proc))
            done=position+1
            if done%checkpoint_every==0 or done==len(indices) or (stop_after is not None and done>=stop_after):
                progress=checkpoint(done)
                print(json.dumps({'converted':done,'total':len(indices),'process_memory_bytes':process_memory(proc),
                                  'minimum_global_commit_bytes':minimum_commit},ensure_ascii=False),flush=True)
            if stop_after is not None and done>=stop_after:
                return {'status':'interrupted_for_fixture','completed':done}
        progress=checkpoint(len(indices))
        result={'complete':True,'identity':identity,'graphs':len(indices),'files':progress['files'],
                'build_seconds_excluding_index':time.perf_counter()-started,'peak_private_bytes':peak_private,
                'minimum_global_commit_bytes':minimum_commit,
                'format':'int64 little-endian contiguo por grafo; offsets en bytes',
                'memory_method':'compromiso privado Windows; RSS en otros sistemas',
                'global_memory_method':'commit disponible Windows/Linux; física disponible si no hay dato de commit',
                'note':'Medición de conversión, no incluye activaciones ni gradientes de la GNN.'}
        atomic_json(manifest_path,result)
        return result
    finally:
        for stream in streams.values():stream.close()

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['complete'] or self.manifest['identity']!=identity:raise ValueError('Cache de otra fuente')
        for name in FILES:
            path=self.directory/name;info=self.manifest['files'][name]
            if path.stat().st_size!=info['bytes'] or digest_prefix(path,info['bytes']).hexdigest()!=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')
        self.maps={name:np.memmap(self.directory/name,dtype='<i8',mode='r') for name in FILES[:3]}
    def get(self,index):
        r=self.records[index];n=r['nodes'];e=r['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))
        x=read('x.bin',r['x_offset'],n*9,(n,9))
        edge_index=read('edges.bin',r['edges_offset'],2*e,(2,e))
        edge_type=read('types.bin',r['types_offset'],e,(e,))
        return Data(x=x,edge_index=edge_index,edge_type=edge_type,
                    y=torch.tensor([r['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])
