"""Contraste pareado con biblioteca de búsqueda y sintaxis v4, reanudable."""
import argparse
import hashlib
import json
import time
from pathlib import Path

from skill_library_env import messages
from skill_library_search_adapter import adapt, retrieval, FROZEN_SHA
from skill_library_constraints import SyntaxConstraint, GRAMMAR, PATTERN
from skill_library_eval import (MODEL, REV, MODEL_SHA, ATTEMPTS, TOTAL_BUDGET,
    OUTPUT_BUDGET, PER_ATTEMPT, unpack, digest, append, output_limit, seed_for,
    row_from_events, validate_history)


def configuration(tasks_path, library_path, split):
    source = Path(__file__)
    task_raw = Path(tasks_path).read_bytes()
    tasks = json.loads(task_raw)[split]
    skills = adapt(library_path, tasks_path)
    meta = {'protocol': 'search-memory-v1', 'split': split, 'model': MODEL,
            'revision': REV, 'model_sha256': MODEL_SHA, 'backend': 'cuda',
            'dataset_sha256': digest(task_raw), 'library_sha256': FROZEN_SHA,
            'tasks_sha256': digest(json.dumps(tasks, sort_keys=True, ensure_ascii=False).encode()),
            'conditions': ['retry', 'library'], 'attempts': ATTEMPTS,
            'total_token_cap': TOTAL_BUDGET, 'output_allocation': OUTPUT_BUDGET,
            'max_output_per_attempt': PER_ATTEMPT,
            'sampling': {'temperature': .7, 'top_p': 1., 'top_k': 0, 'min_p': None,
                         'repetition_penalty': 1.},
            'grammar': PATTERN, 'eos_rule': 'solo EOS tras JSON completo',
            'seed_rule': '5200 + 3*índice + intento en test; igual para ambos brazos',
            'retrieval': 'Jaccard léxico, desempate por orden de biblioteca; sin umbral',
            'cost': 'adquisición separada: 4942 consultas de búsqueda y 12 de validación; cero tokens de modelo',
            'code_sha256': {p.name: digest(p.read_bytes()) for p in (
                source, source.with_name('skill_library_env.py'),
                source.with_name('skill_library_eval.py'),
                source.with_name('skill_library_constraints.py'),
                source.with_name('skill_library_search.py'),
                source.with_name('skill_library_search_adapter.py'))}}
    return tasks, skills, meta


def check_history(tasks, skills, rows, cached, tokenizer, constraint, split):
    validate_history(tasks, rows, cached, tokenizer, split, ('retry', 'library'), skills)
    by_id = {t['id']: t for t in tasks}
    for (task_id, condition, _), event in cached.items():
        expected = retrieval(by_id[task_id]['prompt'], skills) if condition == 'library' else None
        if event.get('retrieval') != expected:
            raise ValueError('la recuperación guardada no coincide')
        prefix = []
        for index, token in enumerate(event['output_ids']):
            if token not in constraint.allowed(prefix):
                raise ValueError('token fuera de gramática')
            if token == tokenizer.eos_token_id:
                if index != len(event['output_ids']) - 1:
                    raise ValueError('EOS interno')
            else:
                prefix.append(token)
        if event['end_reason'] == 'eos' and GRAMMAR.fullmatch(event['text']) is None:
            raise ValueError('EOS antes de JSON completo')


def run(args):
    import torch
    if not torch.cuda.is_available():
        raise RuntimeError('CUDA requerida')
    from transformers import AutoModelForCausalLM, AutoTokenizer
    from huggingface_hub import hf_hub_download
    tasks, skills, meta = configuration(args.tasks, args.library, args.split)
    tokenizer = AutoTokenizer.from_pretrained(MODEL, revision=REV, local_files_only=True)
    constraint = SyntaxConstraint(tokenizer, 0)
    out = Path(args.output)
    journal = Path(str(out) + '.calls.jsonl')
    out.parent.mkdir(parents=True, exist_ok=True)
    rows, cached = {}, {}
    for path, target in ((out, rows), (journal, cached)):
        if path.exists() and path.stat().st_size:
            lines = path.read_text(encoding='utf8').splitlines()
            if json.loads(lines[0]) != {'metadata': meta}:
                raise ValueError('la configuración guardada no coincide')
            for line in lines[1:]:
                item = json.loads(line)
                key = (item['task_id'], item['condition'])
                if target is cached:
                    key += (item['attempt'],)
                if key in target:
                    raise ValueError('registro duplicado')
                target[key] = item
    check_history(tasks, skills, rows, cached, tokenizer, constraint, args.split)
    if len(rows) == 2 * len(tasks):
        print('evaluación completa', flush=True)
        return
    weights = hf_hub_download(MODEL, filename='model.safetensors', revision=REV, local_files_only=True)
    with open(weights, 'rb') as stream:
        if hashlib.file_digest(stream, 'sha256').hexdigest() != MODEL_SHA:
            raise ValueError('pesos distintos')
    torch.cuda.reset_peak_memory_stats()
    model = AutoModelForCausalLM.from_pretrained(MODEL, revision=REV, local_files_only=True,
                                                 dtype=torch.bfloat16).to('cuda').eval()
    added = 0
    with out.open('a', encoding='utf8') as output, journal.open('a', encoding='utf8') as calls:
        if output.tell() == 0: append(output, {'metadata': meta})
        if calls.tell() == 0: append(calls, {'metadata': meta})
        for index, task in enumerate(tasks):
            for condition in ('retry', 'library'):
                if (task['id'], condition) in rows: continue
                prompt = list(unpack(tokenizer.apply_chat_template(messages(task, condition, skills),
                                                                   tokenize=True, add_generation_prompt=True)))
                prompt_sha = digest(json.dumps(prompt, separators=(',', ':')).encode())
                retrieved = retrieval(task['prompt'], skills) if condition == 'library' else None
                constraint.prompt_length = len(prompt)
                events = []; spent = output_spent = 0
                for attempt in range(ATTEMPTS):
                    key = (task['id'], condition, attempt)
                    limit = output_limit(len(prompt), spent, output_spent, attempt)
                    if key in cached:
                        event = cached[key]
                    else:
                        seed = seed_for(args.split, index, attempt)
                        torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
                        x = torch.tensor([prompt], device='cuda'); start = time.perf_counter()
                        callbacks, seconds = constraint.callback_count, constraint.callback_seconds
                        with torch.inference_mode():
                            result = model.generate(input_ids=x, attention_mask=torch.ones_like(x),
                                do_sample=True, temperature=.7, top_p=1., top_k=0, min_p=None,
                                repetition_penalty=1., max_new_tokens=limit,
                                eos_token_id=tokenizer.eos_token_id, pad_token_id=tokenizer.eos_token_id,
                                prefix_allowed_tokens_fn=constraint)
                        ids = result[0, len(prompt):].tolist(); torch.cuda.synchronize()
                        ended = bool(ids and ids[-1] == tokenizer.eos_token_id)
                        decoded = tokenizer.decode(ids, skip_special_tokens=True, clean_up_tokenization_spaces=False).strip()
                        if ended and GRAMMAR.fullmatch(decoded) is None: raise ValueError('JSON incompleto')
                        free, total = torch.cuda.mem_get_info()
                        event = {'task_id': task['id'], 'condition': condition, 'attempt': attempt,
                            'seed': seed, 'prompt_sha256': prompt_sha, 'prompt_tokens': len(prompt),
                            'output_limit': limit, 'output_ids': ids, 'output_tokens': len(ids),
                            'text': decoded, 'end_reason': 'eos' if ended else 'length',
                            'retrieval': retrieved, 'seconds': time.perf_counter() - start,
                            'constraint_callbacks': constraint.callback_count - callbacks,
                            'constraint_seconds': constraint.callback_seconds - seconds,
                            'peak_allocated_bytes': torch.cuda.max_memory_allocated(),
                            'peak_reserved_bytes': torch.cuda.max_memory_reserved(),
                            'cuda_free_bytes': free, 'cuda_total_bytes': total}
                        append(calls, event)
                    spent += event['prompt_tokens'] + event['output_tokens']
                    output_spent += event['output_tokens']; events.append(event)
                row = row_from_events(task, condition, events)
                if spent > TOTAL_BUDGET or output_spent > OUTPUT_BUDGET: raise ValueError('presupuesto excedido')
                append(output, row); added += 1
                print(args.split, index, condition, row['success_at_3'], spent, flush=True)
                if args.max_rows is not None and added >= args.max_rows: return


if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument('--tasks', required=True); p.add_argument('--library', required=True)
    p.add_argument('--split', required=True, choices=('development', 'test'))
    p.add_argument('--output', required=True); p.add_argument('--max-rows', type=int)
    args = p.parse_args()
    if args.max_rows is not None and args.max_rows < 1: raise ValueError('invalid block size')
    run(args)
