#!/usr/bin/env python3
"""Independent, deterministic N-1-1 assessment oracle. No network or third parties.

Public API: evaluate(subtype_id, input_data) -> {decision, answer, reason}.
The oracle only consumes subtype/input; it never reads an expected answer or case ID.
A reject of a proposed answer still returns the correct answer when the task is legal.
The JSON accompanying this file is an authored assessment pack, not teacher approval.
"""
import argparse
import copy
import json
from collections import Counter
from pathlib import Path

SUBTYPES = ('tens-ones', 'compare', 'count')
KIND_COUNTS = {'normal': 8, 'negative': 6, 'boundary': 4,
               'ambiguous': 2, 'holdout': 4}


def result(decision, answer, reason):
    return {'decision': decision, 'answer': answer, 'reason': reason}


def natural_0_100(value):
    # bool is deliberately excluded: Python otherwise treats True as integer 1.
    return type(value) is int and 0 <= value <= 100


def split_tens(quantity):
    # Deliberately use grouping, independently of an authored expected split.
    tens, loose = 0, quantity
    while loose >= 10:
        tens += 1
        loose -= 10
    return {'tens': tens, 'ones': loose}


def validate_quantity(value, name):
    if value is None:
        return result('confirm', None, name + '尚未確認，請補清楚數量。')
    if not natural_0_100(value):
        return result('reject', None, name + '必須是0至100的整數，不能是布林、小數或字串。')
    return None


def evaluate(subtype_id, input_data):
    """Apply the declared input contract, then derive the mathematical answer.

    Missing/null necessary conditions -> confirm; explicit malformed data -> reject.
    Valid counting commands crossing 0/100 -> block (scope guard, not math error).
    If a student's `proposed` is wrong, reject that proposal and return a correction.
    """
    if subtype_id not in SUBTYPES:
        return result('block', None, '本包尚未定義此子型，不能默認另一個解法。')
    if not isinstance(input_data, dict):
        return result('reject', None, 'input必須是JSON物件。')

    if subtype_id == 'tens-ones':
        n = input_data.get('quantity')
        bad = validate_quantity(n, '總量')
        if bad:
            return bad
        answer = split_tens(n)
        if 'proposed' in input_data:
            proposed = input_data['proposed']
            valid_shape = (isinstance(proposed, dict)
                           and type(proposed.get('tens')) is int
                           and type(proposed.get('ones')) is int
                           and 0 <= proposed['tens'] <= 10
                           and 0 <= proposed['ones'] <= 9)
            if not valid_shape:
                return result('reject', answer,
                              '提案不是標準十/個表示；個一欄必須0至9，題目本身仍可解。')
            if proposed['tens'] != answer['tens'] or proposed['ones'] != answer['ones']:
                return result('reject', answer, '學生提案與原量不符，應按每10個一組重排。')
        return result('pass', answer, '以完整十個群與剩餘個數重組原量。')

    if subtype_id == 'compare':
        left, right = input_data.get('left'), input_data.get('right')
        if left is None or right is None:
            return result('confirm', None, '需左右兩邊的數量與單位。')
        if not isinstance(left, dict) or not isinstance(right, dict):
            return result('reject', None, 'left/right必須各為包含quantity及unit的物件。')
        # Check each quantity before interpreting units; never guess unreadable numbers.
        for side, name in ((left, '左量'), (right, '右量')):
            bad = validate_quantity(side.get('quantity'), name)
            if bad:
                return bad
        for side in (left, right):
            unit = side.get('unit')
            if unit is None or (isinstance(unit, str) and not unit.strip()):
                return result('confirm', None, '單位缺漏，可能是捆數或根數，先確認共同單位。')
            if not isinstance(unit, str):
                return result('reject', None, 'unit必須是非空字串。')
        if left['unit'].strip() != right['unit'].strip():
            return result('confirm', None, '單位不同，先確認可比且已統一單位，不擅自換算。')
        mode = input_data.get('comparison')
        if mode is None:
            return result('confirm', None, '請確認比較方向，本包只接受左對右。')
        if mode != 'left-vs-right':
            return result('reject', None, 'comparison只允許left-vs-right，不默默反轉。')
        l, r = left['quantity'], right['quantity']
        # Pair off units, rather than trusting any authored relation symbol.
        l_remaining, r_remaining = l, r
        while l_remaining and r_remaining:
            l_remaining -= 1
            r_remaining -= 1
        answer = '>' if l_remaining else ('<' if r_remaining else '=')
        if 'proposed' in input_data:
            proposed = input_data['proposed']
            if proposed not in ('<', '=', '>'):
                return result('reject', answer, '提案只可用<、=或>；原題仍有正確比較。')
            if proposed != answer:
                return result('reject', answer, '學生符號方向或等量判斷錯，重新一一配對。')
        return result('pass', answer, '同單位逐一配對，依左右剩餘量得關係。')

    start, direction, steps = (input_data.get('start'), input_data.get('direction'),
                                input_data.get('steps'))
    bad = validate_quantity(start, '起點')
    if bad:
        return bad
    if direction is None:
        return result('confirm', None, '缺少方向，請確認每次加1或減1。')
    if direction not in ('forward', 'backward'):
        return result('reject', None, 'direction只能是forward或backward；不猜方向。')
    if steps is None:
        return result('confirm', None, '缺少次數，無法知道停止位置。')
    if not natural_0_100(steps):
        return result('reject', None, '次數必須是0至100整數，不能是負數或布林。')
    delta = 1 if direction == 'forward' else -1
    answer, current = [], start
    for _ in range(steps):
        current += delta
        if not natural_0_100(current):
            return result('block', None, '逐步數數將越過0–100，本包不擴入101以上或負數。')
        answer.append(current)
    if 'proposed' in input_data:
        proposed = input_data['proposed']
        if (not isinstance(proposed, list)
                or any(type(n) is not int for n in proposed)):
            return result('reject', answer, '學生提案須是整數序列，原題仍可逐步列出正解。')
        if proposed != answer:
            return result('reject', answer, '學生序列不合固定步幅或誤把起點算一步。')
    return result('pass', answer, '每移動一次才記一數，起點不列入答案。')


def same_json_value(a, b):
    """JSON numbers, booleans and null are distinct even in nested answers."""
    if type(a) is not type(b):
        return False
    if isinstance(a, dict):
        return a.keys() == b.keys() and all(same_json_value(a[k], b[k]) for k in a)
    if isinstance(a, list):
        return len(a) == len(b) and all(same_json_value(x, y) for x, y in zip(a, b))
    return a == b


def validate_pack(pack):
    """Return errors; derive outputs with evaluate(subtype, input), not expectations."""
    errors = []
    if not isinstance(pack, dict) or not isinstance(pack.get('cases'), list):
        return ['頂層必須為含cases陣列的物件。']
    if pack.get('teacherReviewed') is not False or pack.get('appConnected') is not False:
        errors.append('整包不得冒稱教師驗收或接入App。')
    cases = pack['cases']
    if len(cases) != 72:
        errors.append('本包應恰有72案例。')
    ids = [case.get('id') for case in cases]
    if len(set(ids)) != len(ids):
        errors.append('case id重複。')
    for subtype in SUBTYPES:
        rows = [c for c in cases if c.get('subtypeId') == subtype]
        if len(rows) != 24:
            errors.append(subtype + '應24例。')
        if Counter(c.get('kind') for c in rows) != Counter(KIND_COUNTS):
            errors.append(subtype + '各kind數量不符8/6/4/2/4。')
        normal_inputs = {json.dumps(c['input'], sort_keys=True, ensure_ascii=False)
                         for c in rows if c.get('kind') == 'normal'}
        for c in rows:
            if c.get('kind') == 'holdout' and json.dumps(c['input'], sort_keys=True,
                                                          ensure_ascii=False) in normal_inputs:
                errors.append(c['id'] + ': holdout複製normal input。')
    for c in cases:
        name = c.get('id', '<missing id>')
        if c.get('code') != 'N-1-1':
            errors.append(name + ': 不屬N-1-1。')
        if c.get('teacherReviewed') is not False or c.get('appConnected') is not False:
            errors.append(name + ': 不得冒稱教師審核或App接入。')
        for text_field in ('prompt', 'why'):
            if not isinstance(c.get(text_field), str) or not c[text_field].strip():
                errors.append(name + ': 缺' + text_field)
        if (not isinstance(c.get('solutionSteps'), list)
                or not c['solutionSteps']
                or any(not isinstance(s, str) or not s.strip() for s in c['solutionSteps'])):
            errors.append(name + ': 解題步驟不得空白。')
        got = evaluate(c.get('subtypeId'), c.get('input'))
        if got['decision'] != c.get('expectedDecision'):
            errors.append(name + ': decision expected=' + str(c.get('expectedDecision'))
                          + ' actual=' + got['decision'] + '; ' + got['reason'])
        if not same_json_value(got['answer'], c.get('expectedAnswer')):
            errors.append(name + ': answer expected=' + repr(c.get('expectedAnswer'))
                          + ' actual=' + repr(got['answer']))
        if c.get('kind') == 'ambiguous' and got['decision'] != 'confirm':
            errors.append(name + ': ambiguous必須真的缺條件。')
        if c.get('kind') == 'negative' and got['decision'] != 'reject':
            errors.append(name + ': negative必須有可指出的錯提案或非法入參。')
    return errors


def contract_probes():
    """Additional independent cases; none read the pack's authored expectations."""
    probes = [
        ('tens-ones', {'quantity': 100}, 'pass', {'tens': 10, 'ones': 0}),
        ('tens-ones', {'quantity': 0}, 'pass', {'tens': 0, 'ones': 0}),
        ('tens-ones', {'quantity': True}, 'reject', None),
        ('tens-ones', {'quantity': 12.0}, 'reject', None),
        ('tens-ones', {'quantity': '30'}, 'reject', None),
        ('tens-ones', {}, 'confirm', None),
        ('tens-ones', {'quantity': 18, 'proposed': {'tens': 1, 'ones': 8}},
         'pass', {'tens': 1, 'ones': 8}),
        ('tens-ones', {'quantity': 18, 'proposed': {'tens': 0, 'ones': 18}},
         'reject', {'tens': 1, 'ones': 8}),
        ('compare', {'left': {'quantity': 2, 'unit': '根'},
                     'right': {'quantity': 10, 'unit': '捆'},
                     'comparison': 'left-vs-right'}, 'confirm', None),
        ('compare', {'left': {'quantity': 4, 'unit': '根'},
                     'right': {'quantity': 4, 'unit': '根'},
                     'comparison': 'left-vs-right', 'proposed': '='}, 'pass', '='),
        ('compare', {'left': {'quantity': 11, 'unit': '根'},
                     'right': {'quantity': 2, 'unit': '根'},
                     'comparison': 'left-vs-right'}, 'pass', '>'),
        ('compare', {'left': {'quantity': 0, 'unit': '根'},
                     'right': {'quantity': 100, 'unit': '根'},
                     'comparison': 'left-vs-right'}, 'pass', '<'),
        ('count', {'start': 0, 'direction': 'backward', 'steps': 0}, 'pass', []),
        ('count', {'start': 100, 'direction': 'forward', 'steps': 0}, 'pass', []),
        ('count', {'start': 0, 'direction': 'backward', 'steps': 1}, 'block', None),
        ('count', {'start': 100, 'direction': 'forward', 'steps': 1}, 'block', None),
        ('count', {'start': 95, 'direction': 'forward', 'steps': 5},
         'pass', [96, 97, 98, 99, 100]),
        ('count', {'start': 5, 'direction': 'backward', 'steps': 5},
         'pass', [4, 3, 2, 1, 0]),
        ('count', {'start': 50, 'direction': 'sideways', 'steps': 1}, 'reject', None),
        ('count', {'start': 50, 'direction': 'forward', 'steps': True}, 'reject', None),
        ('count', {'start': 50, 'direction': 'forward', 'steps': 101}, 'reject', None),
        ('count', {'start': 50, 'direction': 'forward'}, 'confirm', None),
    ]
    errors = []
    for index, (subtype, data, decision, answer) in enumerate(probes, 1):
        got = evaluate(subtype, data)
        if (got['decision'], got['answer']) != (decision, answer):
            errors.append('contract probe %d failed: %r' % (index, got))
    return len(probes), errors


def mutation_probes(pack):
    """Prove wrong expected fields cannot pass by merely comparing them to themselves."""
    errors = []
    answer_mutation = copy.deepcopy(pack)
    answer_mutation['cases'][0]['expectedAnswer'] = {'tens': 99, 'ones': 99}
    if not any('answer expected=' in e for e in validate_pack(answer_mutation)):
        errors.append('篡改預期答案未被檢出。')
    decision_mutation = copy.deepcopy(pack)
    decision_mutation['cases'][0]['expectedDecision'] = 'confirm'
    if not any('decision expected=' in e for e in validate_pack(decision_mutation)):
        errors.append('篡改預期決策未被檢出。')
    type_mutation = copy.deepcopy(pack)
    # This case's tens should be zero, not JSON false (Python normally equates them).
    zero_case = next(c for c in type_mutation['cases']
                     if c['subtypeId'] == 'tens-ones'
                     and c['expectedAnswer'] == {'tens': 0, 'ones': 7})
    zero_case['expectedAnswer']['tens'] = False
    if not any('answer expected=' in e for e in validate_pack(type_mutation)):
        errors.append('布林值混入數量答案未被檢出。')
    return 3, errors


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('path', nargs='?', type=Path,
                        default=Path(__file__).with_name('grade1-place-value.json'))
    args = parser.parse_args(argv)
    pack = json.loads(args.path.read_text(encoding='utf-8'))
    errors = validate_pack(pack)
    n_probes, probe_errors = contract_probes()
    n_mutations, mutation_errors = mutation_probes(pack)
    errors += probe_errors + mutation_errors
    if errors:
        for error in errors:
            print('FAIL:', error)
        return 1
    decisions = Counter(evaluate(c['subtypeId'], c['input'])['decision']
                        for c in pack['cases'])
    print('PASS: N-1-1 / 3 subtypes / 72 authored cases (24 per subtype).')
    print('Kinds per subtype: normal=8 negative=6 boundary=4 ambiguous=2 holdout=4.')
    print('Independently derived decisions:', json.dumps(dict(sorted(decisions.items()))))
    print('PASS: %d contract probes; %d expected-field mutation probes detected.'
          % (n_probes, n_mutations))
    print('teacherReviewed=false; appConnected=false; not full curriculum approval.')
    return 0


if __name__ == '__main__':
    raise SystemExit(main())
