"""Convierte GraphML `joern-export --repr all` en grafos por función.
Los archivos de entrada se nombran `<índice>.c` o `<índice>.cpp`, con índice del corpus concatenado.
Solo toma funciones no externas con AST y conserva AST, CFG y REACHING_DEF
entre sus descendientes AST. Reporta ausencia y ambigüedad: no las oculta.
"""
import argparse, collections, hashlib, json, re, xml.etree.ElementTree as ET
from pathlib import Path
p=argparse.ArgumentParser();p.add_argument('graphml',type=Path);p.add_argument('--output',type=Path,default=Path('graphs.jsonl'));a=p.parse_args()
ns={'g':'http://graphml.graphdrawing.org/xmlns'}; root=ET.parse(a.graphml).getroot(); nodes={}; methods=[]
for node in root.findall('.//g:node',ns):
    data={x.get('key'):x.text or '' for x in node.findall('g:data',ns)}; kind=data.get('labelV',''); prefix=f'node__{kind}__'
    props={k[len(prefix):]:v for k,v in data.items() if k.startswith(prefix)}
    nodes[node.get('id')]={'kind':kind,'props':props}
    if kind=='METHOD' and props.get('IS_EXTERNAL')=='false' and props.get('NAME')!='<global>':
        m=re.search(r'(?:^|[\\/])(\d+)\.(?:c|cpp)$',props.get('FILENAME',''))
        if m:methods.append((int(m.group(1)),node.get('id')))
edges=[]; children=collections.defaultdict(list); outgoing=collections.defaultdict(list)
for edge in root.findall('.//g:edge',ns):
    data={x.get('key'):x.text or '' for x in edge.findall('g:data',ns)}; label=data.get('labelE','')
    if label in ('AST','CFG','REACHING_DEF'):
        s,t=edge.get('source'),edge.get('target');edges.append((s,t,label));outgoing[s].append((len(edges)-1,s,t,label))
        if label=='AST':children[s].append(t)
counts=collections.Counter(index for index,_ in methods); emitted=0; a.output.parent.mkdir(parents=True,exist_ok=True)
with a.output.open('w',encoding='utf-8') as out:
    for index,method in methods:
        if counts[index]!=1:continue
        selected=set(); todo=[method]
        while todo:
            v=todo.pop()
            if v in selected:continue
            selected.add(v);todo.extend(children[v])
        order=sorted(selected,key=int); mapping={v:i for i,v in enumerate(order)}
        graph={'index':index,'source_ext':Path(nodes[method]['props']['FILENAME']).suffix,'nodes':[{'kind':nodes[v]['kind'],'code':'' if nodes[v]['kind']=='METHOD' else nodes[v]['props'].get('CODE','')} for v in order],
               'edges':[[mapping[s],mapping[t],kind] for _,s,t,kind in sorted((item for v in selected for item in outgoing[v]),key=lambda item:item[0]) if t in selected]}
        out.write(json.dumps(graph,ensure_ascii=False)+'\n');emitted+=1
print(json.dumps({'input_sha256':hashlib.sha256(a.graphml.read_bytes()).hexdigest(),'method_candidates':len(methods),
                  'ambiguous_indices':sum(v>1 for v in counts.values()),'graphs':emitted},indent=2))
