#!/usr/bin/env python3
"""Offline fraction assessment oracle; safe to import. No expected/id/kind in evaluate.
Three authored subtypes with 24 cases each are NOT whole-curriculum teacher approval.
"""
import argparse
import copy
import json
import math
from collections import Counter
from fractions import Fraction
from pathlib import Path

GRADE = 5
CODE = 'N-5-4'
PREFIX = 'g5.unlike'
NAME = 'grade5-different-denominators'
OPERATIONS = ['compare', 'add', 'subtract']
SUBTYPES = tuple(PREFIX + '.' + op for op in OPERATIONS)
KINDS = {'normal': 8, 'negative': 6, 'boundary': 4, 'ambiguous': 2, 'holdout': 4}


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


def parse_fraction(data):
    """Return (exact value, original denominator, whole, error), never guess a digit."""
    if data is None:
        return None, None, None, output('confirm', None, '分數數值尚未確認。')
    if not isinstance(data, dict):
        return None, None, None, output('reject', None, '分數入參必須是物件。')
    n, d, w = data.get('numerator'), data.get('denominator'), data.get('whole', 0)
    if n is None or d is None or w is None:
        return None, None, None, output('confirm', None, '分子、分母或已出現的整張量缺漏。')
    if any(type(x) is not int for x in (n, d, w)):
        return None, None, None, output('reject', None, '數值須JSON整數，不接受布林、小數型別或字串。')
    if n < 0 or w < 0 or d <= 0:
        return None, None, None, output('reject', None, '已知物件分數須非負，分母必須正且不為0。')
    return Fraction(w) + Fraction(n, d), d, w, None


def allowed_grade5_denominators(a, b):
    """Exact official three-way restriction, not an unrestricted rational domain."""
    if a <= 9 and b <= 9:
        return True
    if max(a, b) < 100 and (a % b == 0 or b % a == 0):
        return True
    # The common multiple need not be the least common multiple.
    return any(a*i == b*j for i in range(2,6) for j in range(2,6))


def canonical_answer(value, original_denominator):
    if GRADE == 3:
        units = value * original_denominator
        assert units.denominator == 1
        # Do not require simplification/terminology beyond grade-three unit counting.
        return {'numerator': units.numerator, 'denominator': original_denominator}
    if GRADE == 4:
        w, rem = divmod(value.numerator, value.denominator)
        return {'whole': w, 'numerator': rem, 'denominator': value.denominator}
    return {'numerator': value.numerator, 'denominator': value.denominator}


def evaluate(subtype_id, input_data):
    """Return decision/answer/reason derived only from subtype and input conditions.

    Correct equivalent student fractions are accepted, even when unreduced or in a
    different equivalent representation. A wrong proposal never erases a legal task.
    """
    if subtype_id not in SUBTYPES:
        return output('block', None, '此子型不在本包，禁止由名稱猜另一年級解法。')
    if not isinstance(input_data, dict):
        return output('reject', None, 'input必須是JSON物件。')
    unit = input_data.get('unit')
    if unit is None or (isinstance(unit, str) and not unit.strip()):
        return output('confirm', None, '缺少共同計量單位，先確認。')
    if not isinstance(unit, str):
        return output('reject', None, 'unit須非空字串。')
    same = input_data.get('sameWhole')
    if same is None or same is False:
        return output('confirm', None, '須先確認共用同大小整體，不能默認兩張不同紙同大。')
    if same is not True:
        return output('reject', None, 'sameWhole須明確布林值，不把1或字串true當條件。')
    a, da, wa, bad = parse_fraction(input_data.get('left'))
    if bad:
        return bad
    op = subtype_id[len(PREFIX) + 1:]
    b, db, wb = None, None, None
    if op == 'integer-multiple':
        m = input_data.get('multiplier')
        if m is None:
            return output('confirm', None, '缺少取幾份的非負整數倍數。')
        if type(m) is not int or m < 0:
            return output('reject', None, '份數須非負整數，不能是負數、分數、布林或字串。')
        operation = 'multiply'
    else:
        b, db, wb, bad = parse_fraction(input_data.get('right'))
        if bad:
            return bad
        operation = op
        if op == 'add-subtract':
            operation = input_data.get('operation')
            if operation is None:
                return output('confirm', None, '請確認題目要合併或取走；不同操作可有不同答案。')
            if operation not in ('add', 'subtract'):
                return output('reject', None, 'operation只能add或subtract。')
        if GRADE in (3, 4) and da != db:
            return output('block', None, '原題可另解，但分母不同，不屬此同分母子型。')
        if GRADE == 5:
            if da == db:
                return output('block', None, '這是同分母題，轉同分母子型，不宣稱原題無解。')
            if not allowed_grade5_denominators(da, db):
                return output('block', None, '通分分母超出本碼宣告的三種原課綱範圍。')
    if GRADE == 3 and (wa != 0 or (wb is not None and wb != 0)):
        return output('block', None, '本包三年級只用分子分母的份數表示，不要求整張另列格式。')
    if GRADE == 3 and (a > 2 or (b is not None and b > 2)):
        return output('block', None, '本碼所有已知分數與結果不能超過2。')
    if operation == 'compare':
        exact = None
        answer = '<' if a < b else ('>' if a > b else '=')
    else:
        exact = a + b if operation == 'add' else (a - b if operation == 'subtract' else a * m)
        if exact < 0:
            return output('block', None, '取走量超過已有的非負分數量，先確認情境或轉適合範圍。')
        if GRADE == 3 and exact > 2:
            return output('block', None, '結果超過本碼的2，轉適合範圍，不硬給本碼通過。')
        answer = canonical_answer(exact, da)
    if 'proposed' in input_data:
        proposed = input_data['proposed']
        if operation == 'compare':
            if proposed not in ('<', '=', '>') or proposed != answer:
                return output('reject', answer, '學生關係符號不正確，原題仍提供正確方向。')
        else:
            candidate, _, _, bad = parse_fraction(proposed)
            if bad or candidate != exact:
                return output('reject', answer, '學生提案格式或數值錯誤，原題仍提供正解。')
    return output('pass', answer, '條件完整且精確分數核對一致；等值寫法不判錯。')


def same_json(a, b):
    if type(a) is not type(b):
        return False
    if isinstance(a, dict):
        return a.keys() == b.keys() and all(same_json(a[k], b[k]) for k in a)
    if isinstance(a, list):
        return len(a) == len(b) and all(same_json(x, y) for x, y in zip(a, b))
    return a == b


def validate_pack(pack):
    errors = []
    if not isinstance(pack, dict) or not isinstance(pack.get('cases'), list):
        return ['頂層需含cases陣列。']
    rows = pack['cases']
    if len(rows) != 72 or pack.get('code') != CODE:
        errors.append('包碼或72例數目不符。')
    if pack.get('teacherReviewed') is not False or pack.get('appConnected') is not False:
        errors.append('不得冒稱教師驗收或接入App。')
    if len({r.get('id') for r in rows}) != len(rows):
        errors.append('case id重複。')
    for subtype in SUBTYPES:
        subset = [r for r in rows if r.get('subtypeId') == subtype]
        if Counter(r.get('kind') for r in subset) != Counter(KINDS):
            errors.append(subtype + ': 應24例，kind為8/6/4/2/4。')
        normals = {json.dumps(r['input'], sort_keys=True) for r in subset if r.get('kind') == 'normal'}
        for r in subset:
            if r.get('kind') == 'holdout' and json.dumps(r['input'], sort_keys=True) in normals:
                errors.append(r['id'] + ': holdout不可只複製normal改ID。')
    for row in rows:
        label = row.get('id', '<missing>')
        if row.get('code') != CODE:
            errors.append(label + ': case code錯誤。')
        if row.get('casePurpose') not in ('teaching-example', 'proposal-review', 'validator-guard'):
            errors.append(label + ': 缺casePurpose。')
        if row.get('studentFacing') is not (row.get('casePurpose') != 'validator-guard'):
            errors.append(label + ': studentFacing須依casePurpose區隔工程守衛。')
        if row.get('teacherReviewed') is not False or row.get('appConnected') is not False:
            errors.append(label + ': 狀態不得冒稱通過。')
        if not row.get('prompt') or not row.get('why') or not row.get('solutionSteps'):
            errors.append(label + ': 缺題意或解題依據。')
        if any(not isinstance(s, str) or not s.strip() for s in row.get('solutionSteps', [])):
            errors.append(label + ': 有空白步驟。')
        got = evaluate(row.get('subtypeId'), row.get('input'))
        if got['decision'] != row.get('expectedDecision'):
            errors.append(label + ': decision mismatch ' + str(got))
        if not same_json(got['answer'], row.get('expectedAnswer')):
            errors.append(label + ': answer mismatch actual=' + repr(got['answer']))
        if row.get('kind') == 'ambiguous' and got['decision'] != 'confirm':
            errors.append(label + ': ambiguous應真缺條件。')
        if row.get('casePurpose') == 'proposal-review' and 'proposed' not in row['input']:
            errors.append(label + ': 提案檢查須帶學生提案。')
        if got['decision'] == 'block' and row.get('casePurpose') != 'validator-guard':
            errors.append(label + ': 範圍/路由守衛不得冒充一般學生題。')
    return errors


def probes():
    def frac(n, d, w=0):
        return {'numerator': n, 'denominator': d, 'whole': w}
    def data(a, b=None, **kwargs):
        value = {'unit': '同規格紙片（張）', 'sameWhole': True, 'left': a}
        if b is not None:
            value['right'] = b
        value.update(kwargs)
        return value
    p = []
    compare = PREFIX + '.compare'
    p += [(compare, data(frac(1, 2), frac(0, 2 if GRADE < 5 else 3)), 'pass', '>'),
          (compare, data(frac(0, 2), frac(0, 2 if GRADE < 5 else 3)), 'pass', '='),
          (compare, data(frac(True, 2), frac(1, 2 if GRADE < 5 else 3)), 'reject', None),
          (compare, data(frac(1, 0), frac(1, 2)), 'reject', None),
          (compare, data(frac(None, 2), frac(1, 2)), 'confirm', None),
          (compare, data(frac(1, 2), frac(1, 2 if GRADE < 5 else 3), sameWhole=None), 'confirm', None)]
    if GRADE == 3:
        p += [(PREFIX + '.add', data(frac(1, 3), frac(1, 3), proposed=frac(2, 3)),
               'pass', {'numerator': 2, 'denominator': 3}),
              (PREFIX + '.add', data(frac(1, 4), frac(1, 4), proposed=frac(1, 2)),
               'pass', {'numerator': 2, 'denominator': 4}),
              (PREFIX + '.add', data(frac(4, 3), frac(2, 3)),
               'pass', {'numerator': 6, 'denominator': 3}),
              (PREFIX + '.add', data(frac(4, 3), frac(3, 3)), 'block', None),
              (PREFIX + '.subtract', data(frac(1, 3), frac(2, 3)), 'block', None)]
    elif GRADE == 4:
        p += [(PREFIX + '.add-subtract', data(frac(1, 4, 2), frac(3, 4, 1), operation='subtract'),
               'pass', {'whole': 0, 'numerator': 1, 'denominator': 2}),
              (PREFIX + '.integer-multiple', data(frac(1, 2, 1), multiplier=0),
               'pass', {'whole': 0, 'numerator': 0, 'denominator': 1}),
              (PREFIX + '.integer-multiple', data(frac(1, 2, 1), multiplier=2, proposed=frac(6, 2)),
               'pass', {'whole': 3, 'numerator': 0, 'denominator': 1}),
              (PREFIX + '.integer-multiple', data(frac(1, 2), multiplier=True), 'reject', None),
              (PREFIX + '.add-subtract', data(frac(1, 4), frac(1, 4)), 'confirm', None)]
    else:
        p += [(PREFIX + '.add', data(frac(1, 12), frac(1, 18)),
               'pass', {'numerator': 5, 'denominator': 36}),
              (PREFIX + '.compare', data(frac(1, 33), frac(3, 99)), 'pass', '='),
              (PREFIX + '.add', data(frac(1, 100), frac(1, 200)), 'pass', {'numerator':3,'denominator':200}),
              (PREFIX + '.add', data(frac(1, 11), frac(1, 13)), 'block', None),
              (PREFIX + '.add', data(frac(1, 12), frac(1, 20), proposed=frac(8, 60)),
               'pass', {'numerator': 2, 'denominator': 15}),
              (PREFIX + '.subtract', data(frac(1, 3), frac(1, 2)), 'block', None)]
    errors = []
    for index, (subtype, given, dec, ans) in enumerate(p, 1):
        got = evaluate(subtype, given)
        if got['decision'] != dec or not same_json(got['answer'], ans):
            errors.append('probe %d: %r' % (index, got))
    return len(p), errors


def mutations(pack):
    errors = []
    expected_mutation = copy.deepcopy(pack)
    expected_mutation['cases'][0]['expectedAnswer'] = {'numerator': 999, 'denominator': 1}
    if not any('answer mismatch' in e for e in validate_pack(expected_mutation)):
        errors.append('expected-answer篡改未檢出。')
    decision_mutation = copy.deepcopy(pack)
    decision_mutation['cases'][0]['expectedDecision'] = 'confirm'
    if not any('decision mismatch' in e for e in validate_pack(decision_mutation)):
        errors.append('expected-decision篡改未檢出。')
    input_mutation = copy.deepcopy(pack)
    row = next(r for r in input_mutation['cases'] if r['kind'] == 'normal'
               and r['subtypeId'].endswith(('.add', '.add-subtract')))
    row['input']['left']['numerator'] += 1
    if not any('answer mismatch' in e or 'decision mismatch' in e
               for e in validate_pack(input_mutation)):
        errors.append('input數值篡改未檢出；不應只看expected。')
    return 3, errors


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('path', nargs='?', type=Path,
                        default=Path(__file__).with_name(NAME + '.json'))
    args = parser.parse_args(argv)
    pack = json.loads(args.path.read_text(encoding='utf-8'))
    errors = validate_pack(pack)
    np, pe = probes()
    nm, me = mutations(pack)
    errors += pe + me
    if errors:
        for error in errors:
            print('FAIL:', error)
        return 1
    counts = Counter(evaluate(r['subtypeId'], r['input'])['decision'] for r in pack['cases'])
    print('PASS:', CODE, '/ 3 subtypes / 72 authored cases / 8+6+4+2+4 per subtype')
    print('Decisions:', json.dumps(dict(sorted(counts.items()))))
    print('PASS:', np, 'independent contract probes;', nm, 'expected/input mutation probes detected.')
    print('teacherReviewed=false; appConnected=false; not all 204 codes approved.')
    return 0


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