"""Lossless candidate/alias graph; relations never assert biological identity."""
import hashlib,json
import numpy as np

def mask_digest(mask):
    """Hash shape and exact binary pixels in canonical big-endian bit order."""
    if not isinstance(mask,np.ndarray) or mask.ndim!=2 or mask.dtype!=np.bool_:
        raise ValueError('Expected a two-dimensional boolean mask')
    h=hashlib.sha256();h.update(f'{mask.shape[0]}x{mask.shape[1]}:'.encode('ascii'));h.update(np.packbits(mask.ravel(),bitorder='big').tobytes());return h.hexdigest()

def build_graph(candidates,relations,plane_count,provenance):
    """Build a serializable graph while preserving every candidate ID.

    Edges mean only that an algorithm suppressed ``candidate`` in favor of
    ``kept`` at the named stage. They do not mean same or different specimen.
    Candidates retain source and plane, including equal masks with distinct
    IDs. Cross-stage cycles and repeated pair relationships remain explicit.
    Masks must be retained separately and can be checked with ``mask_digest``.
    """
    if type(plane_count) is not int or plane_count<=0 or not isinstance(provenance,dict):raise ValueError('Invalid graph metadata')
    nodes=[];ids=set();shape=None
    for c in candidates:
        if not isinstance(c,dict):raise ValueError('Invalid candidate')
        ident=c.get('id');z=c.get('z');source=c.get('source');mask=c.get('mask');metadata=c.get('metadata',{})
        if not isinstance(ident,str) or not ident or ident in ids or type(z) is not int or not 0<=z<plane_count or not isinstance(source,str) or not source or not isinstance(metadata,dict):raise ValueError('Invalid candidate metadata')
        digest=mask_digest(mask)
        if shape is None:shape=mask.shape
        if mask.shape!=shape:raise ValueError('Candidate shapes differ')
        ids.add(ident);nodes.append({'id':ident,'z':z,'source':source,'area':int(mask.sum()),'mask_sha256':digest,'metadata':metadata})
    edges=[]
    for r in relations:
        if not isinstance(r,dict) or not isinstance(r.get('stage'),str) or not r['stage'] or r.get('candidate') not in ids or r.get('kept') not in ids or r['candidate']==r['kept']:
            raise ValueError('Invalid or unresolved relation')
        edges.append({'stage':r['stage'],'candidate':r['candidate'],'kept':r['kept'],'semantics':'suppressed_by_algorithm_not_identity'})
    result={'format':'diatom-proposal-graph-v1','plane_count':plane_count,'mask_shape':list(shape) if shape is not None else None,'provenance':provenance,'candidates':nodes,'relations':edges,'warning':'Relations record algorithmic suppression only. No relation establishes that candidates represent one or multiple organisms; unlisted candidates are not negatives.'}
    try:json.dumps(result,allow_nan=False)
    except (TypeError,ValueError) as e:raise ValueError('Metadata must be finite JSON data') from e
    return result

def pack_candidates(candidates):
    """Pack every source mask in candidate order, without deduplication."""
    if not candidates:return {'ids':np.array([],dtype=str),'shape':np.array([0,0,0],dtype='int64'),'bits':np.array([],dtype='uint8')}
    if any(not isinstance(q.get('mask'),np.ndarray) or q['mask'].ndim!=2 or q['mask'].dtype!=np.bool_ for q in candidates):raise ValueError('Invalid masks')
    shapes=[q['mask'].shape for q in candidates]
    if any(s!=shapes[0] for s in shapes):raise ValueError('Invalid masks')
    return {'ids':np.array([q['id'] for q in candidates]),'shape':np.array([len(candidates),*shapes[0]],dtype='int64'),'bits':np.packbits(np.stack([q['mask'] for q in candidates]).ravel(),bitorder='big')}

def unpack_candidates(archive):
    """Restore masks keyed by IDs; reject malformed shapes and duplicate IDs."""
    shape=tuple(int(v) for v in archive['shape']);ids=[str(v) for v in archive['ids']];bits=np.asarray(archive['bits'])
    if len(shape)!=3 or any(v<0 for v in shape) or len(ids)!=shape[0] or len(set(ids))!=len(ids) or bits.ndim!=1 or bits.dtype!=np.uint8:raise ValueError('Invalid packed archive')
    n=int(np.prod(shape));expected=(n+7)//8
    if len(bits)!=expected or (n and (shape[1]==0 or shape[2]==0)):raise ValueError('Invalid packed length')
    if n%8 and int(bits[-1]) & ((1<<(8-n%8))-1):raise ValueError('Nonzero padding bits')
    masks=np.unpackbits(bits,bitorder='big')[:n].reshape(shape).astype(bool)
    return {ident:mask for ident,mask in zip(ids,masks)}
