"""Check IDs, permitted labels and literal evidence quotes, not screening accuracy.
Usage: python check_output.py output.json
Keep records.json next to this script. All records are constructed case materials.
"""
import json
import sys
from collections import Counter
from pathlib import Path

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

root = Path(__file__).resolve().parent
records = json.loads((root / 'records.json').read_text(encoding='utf-8-sig'))
output_path = Path(sys.argv[1]) if len(sys.argv) > 1 else root / 'answer-key.json'
candidate = json.loads(output_path.read_text(encoding='utf-8-sig'))
sources = {row['id']: row['abstract'] for row in records}
labels = {'保留取全文', '明确排除', '待定取全文'}
errors = []
if not isinstance(candidate, list):
    raise SystemExit('Output must be a JSON array.')
ids = [row.get('id') for row in candidate]
duplicates = [key for key, count in Counter(ids).items() if count > 1]
if duplicates:
    errors.append(f'Duplicate IDs: {duplicates}')
if set(ids) != set(sources):
    errors.append(f'Missing IDs: {sorted(set(sources)-set(ids))}')
    errors.append(f'Unexpected IDs: {sorted(set(ids)-set(sources), key=str)}')
for row in candidate:
    identifier = row.get('id')
    if row.get('decision') not in labels:
        errors.append(f'{identifier}: invalid decision')
    quote = row.get('evidence', '')
    if not quote or quote not in sources.get(identifier, ''):
        errors.append(f'{identifier}: evidence is not a literal abstract excerpt')
    if not row.get('reason'):
        errors.append(f'{identifier}: missing reason')
if errors:
    print('\n'.join(errors))
    raise SystemExit(1)
print(f'{len(candidate)} records; IDs complete, labels valid, evidence quotes found.')
for key, value in sorted(Counter(row['decision'] for row in candidate).items()):
    print(f'{key}: {value}')
print('This checks output structure and quote presence. It does NOT verify eligibility decisions.')
