"""Cuenta marcadores estructurales CPG; no ejecuta código ni juzga vulnerabilidades."""
import argparse
import hashlib
import json
from pathlib import Path

p=argparse.ArgumentParser()
p.add_argument('--root',type=Path,required=True);p.add_argument('--graphs',type=Path,required=True)
p.add_argument('--splits',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
p.add_argument('--long-threshold',type=int,default=200);p.add_argument('--inspect-index',type=int)
a=p.parse_args()
if a.long_threshold<0:p.error('El umbral debe ser no negativo')
manifest=json.loads((a.graphs/'manifest.json').read_text(encoding='utf-8'))
assignment=json.loads(a.splits.read_text(encoding='utf-8'))
if not manifest.get('complete') or manifest.get('failed_batches'):raise ValueError('Extracción incompleta')
labels=[];lengths=[];sources={}
for part in ('train','valid','test'):
    path=a.root/f'primevul_{part}.jsonl'
    with path.open('rb') as stream:sources[path.name]=hashlib.file_digest(stream,'sha256').hexdigest()
    with path.open(encoding='utf-8') as stream:
        for line in stream:
            row=json.loads(line);labels.append(int(row['target']));lengths.append(len(row['func']))
if sources!=manifest['source_sha256'] or sources!=assignment['source_sha256']:raise ValueError('Fuentes incompatibles')
structural={'BLOCK','METHOD','METHOD_PARAMETER_IN','METHOD_PARAMETER_OUT','METHOD_RETURN'}
flags={};hashes={}
for path in sorted(a.graphs.glob('*.jsonl')):
    digest=hashlib.sha256()
    with path.open('rb') as stream:
        for line in stream:
            digest.update(line);graph=json.loads(line);i=int(graph['index'])
            if not 0<=i<len(labels) or i in flags:raise ValueError('Índice duplicado o fuera de rango')
            kinds={node['kind'] for node in graph['nodes']}
            empty=any(node['kind']=='BLOCK' and node.get('code','').strip()=='<empty>' for node in graph['nodes'])
            only=bool(kinds) and kinds<=structural
            flags[i]={'empty_block_marker':empty,'only_structural_kinds':only,
                      'only_structural_and_source_over_threshold':only and lengths[i]>a.long_threshold}
    hashes[path.name]=digest.hexdigest()
if hashes!=manifest['graph_sha256']:raise ValueError('Hashes de grafos incompatibles')
names=('empty_block_marker','only_structural_kinds','only_structural_and_source_over_threshold')
total={'covered':len(flags),**{name:sum(v[name] for v in flags.values()) for name in names}}
partitions={}
for partition,split in assignment['splits'].items():
    if len(split)!=len(labels):raise ValueError('Dimensión de partición incorrecta')
    partitions[partition]={}
    for subset in ('train','valid','test'):
        partitions[partition][subset]={}
        for label in (0,1):
            ids=[i for i in flags if split[i]==subset and labels[i]==label]
            partitions[partition][subset][str(label)]={'covered':len(ids),**{name:sum(flags[i][name] for i in ids) for name in names}}
case=None
if a.inspect_index is not None:
    if a.inspect_index not in flags:raise ValueError('El índice solicitado no tiene grafo')
    case={'index':a.inspect_index,'source_length':lengths[a.inspect_index],**flags[a.inspect_index]}
out={'source_sha256':sources,'graph_sha256':hashes,
     'graph_manifest_sha256':hashlib.sha256((a.graphs/'manifest.json').read_bytes()).hexdigest(),
     'splits_sha256':hashlib.sha256(a.splits.read_bytes()).hexdigest(),
     'script_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
     'long_threshold_characters':a.long_threshold,
     'total':total,'partitions':partitions,'inspected_case':case,
     'definition':'Solo estructura: tipos BLOCK, METHOD, METHOD_PARAMETER_IN, METHOD_PARAMETER_OUT o METHOD_RETURN.',
     'note':'Marcadores y longitud son indicadores descriptivos; no prueban por sí solos fallo del parser ni ausencia de vulnerabilidad.'}
a.output.write_text(json.dumps(out,indent=2,ensure_ascii=False),encoding='utf-8')
print(json.dumps({'total':total,'inspected_case':case},ensure_ascii=False),flush=True)
