"""Deterministic structural checks, not translation-quality scores. MIT."""
import re
from collections import Counter

TOKEN = re.compile(r'\{\{[A-Za-z_][\w]*\}\}|(?<!\{)\{[A-Za-z_][\w]*\}(?!\})|%(?:\d+\$)?[sd]')
TAG = re.compile(r'<[^>]+>')

def inspect(item, arguments):
    valid = isinstance(arguments, dict) and set(arguments) == {'key', 'translation'} and arguments.get('key') == item['key'] and isinstance(arguments.get('translation'), str) and bool(arguments['translation'].strip())
    text = arguments.get('translation', '') if valid else ''
    expected = item['expected']
    broken = not valid or Counter(TOKEN.findall(text)) != Counter(expected['placeholders'])
    icu_ok = plural_ok = True
    if expected['icu_variable']:
        # This fixture deliberately uses only flat cardinal ICU plurals. Reject
        # unsupported/nested syntax instead of claiming a full ICU parser.
        pattern = r'\{count,\s*plural,\s*((?:(?:zero|one|two|few|many|other|=\d+)\s*\{[^{}]*\}\s*)+)\}'
        match = re.search(pattern, text)
        icu_ok = bool(match) and text.count('{') == text.count('}') and not re.search(r'[{}]', text[:match.start()] + text[match.end():]) if match else False
        categories = re.findall(r'(zero|one|two|few|many|other|=\d+)\s*\{', match[1]) if match else []
        plural_ok = icu_ok and len(categories) == len(set(categories)) and set(expected['plural_categories']).issubset(categories)
        broken = broken or not icu_ok or '#' not in text
    markup = valid and TAG.findall(text) == expected['tags']
    glossary = valid and all(term in text for term in expected['glossary'])
    return {'broken': int(broken), 'icu_valid': int(valid and icu_ok), 'plural_complete': int(valid and plural_ok), 'glossary_adherence': int(glossary), 'key_set_equal': int(valid), 'markup_preserved': int(markup)}

def score(item, arguments, config):
    first = inspect(item, arguments.get('first', {}) if 'first' in arguments else arguments)
    final = inspect(item, arguments.get('retry', arguments.get('first', {})) if 'first' in arguments else arguments)
    secondary = {name: {'score': first[name]} for name in ['icu_valid', 'plural_complete', 'glossary_adherence', 'key_set_equal', 'markup_preserved']}
    secondary['after_retry'] = {'score': final['broken']}
    # Locale metrics are scaled contributions over equal-sized locale groups.
    # Each mean therefore equals that locale's break rate, not pooled rate.
    for locale in ['de', 'ja', 'pl', 'ar', 'pt-BR']:
        secondary['locale_' + locale.replace('-', '_')] = {'score': first['broken'] * 5 if item['locale'] == locale else 0}
    return {'score': first['broken'], 'secondary': secondary}
