"""Adapta una biblioteca de búsqueda congelada al recuperador existente."""
import argparse
import hashlib
import json
import re
from pathlib import Path

from skill_library_env import retrieve
from skill_library_search import acquire

FROZEN_SHA = '7151e54e6c7d4d41ce85a052835cb79f1c8ebace5364400cc07179a477a77c1b'


def retrieval(prompt, skills):
    selected = retrieve(prompt, skills)
    if selected is None:
        return {'id': None, 'score': None}
    words = lambda s: set(re.findall(r'[^\W\d_]+', s.casefold()))
    query, description = words(prompt), words(selected['description'])
    return {'id': selected['id'], 'score': len(query & description) / len(query | description)}


def sha(data):
    return hashlib.sha256(data).hexdigest()


def adapt(path, task_path):
    raw = Path(path).read_bytes()
    if sha(raw) != FROZEN_SHA:
        raise ValueError('la biblioteca congelada no coincide')
    book = json.loads(raw)
    task_bytes = Path(task_path).read_bytes()
    if sha(task_bytes) != book['dataset_sha256']:
        raise ValueError('el corpus no coincide')
    development = json.loads(task_bytes)['development']
    for key, value in acquire(development).items():
        if book[key] != value:
            raise ValueError('la adquisición no se reproduce: ' + key)
    skills = []
    for entry in book['skills']:
        plan = entry['template']
        steps = plan['steps']
        if (len(steps) != 2 or [(s['a'], s['b']) for s in steps] != [('a', 'b'), ('$0', 'c')]
                or plan['result'] != '$1'):
            raise ValueError('plantilla no representable por el recuperador existente')
        skills.append({'id': entry['id'], 'description': entry['description'],
                       'ops': [s['op'] for s in steps]})
    return skills


def main():
    p = argparse.ArgumentParser()
    p.add_argument('--library', required=True)
    p.add_argument('--tasks', required=True)
    p.add_argument('--output', required=True)
    args = p.parse_args()
    skills = adapt(args.library, args.tasks)
    tasks = json.loads(Path(args.tasks).read_text(encoding='utf8'))['development']
    recovered = []
    for task in tasks:
        selected = retrieval(task['prompt'], skills)
        recovered.append({'task_id': task['id'], 'family': task['skill'],
                          'retrieved': selected['id'], 'score': selected['score']})
    result = {'source_sha256': FROZEN_SHA, 'development_tasks': len(tasks),
              'skills': skills, 'recovery': recovered,
              'matching': sum(x['family'] == x['retrieved'] for x in recovered),
              'nonmatching': sum(x['retrieved'] is not None and x['family'] != x['retrieved'] for x in recovered),
              'empty': sum(x['retrieved'] is None for x in recovered),
              'limitation': 'Jaccard siempre elige la mejor descripción disponible; '
                            'una familia ausente puede recuperar otra, no implica ausencia de memoria'}
    output = Path(args.output)
    if output.exists():
        raise ValueError('refusing to overwrite')
    output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n', encoding='utf8')
    print(json.dumps({k: result[k] for k in ('development_tasks', 'matching', 'nonmatching', 'empty')}))


if __name__ == '__main__':
    main()
