"""Frozen exact-value and quote checker; never executes model output. MIT."""
import json


def normalize(value):
    return ' '.join(value.casefold().split()) if isinstance(value, str) else value


def score(item, tool_arguments, config):
    expected = item['gold']
    valid = isinstance(tool_arguments, dict) and set(tool_arguments) == set(expected)
    correct = quote_matches = review = 0
    for name, gold in expected.items():
        field = tool_arguments.get(name, {}) if isinstance(tool_arguments, dict) else {}
        shape = isinstance(field, dict) and set(field) == {'value', 'quote'} and (isinstance(field.get('value'), str) or field.get('value') is None) and isinstance(field.get('quote'), str)
        valid = valid and shape
        value = field.get('value') if shape else object()
        quote = field.get('quote', '') if shape else ''
        match = shape and (quote in item['text'] and bool(quote) if gold is not None else value is None and quote == '')
        correct += int(shape and normalize(value) == normalize(gold))
        quote_matches += int(match)
        review += int(not match or value is None)
    n = len(expected)
    return {'score': correct / n, 'secondary': {'quote_match': {'score': quote_matches / n}, 'review_load': {'score': review / n}, 'schema_valid': {'score': int(valid)}}}


if __name__ == '__main__':
    import argparse
    from pathlib import Path
    parser = argparse.ArgumentParser(description='Check JSON tool arguments against a selected fixture row.')
    parser.add_argument('fixture', type=Path)
    parser.add_argument('item_id')
    parser.add_argument('arguments', type=Path)
    args = parser.parse_args()
    item = next(json.loads(line) for line in args.fixture.read_text().splitlines() if json.loads(line)['item_id'] == args.item_id)
    result = score(item, json.loads(args.arguments.read_text()), {})
    print(json.dumps(result, indent=2))
    raise SystemExit(0 if result['score'] == 1 and result['secondary']['schema_valid']['score'] == 1 else 1)
