"""Verifica las trazas reales y construye datos del visor Game 24."""
import argparse
from fractions import Fraction
import hashlib
import json
from pathlib import Path
import re
import generate_game24 as game

def digest(path):
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()

def build(root):
    root=Path(root)
    protocol=json.loads((root/'protocol.json').read_text(encoding='utf8'))
    if protocol['revision']!=game.REV or protocol['model_sha256']!=game.WEIGHTS_SHA256:
        raise ValueError('Modelo distinto del protocolo')
    if protocol['code_sha256']!=digest(game.__file__) or protocol['cases']!=game.CASES:
        raise ValueError('Código o casos diferentes del protocolo')
    graphs=[]
    for case_id,case in enumerate(game.CASES):
        path=root/f'case{case_id}.json'
        nodes=json.loads(path.read_text(encoding='utf8'))
        if not nodes or nodes[0]['values']!=list(map(str,case)) or nodes[0]['path']!=[]:
            raise ValueError('Raíz incompleta')
        seen=set();expected_paths={()}
        for idx,node in enumerate(nodes):
            if node!=json.loads((root/f'c{case_id}-n{idx:03d}.json').read_text(encoding='utf8')):
                raise ValueError('El agregado difiere del registro de nodo')
            key=tuple(node['path'])
            if key in seen or node['depth']!=len(key) or node['depth']>2:
                raise ValueError('Ruta de nodo inválida')
            seen.add(key)
            values=[Fraction(x) for x in node['values']]
            parsed=game.parse_proposals(node['text'],values)
            labels={int(n):label.lower() for n,label in re.findall(
                r'(?im)^\s*(\d+)\s*[:.)-]\s*(sure|likely|impossible)\b',node['judge_text'])}
            if len(parsed)!=len(node['proposals']):raise ValueError('Número de propuestas discrepante')
            for i,(expected,actual) in enumerate(zip(parsed,node['proposals'])):
                if any(expected[k]!=actual[k] for k in ('operation','remaining','solvable')):
                    raise ValueError('Propuesta o viabilidad discrepante')
                if actual['judge']!=labels.get(i+1,'unknown'):raise ValueError('Juicio discrepante')
                if node['depth']<2 and i<5:expected_paths.add(key+(actual['operation'],))
            for key2 in ('input_tokens','output_tokens','judge_input_tokens','judge_output_tokens'):
                if type(node[key2]) is not int or node[key2]<0:raise ValueError('Contador inválido')
            if (len(node['output_token_ids'])!=node['output_tokens']
                or len(node['judge_token_ids'])!=node['judge_output_tokens']):
                raise ValueError('IDs de tokens inconsistentes')
            if idx and tuple(node['path'][:-1]) not in seen:raise ValueError('Padre ausente o fuera de orden')
        if seen!=expected_paths:raise ValueError('Árbol incompleto')
        graphs.append(nodes)
    return graphs,protocol

def main():
    ap=argparse.ArgumentParser()
    ap.add_argument('--run',required=True);ap.add_argument('--output',required=True)
    args=ap.parse_args()
    graphs,protocol=build(args.run)
    path=Path(args.output);tmp=path.with_suffix(path.suffix+'.tmp')
    tmp.write_text(json.dumps(graphs,ensure_ascii=False,separators=(',',':')),encoding='utf8');tmp.replace(path)
    print(json.dumps({'casos':len(graphs),'nodos':[len(x) for x in graphs],
                      'sha256':digest(path),'revision':protocol['revision'],
                      'modelo_sha256':protocol['model_sha256']},ensure_ascii=False))

if __name__=='__main__':main()
