#!/usr/bin/env python3
"""Offline N-1-2 request oracle and fixture checker (Python standard library only).

The oracle reads only subtype_id + input. It never reads expected fields, case kind,
prompt, fixture id, solutionSteps or why. It checks the formal request contract and
recomputes the numerical relation. A rejected proposal may still return the correct
answer to the original valid problem; invalid/incomplete conditions return no answer.

Usage: python3 check-grade1-add-subtract.py [JSON_PATH] [--self-test]
Import: evaluate(subtype_id, input_dict) -> {decision, answer, reasonCode}
This is not a teacher review, photo/OCR parser, or proof of all curriculum coverage.
"""
import argparse
from collections import Counter
import json
from pathlib import Path
import sys

RELATIONS = {'increase': 'increase', 'combine': 'combine', 'take-away': 'take_away',
             'compare': 'compare', 'zero': 'zero_change'}
TARGETS = {'increase': 'after_addition', 'combine': 'combined_total',
           'take-away': 'remaining', 'compare': 'gap_and_larger', 'zero': 'result'}
KINDS = {'normal': 8, 'negative': 6, 'boundary': 4, 'ambiguous': 2, 'holdout': 4}
ROOT_KEYS = {'relation', 'target', 'task', 'left', 'right', 'groupsDisjoint', 'operator', 'proposal'}
QUANTITY_KEYS = {'label', 'value', 'unit'}
PROPOSAL_KEYS = {'value', 'unit', 'larger'}


def outcome(decision, answer=None, reason='ok'):
    return {'decision': decision, 'answer': answer, 'reasonCode': reason}


def evaluate(subtype_id, request):
    """Validate conditions and solve, without using any fixture expected answer.

    Decisions:
    pass: well-formed solvable problem (or a correct proposal).
    confirm: genuine absent condition; do not infer a quantity/unit/operation.
    reject: invalid data, unsupported subtype/range, or false solution proposal.
    """
    if not isinstance(subtype_id, str) or subtype_id not in RELATIONS:
        return outcome('reject', reason='unsupported-subtype')
    if type(request) is not dict:
        return outcome('reject', reason='request-not-object')
    if set(request) - ROOT_KEYS:
        return outcome('reject', reason='unknown-request-field')
    if request.get('relation') is None or request.get('target') is None:
        return outcome('confirm', reason='missing-relation-or-target')
    if request['relation'] != RELATIONS[subtype_id]:
        return outcome('reject', reason='relation-does-not-match-subtype')
    if request['target'] != TARGETS[subtype_id]:
        # Inverse unknown-addend/subtrahend/minuend tasks belong to N-2-3.
        return outcome('reject', reason='unsupported-target-route-to-appropriate-module')
    if request.get('task') is None:
        return outcome('confirm', reason='missing-task')
    if request['task'] not in ('solve', 'check_proposal'):
        return outcome('reject', reason='unsupported-task')
    quantities = []
    for side in ('left', 'right'):
        quantity = request.get(side)
        if quantity is None:
            return outcome('confirm', reason='missing-' + side + '-quantity')
        if type(quantity) is not dict or set(quantity) - QUANTITY_KEYS:
            return outcome('reject', reason='invalid-' + side + '-quantity-object')
        if not isinstance(quantity.get('label'), str) or not quantity['label'].strip():
            return outcome('confirm', reason='missing-' + side + '-quantity-role')
        number = quantity.get('value')
        if number is None:
            return outcome('confirm', reason='missing-' + side + '-value')
        # bool subclasses int in Python; accepting isinstance(x,int) is unsafe here.
        if type(number) is not int:
            return outcome('reject', reason='non-integer-' + side + '-quantity')
        if not 0 <= number <= 100:
            return outcome('reject', reason='out-of-range-' + side + '-quantity')
        unit = quantity.get('unit')
        if unit is None or unit == '':
            return outcome('confirm', reason='missing-' + side + '-unit')
        if not isinstance(unit, str):
            return outcome('reject', reason='non-string-' + side + '-unit')
        if unit != unit.strip() or not unit.strip():
            return outcome('reject', reason='noncanonical-' + side + '-unit')
        quantities.append((number, unit))
    (a, unit), (b, other_unit) = quantities
    if unit != other_unit:
        return outcome('reject', reason='incomparable-or-mixed-units')
    if subtype_id == 'combine':
        disjoint = request.get('groupsDisjoint')
        if disjoint is None:
            return outcome('confirm', reason='unknown-group-overlap')
        if type(disjoint) is not bool:
            return outcome('reject', reason='non-boolean-group-overlap')
        if not disjoint:
            return outcome('reject', reason='overlapping-groups-cannot-directly-add')
    elif 'groupsDisjoint' in request:
        return outcome('reject', reason='group-overlap-field-for-wrong-relation')
    operator = None
    if subtype_id == 'zero':
        operator = request.get('operator')
        if operator is None:
            return outcome('confirm', reason='missing-zero-operation')
        if operator not in ('add', 'subtract'):
            return outcome('reject', reason='unsupported-zero-operation')
        if operator == 'add' and a != 0 and b != 0:
            return outcome('reject', reason='not-an-add-zero-problem-route-subtype')
        if operator == 'subtract' and b != 0:
            return outcome('reject', reason='not-taking-zero-or-infeasible-removal')
    elif 'operator' in request:
        return outcome('reject', reason='operator-field-for-wrong-relation')
    if subtype_id in ('increase', 'combine') or (subtype_id == 'zero' and operator == 'add'):
        total = a + b
        if total > 100:
            return outcome('reject', reason='total-over-100-route-module')
        answer = {'value': total, 'unit': unit}
    elif subtype_id == 'take-away' or (subtype_id == 'zero' and operator == 'subtract'):
        if b > a:
            return outcome('reject', reason='cannot-remove-more-than-present')
        answer = {'value': a - b, 'unit': unit}
    else:  # compare: never use an ordered a-b as a negative Grade 1 result.
        larger = 'equal' if a == b else ('first' if a > b else 'second')
        answer = {'value': max(a, b) - min(a, b), 'unit': unit, 'larger': larger}
    if request['task'] == 'solve':
        if 'proposal' in request:
            return outcome('reject', answer, 'proposal-present-with-solve-task')
        return outcome('pass', answer)
    proposal = request.get('proposal')
    if proposal is None:
        return outcome('confirm', answer, 'missing-proposal-to-check')
    if type(proposal) is not dict or set(proposal) - PROPOSAL_KEYS:
        return outcome('reject', answer, 'malformed-proposal')
    if type(proposal.get('value')) is not int or not isinstance(proposal.get('unit'), str):
        return outcome('reject', answer, 'malformed-proposal-value-or-unit')
    if subtype_id == 'compare':
        if proposal.get('larger') not in ('first', 'second', 'equal'):
            return outcome('reject', answer, 'missing-or-invalid-larger-in-proposal')
    elif 'larger' in proposal:
        return outcome('reject', answer, 'larger-field-for-noncomparison-proposal')
    if proposal != answer:
        return outcome('reject', answer, 'incorrect-proposal-not-rejection-of-student-question')
    return outcome('pass', answer, 'correct-proposal')


def semantic_signature(case):
    """Ignore ID/prompt for holdout leakage: compare the actual numerical request."""
    req = case['input']
    return (req['left']['value'], req['right']['value'], req.get('operator'), req['target'])


def verify_package(package):
    failures = []
    if package.get('code') != 'N-1-2':
        failures.append('package code is not N-1-2')
    if package.get('teacherReviewed') is not False or package.get('appConnected') is not False:
        failures.append('package must remain unreviewed/offline')
    cases = package.get('cases', [])
    if len(cases) != 120:
        failures.append('expected 120 cases, found ' + str(len(cases)))
    ids = [case.get('id') for case in cases]
    if len(set(ids)) != len(ids):
        failures.append('duplicate case IDs')
    counts = Counter((case.get('subtypeId'), case.get('kind')) for case in cases)
    for subtype in RELATIONS:
        for kind, count in KINDS.items():
            if counts[subtype, kind] != count:
                failures.append(f'{subtype}/{kind}: {counts[subtype,kind]} not {count}')
    decisions = Counter()
    for case in cases:
        cid = case.get('id')
        if case.get('subtypeId') not in RELATIONS or case.get('kind') not in KINDS:
            failures.append(f'{cid}: unknown subtype/kind')
        if case.get('code') != 'N-1-2':
            failures.append(f'{cid}: wrong curriculum code')
        if case.get('teacherReviewed') is not False or case.get('appConnected') is not False:
            failures.append(f'{cid}: must not claim teacher review or app integration')
        for field in ('prompt', 'why'):
            if not isinstance(case.get(field), str) or not case[field].strip():
                failures.append(f'{cid}: missing {field}')
        steps = case.get('solutionSteps')
        if not isinstance(steps, list) or len(steps) < 2 or any(not isinstance(s, str) or not s.strip() for s in steps):
            failures.append(f'{cid}: missing concrete solution/confirmation steps')
        actual = evaluate(case.get('subtypeId'), case.get('input'))
        decisions[actual['decision']] += 1
        if actual['decision'] != case.get('expectedDecision'):
            failures.append(f'{cid}: decision actual={actual["decision"]} expected={case.get("expectedDecision")} ({actual["reasonCode"]})')
        if actual['answer'] != case.get('expectedAnswer'):
            failures.append(f'{cid}: answer actual={actual["answer"]} expected={case.get("expectedAnswer")}')
        if case.get('kind') == 'ambiguous' and actual['decision'] != 'confirm':
            failures.append(f'{cid}: ambiguous fixture must truly lack conditions')
        if case.get('kind') == 'negative' and actual['decision'] != 'reject':
            failures.append(f'{cid}: negative fixture not actually rejected')
    # Holdout must not be an ID/prompt-only duplicate of another fixture's numbers/relation.
    for subtype in RELATIONS:
        family = [c for c in cases if c.get('subtypeId') == subtype]
        seen_non_holdout = {semantic_signature(c) for c in family if c['kind'] != 'holdout'}
        holdout = [c for c in family if c['kind'] == 'holdout']
        signatures = [semantic_signature(c) for c in holdout]
        if len(signatures) != len(set(signatures)):
            failures.append(f'{subtype}: duplicate holdout numerical requests')
        for c in holdout:
            if semantic_signature(c) in seen_non_holdout:
                failures.append(f'{c["id"]}: numerical holdout leakage')
    return failures, dict(decisions)


def self_test():
    """Independent request probes and mutation checks, not reads from expected fields."""
    def q(a, b, unit='顆'):
        return {'relation': 'increase', 'target': 'after_addition', 'task': 'solve',
                'left': {'label': '原有', 'value': a, 'unit': unit},
                'right': {'label': '新增', 'value': b, 'unit': unit}}
    probes = []
    def check(label, subtype, req, decision, answer):
        result = evaluate(subtype, req)
        assert result['decision'] == decision and result['answer'] == answer, (label, result)
        probes.append(label)
    check('fresh sum unseen in corpus', 'increase', q(33, 18), 'pass', {'value': 51, 'unit': '顆'})
    check('upper sum limit', 'increase', q(64, 36), 'pass', {'value': 100, 'unit': '顆'})
    check('one past sum limit', 'increase', q(64, 37), 'reject', None)
    check('bool is not count', 'increase', q(True, 2), 'reject', None)
    check('float is not JSON integer', 'increase', q(3.0, 2), 'reject', None)
    check('negative count', 'increase', q(-1, 2), 'reject', None)
    check('missing amount', 'increase', q(None, 2), 'confirm', None)
    unit_missing = q(7, 2); unit_missing['right']['unit'] = None
    check('missing unit', 'increase', unit_missing, 'confirm', None)
    mixed = q(7, 2); mixed['right']['unit'] = '公分'
    check('mixed units', 'increase', mixed, 'reject', None)
    inverse = q(7, 2); inverse['target'] = 'initial'
    check('unknown original amount not Grade 1 task', 'increase', inverse, 'reject', None)
    compare = q(12, 31); compare.update(relation='compare', target='gap_and_larger')
    check('second larger never negative', 'compare', compare, 'pass', {'value': 19, 'unit': '顆', 'larger': 'second'})
    compare['left']['value'] = 31
    check('equal compare has zero gap', 'compare', compare, 'pass', {'value': 0, 'unit': '顆', 'larger': 'equal'})
    removal = q(5, 8); removal.update(relation='take_away', target='remaining')
    check('infeasible removal not negative result', 'take-away', removal, 'reject', None)
    combine = q(16, 8); combine.update(relation='combine', target='combined_total', groupsDisjoint=None)
    check('unknown overlap', 'combine', combine, 'confirm', None)
    combine['groupsDisjoint'] = False
    check('confirmed overlap', 'combine', combine, 'reject', None)
    zero = q(73, 0); zero.update(relation='zero_change', target='result', operator='subtract')
    check('taking zero', 'zero', zero, 'pass', {'value': 73, 'unit': '顆'})
    zero['operator'] = None
    check('unknown zero operation not inferred', 'zero', zero, 'confirm', None)
    proposal = q(33, 18); proposal.update(task='check_proposal', proposal={'value': 52, 'unit': '顆'})
    check('reject wrong proposal but solve original', 'increase', proposal, 'reject', {'value': 51, 'unit': '顆'})
    proposal['proposal']['value'] = 51
    check('accept correct proposal', 'increase', proposal, 'pass', {'value': 51, 'unit': '顆'})
    return probes


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('path', nargs='?', default=str(Path(__file__).with_name('grade1-add-subtract.json')))
    parser.add_argument('--self-test', action='store_true')
    args = parser.parse_args(argv)
    try:
        package = json.loads(Path(args.path).read_text(encoding='utf-8'))
        failures, decisions = verify_package(package)
        probes = self_test() if args.self_test else []
    except (OSError, ValueError, KeyError, TypeError, AssertionError) as error:
        print(json.dumps({'ok': False, 'error': str(error)}, ensure_ascii=False))
        return 1
    print(json.dumps({'ok': not failures, 'code': 'N-1-2', 'caseCount': len(package['cases']),
                      'subtypeCount': len(RELATIONS), 'decisions': decisions,
                      'independentProbeCount': len(probes), 'failures': failures,
                      'teacherReviewed': False, 'appConnected': False,
                      'scope': 'only these five Grade 1 subtypes; not all curriculum codes'},
                     ensure_ascii=False, indent=2))
    return 1 if failures else 0


if __name__ == '__main__':
    sys.exit(main())
