#!/usr/bin/env python3
# Standalone merged source; statically prefixed AST preserves both source namespaces.
import json as _legacy_json, sys as _legacy_sys, pathlib as _legacy_pathlib, math as _legacy_math, copy as _legacy_copy, collections as _legacy_collections, re as _legacy_re
from fractions import Fraction as _legacy_Fraction
_legacy_PACK = 'grade2-ruler-operation-methods'
_legacy_SUBTYPES = {'g2-geo-ruler-read': 'ruler-read', 'g2-geo-ruler-mark': 'ruler-mark'}
_legacy_REQ = {'touch-features': ['observations'], 'aligned-length': ['aEnd', 'bEnd', 'sameStart', 'sameDirection', 'orderedMarks'], 'plane-classify': ['items', 'allContoursConfirmed'], 'solid-classify': ['items', 'allSurfacesConfirmed'], 'ruler-read': ['start', 'end', 'unit', 'straightAligned'], 'ruler-mark': ['start', 'length', 'maximum', 'unit'], 'boundary-sum': ['edges', 'unit', 'closedBoundary', 'allEdgesOnce'], 'equal-edge-complete': ['shape', 'edges', 'unit', 'shapeConfirmed', 'equalRelationsConfirmed'], 'tile-compare': ['aTiles', 'bTiles', 'sameTile', 'aFilled', 'bFilled', 'noOverlap'], 'cut-preserve': ['originalPieces', 'keptPieces', 'samePieces', 'noStretch', 'noOverlap'], 'overlay-containment': ['aOnlyRegions', 'bOnlyRegions', 'sharedRegions', 'allRegionsConfirmed', 'noStretch', 'noOverlap']}

def _legacy_out(d, a=None, r=''):
    return {'decision': d, 'answer': a, 'reason': r}

def _legacy_natural(v, lo=0, hi=100):
    if type(v) is not int or not lo <= v <= hi:
        raise ValueError('原量需有限整數')
    return v

def _legacy_flag(v):
    if type(v) is not bool:
        raise ValueError('條件需已確認是或否')
    return v

def _legacy_enum(v, vs):
    if type(v) is not str or v not in vs:
        raise ValueError('不在此有限方法')
    return v

def _legacy_relation(a, b):
    return '甲較長' if a > b else '乙較長' if a < b else '一樣長'

def _legacy_same_answer(p, a):
    if type(a) is int:
        if type(p) is bool or type(p) is float:
            return False
        if type(p) is int:
            return abs(p) < 10 ** 80 and p == a
        if type(p) is str and 1 <= len(p) <= 80 and _legacy_re.fullmatch('[+-]?(?:[0-9]{1,80}(?:/[0-9]{1,80}|\\.[0-9]{0,80})?|\\.[0-9]{1,80})', p, _legacy_re.ASCII):
            if '/' in p and (not any((x != '0' for x in p.split('/')[1]))):
                return False
            try:
                return _legacy_Fraction(p) == a
            except (ValueError, ZeroDivisionError):
                return False
        return False
    if type(a) is bool:
        return type(p) is bool and p == a
    if type(a) is dict:
        return type(p) is dict and set(p) == set(a) and all((_legacy_same_answer(p[k], a[k]) for k in a))
    if type(a) is list:
        return type(p) is list and len(p) == len(a) and all((_legacy_same_answer(x, y) for (x, y) in zip(p, a)))
    return type(p) is type(a) and p == a

def _legacy_missing(mode, r):
    if any((k not in r or r[k] is None for k in _legacy_REQ[mode])):
        return True
    if mode == 'touch-features' and type(r['observations']) is list and (len(r['observations']) <= 4):
        return any((x is None for x in r['observations']))
    if mode in ('plane-classify', 'solid-classify') and type(r['items']) is list and (len(r['items']) <= 4):
        fields = ('straightSides', 'curvedBoundary', 'closed', 'circleConfirmed') if mode == 'plane-classify' else ('flatFaces', 'curvedSide', 'roundFlatEnds', 'boxLayout', 'ballConfirmed')
        for x in r['items']:
            if type(x) is not dict:
                continue
            if any((k not in x or x[k] is None for k in fields)):
                return True
            if mode == 'solid-classify' and x.get('flatFaces') == 2 and (x.get('curvedSide') is True) and (x.get('roundFlatEnds') == 2) and (x.get('boxLayout') is False):
                if any((k not in x or x[k] is None for k in ('equalRoundEnds', 'uniformThickness', 'columnLayout'))):
                    return True
        return False
    if mode in ('boundary-sum', 'equal-edge-complete') and type(r['edges']) is list and (len(r['edges']) <= 8):
        return any((x is None for x in r['edges']))
    return False

def _legacy_evaluate(subtype_id, r):
    if type(subtype_id) is not str or subtype_id not in _legacy_SUBTYPES or type(r) is not dict:
        return _legacy_out('block', r='非本有限文字方法')
    mode = _legacy_SUBTYPES[subtype_id]
    if r.get('confirmed') is not True or _legacy_missing(mode, r):
        return _legacy_out('confirm', r='先確認缺少的原條件，不由圖形名稱或外觀補值')
    if set(r) - set(_legacy_REQ[mode]) - {'confirmed', 'task', 'proposal'} or type(r.get('task')) is not str or r['task'] not in ('solve', 'check_proposal'):
        return _legacy_out('block', r='結構或任務不符')
    try:
        if mode == 'touch-features':
            xs = r['observations']
            mp = {'flat-patch': '平平的面', 'curved-patch': '彎彎的面', 'two-faces-line': '邊', 'edges-meet-point': '角'}
            if type(xs) is not list or not 1 <= len(xs) <= 4:
                raise ValueError()
            ans = {'features': [mp[_legacy_enum(x, mp)] for x in xs]}
        elif mode == 'aligned-length':
            a = _legacy_natural(r['aEnd'], 1, 30)
            b = _legacy_natural(r['bEnd'], 1, 30)
            if not all((_legacy_flag(r[k]) for k in ('sameStart', 'sameDirection', 'orderedMarks'))):
                return _legacy_out('confirm', r='先把左端排齊、朝同一方向，再確認比較記號的先後')
            ans = {'relation': _legacy_relation(a, b)}
        elif mode in ('plane-classify', 'solid-classify'):
            xs = r['items']
            if type(xs) is not list or not 1 <= len(xs) <= 4:
                raise ValueError()
            if not _legacy_flag(r['allContoursConfirmed' if mode == 'plane-classify' else 'allSurfacesConfirmed']):
                return _legacy_out('confirm', r='需確認完整輪廓或轉動後全部表面，不能猜背面')
            kinds = []
            for x in xs:
                if type(x) is not dict:
                    raise ValueError()
                if mode == 'plane-classify':
                    if set(x) != {'straightSides', 'curvedBoundary', 'closed', 'circleConfirmed'}:
                        raise ValueError()
                    s = _legacy_natural(x['straightSides'], 0, 8)
                    cur = _legacy_flag(x['curvedBoundary'])
                    cl = _legacy_flag(x['closed'])
                    circle = _legacy_flag(x['circleConfirmed'])
                    if circle and (s != 0 or not cur):
                        raise ValueError()
                    if not cl:
                        return _legacy_out('confirm', r='先確認要辨認的是完整封閉輪廓')
                    if cur and s == 0:
                        k = '圓形輪廓'
                    elif not cur and s == 3:
                        k = '三角形'
                    elif not cur and s == 4:
                        k = '四邊形'
                    else:
                        return _legacy_out('block', r='本型只已確認圓輪廓或三、四條直邊封閉圖形')
                    if cur and (not circle):
                        k = '有彎曲邊界，不能只憑此確定是圓'
                else:
                    baseKeys = {'flatFaces', 'curvedSide', 'roundFlatEnds', 'boxLayout', 'ballConfirmed'}
                    isColumnCandidate = x.get('flatFaces') == 2 and x.get('curvedSide') is True and (x.get('roundFlatEnds') == 2) and (x.get('boxLayout') is False)
                    expectedKeys = baseKeys | {'equalRoundEnds', 'uniformThickness', 'columnLayout'} if isColumnCandidate else baseKeys
                    if set(x) != expectedKeys:
                        raise ValueError()
                    f = _legacy_natural(x['flatFaces'], 0, 6)
                    cur = _legacy_flag(x['curvedSide'])
                    ends = _legacy_natural(x['roundFlatEnds'], 0, 2)
                    box = _legacy_flag(x['boxLayout'])
                    ball = _legacy_flag(x['ballConfirmed'])
                    if ball and (f != 0 or not cur or ends != 0 or box):
                        raise ValueError()
                    if f == 6 and (not cur) and (ends == 0) and box:
                        k = '盒狀物'
                    elif f == 2 and cur and (ends == 2) and (not box):
                        equalEnds = _legacy_flag(x['equalRoundEnds'])
                        uniform = _legacy_flag(x['uniformThickness'])
                        layout = _legacy_flag(x['columnLayout'])
                        k = '圓柱狀物' if equalEnds and uniform and layout else '有兩個平圓端面與曲側面，但已確認不是本型圓柱狀物'
                    elif f == 0 and cur and (ends == 0) and (not box):
                        k = '球狀物' if ball else '只有曲面，不能只憑此確定是球'
                    else:
                        return _legacy_out('block', r='已確認表面條件與本型特徵不一致，先重新觀察')
                kinds.append(k)
            ans = {'classifications': kinds}
        elif mode == 'ruler-read':
            s = _legacy_natural(r['start'])
            e = _legacy_natural(r['end'])
            _legacy_enum(r['unit'], ('cm',))
            if not _legacy_flag(r['straightAligned']):
                return _legacy_out('confirm', r='尺與物品需平貼同方向')
            if e < s:
                raise ValueError()
            ans = {'length': e - s, 'unit': 'cm'}
        elif mode == 'ruler-mark':
            s = _legacy_natural(r['start'])
            n = _legacy_natural(r['length'])
            mx = _legacy_natural(r['maximum'])
            _legacy_enum(r['unit'], ('cm',))
            if s > mx or s + n > mx:
                return _legacy_out('block', r='這把尺的已確認可用範圍不夠，換工具或改起點')
            ans = {'end': s + n, 'length': n, 'unit': 'cm'}
        elif mode == 'boundary-sum':
            es = r['edges']
            _legacy_enum(r['unit'], ('cm',))
            if type(es) is not list or not 3 <= len(es) <= 8:
                raise ValueError()
            es = [_legacy_natural(x, 1, 30) for x in es]
            if not _legacy_flag(r['closedBoundary']) or not _legacy_flag(r['allEdgesOnce']):
                return _legacy_out('confirm', r='需核對外框封閉並逐邊量過一次')
            if sum(es) > 100 or max(es) >= sum(es) - max(es):
                return _legacy_out('block', r='原量或已確認外框資料不一致，需重測，不能當有效外框')
            ans = {'perimeter': sum(es), 'unit': 'cm'}
        elif mode == 'equal-edge-complete':
            _legacy_enum(r['shape'], ('square', 'rectangle'))
            _legacy_enum(r['unit'], ('cm',))
            es = r['edges']
            if type(es) is not list or len(es) != 4:
                raise ValueError()
            known = es[:]
            resolving = set()

            def resolve(i):
                if i in resolving:
                    raise ValueError('等長引用無已知量')
                x = known[i]
                if type(x) is int:
                    return _legacy_natural(x, 1, 25)
                if type(x) is not str or x not in ('same-as-1', 'same-as-2', 'same-as-3', 'same-as-4'):
                    raise ValueError()
                resolving.add(i)
                v = resolve(int(x[-1]) - 1)
                resolving.remove(i)
                return v
            es = [resolve(i) for i in range(4)]
            if not _legacy_flag(r['shapeConfirmed']) or not _legacy_flag(r['equalRelationsConfirmed']):
                return _legacy_out('confirm', r='先確認實物形狀與等長邊關係，不由名字補邊')
            if r['shape'] == 'square' and len(set(es)) != 1 or (r['shape'] == 'rectangle' and (es[0] != es[2] or es[1] != es[3])):
                return _legacy_out('block', r='逐邊原量與已確認等長關係矛盾，請重測')
            ans = {'edges': es, 'perimeter': sum(es), 'unit': 'cm'}
        elif mode == 'tile-compare':
            a = _legacy_natural(r['aTiles'], 1, 60)
            b = _legacy_natural(r['bTiles'], 1, 60)
            if not all((_legacy_flag(r[k]) for k in ('sameTile', 'aFilled', 'bFilled', 'noOverlap'))):
                return _legacy_out('confirm', r='先用同大方片無重疊、無空隙鋪滿兩張紙，才能比塊數')
            ans = {'relation': '甲較大' if a > b else '乙較大' if a < b else '一樣大'}
        elif mode == 'cut-preserve':
            n = _legacy_natural(r['originalPieces'], 1, 30)
            kept = _legacy_natural(r['keptPieces'], 0, 30)
            if kept > n:
                raise ValueError()
            if not all((_legacy_flag(r[k]) for k in ('samePieces', 'noStretch', 'noOverlap'))):
                return _legacy_out('confirm', r='先確認使用原來那些紙片、沒有拉伸或重疊')
            ans = {'relation': '面積不變' if n == kept else '面積變小', 'lostPieces': n - kept}
        elif mode == 'overlay-containment':
            a = _legacy_natural(r['aOnlyRegions'], 0, 20)
            b = _legacy_natural(r['bOnlyRegions'], 0, 20)
            shared = _legacy_natural(r['sharedRegions'], 1, 20)
            if not all((_legacy_flag(r[k]) for k in ('allRegionsConfirmed', 'noStretch', 'noOverlap'))):
                return _legacy_out('confirm', r='先確認整張重疊分區、紙沒有伸縮，不能只看局部')
            if a and b:
                return _legacy_out('confirm', r='兩張各有露出的部分，區塊不保證同大；需再用同大方片或拼補比較')
            ans = {'relation': '甲較大' if a else '乙較大' if b else '一樣大'}
        else:
            raise ValueError()
    except (ValueError, TypeError, KeyError, OverflowError):
        return _legacy_out('block', r='原量、單位或已確認特徵不符此有限方法')
    if r['task'] == 'check_proposal':
        if r.get('proposal') is None:
            return _legacy_out('confirm', ans, '請先說說你的想法')
        if not _legacy_same_answer(r['proposal'], ans):
            return _legacy_out('reject', ans, '保留原條件逐步核對，不改題目湊答案')
    return _legacy_out('pass', ans, '只核對已確認的文字資料；未驗證實物操作或圖片')

def _legacy_check(path=None):
    d = _legacy_json.loads(_legacy_pathlib.Path(path or _legacy_pathlib.Path(__file__).with_name(_legacy_PACK + '.json')).read_text())
    ct = _legacy_collections.Counter()
    rt = 0
    for sid in _legacy_SUBTYPES:
        assert _legacy_collections.Counter((c['kind'] for c in d['cases'] if c['subtypeId'] == sid)) == dict(normal=8, negative=6, boundary=4, ambiguous=2, holdout=4)
    for c in d['cases']:
        res = evaluate(c['subtypeId'], c['input'])
        assert (res['decision'], res['answer']) == (c['expectedDecision'], c['expectedAnswer']), c['id']
        ct[res['decision']] += 1
        if res['answer'] is not None:
            assert evaluate(c['subtypeId'], dict(c['input'], task='check_proposal', proposal=res['answer']))['decision'] == 'pass'
            rt += 1
    print(_legacy_json.dumps({'cases': len(d['cases']), 'roundtrips': rt, 'decisions': dict(ct)}, ensure_ascii=False))

def _legacy_cli_main():
    if len(_legacy_sys.argv) > 1 and _legacy_sys.argv[1] == 'evaluate':
        print(_legacy_json.dumps(evaluate(_legacy_sys.argv[2], _legacy_json.loads(_legacy_sys.argv[3])), ensure_ascii=False))
    else:
        _legacy_check(_legacy_sys.argv[1] if len(_legacy_sys.argv) > 1 else None)

"""Finite confirmed-record references. Never physical/learner ability verification."""
import sys as _r26_sys, json as _r26_json, copy as _r26_copy

class _r26_Bad(Exception):
    pass

class _r26_Need(Exception):
    pass
_r26_SIDS = ('s12-stacking-operation-guidance', 's21-boundary-interior-exterior', 's23-agreed-tolerance-operation-check', 'n313-trace-transfer-and-right-copy')

def _r26_require(ok, msg):
    if not ok:
        raise _r26_Bad(msg)

def _r26_bounded(v, d=0, b=None):
    if b is None:
        b = [0]
    b[0] += 1
    _r26_require(d <= 8 and b[0] <= 1500, '資料結構超過本有限紀錄範圍，請改由人工整理。')
    if type(v) is dict:
        _r26_require(len(v) <= 32, '欄位太多。')
        for (k, x) in v.items():
            _r26_require(type(k) is str and len(k) <= 80, '欄名無效。')
            _r26_bounded(x, d + 1, b)
    elif type(v) is list:
        _r26_require(len(v) <= 80, '紀錄太長。')
        for x in v:
            _r26_bounded(x, d + 1, b)
    elif type(v) is str:
        _r26_require(len(v) <= 200, '文字太長。')
    elif type(v) is int:
        _r26_require(v.bit_length() <= 40, '數字超過本有限紀錄域。')
    else:
        _r26_require(v is None or type(v) is bool, '只收明確整數、文字、布林與有限紀錄。')

def _r26_need(v):
    if v is None:
        raise _r26_Need('請先補上原觀察或原約定，不自行猜測。')
    if type(v) is list:
        for x in v:
            _r26_need(x)
    if type(v) is dict:
        for x in v.values():
            _r26_need(x)

def _r26_fields(i, req):
    for k in req:
        if k not in i:
            raise _r26_Need('請先補上原觀察或原約定，不自行猜測。')
        _r26_need(i[k])

def _r26_boolean(v):
    _r26_require(type(v) is bool, '確認欄須為布林。')
    return v

def _r26_integer(v, lo, hi):
    _r26_require(type(v) is int and lo <= v <= hi, '整數不在本型明列範圍。')
    return v

def _r26_enum(v, values):
    _r26_require(type(v) is str and v in values, '紀錄類別不在本型明列範圍。')
    return v

def _r26_source(i):
    _r26_enum(i['observationSource'], ('teacher-operation-log', 'learner-operation-log'))
    if not _r26_boolean(i['observationConfirmed']):
        raise _r26_Need('原觀察尚未確認，先回到實物或原始紀錄。')

def _r26_equal(a, b):
    return type(a) is type(b) and (set(a) == set(b) and all((_r26_equal(a[k], b[k]) for k in a)) if type(a) is dict else len(a) == len(b) and all((_r26_equal(x, y) for (x, y) in zip(a, b))) if type(a) is list else a == b)

def _r26_stacking(i):
    _r26_fields(i, ['objects', 'plan', 'events', 'adultSafetyConfirmed', 'observationSource', 'observationConfirmed'])
    _r26_source(i)
    if not _r26_boolean(i['adultSafetyConfirmed']):
        raise _r26_Need('請成人先確認材料與操作區，再進行堆疊。')
    objects = i['objects']
    plan = i['plan']
    events = i['events']
    _r26_require(type(objects) is list and 2 <= len(objects) <= 6 and all((type(x) is str and 1 <= len(x) <= 12 for x in objects)) and (len(set(objects)) == len(objects)), '物件需逐一指認且不可重複。')
    _r26_require(type(plan) is list and 1 <= len(plan) <= 5 and (type(events) is list) and (len(events) <= 30), '計畫或觀察次數超出本型。')
    joined = {objects[0]}
    actions = []
    for p in plan:
        _r26_require(type(p) is dict and set(p) == {'lower', 'upper', 'contactFace'}, '每步須指明承接物、放置物與接觸面。')
        _r26_require(type(p['lower']) is str and type(p['upper']) is str and (p['lower'] in joined) and (p['upper'] in objects) and (p['upper'] not in joined), '計畫需先有承接物，不能自接或循環。')
        _r26_require(type(p['contactFace']) is str and 1 <= len(p['contactFace']) <= 30, '須有外部已指認接觸面。')
        joined.add(p['upper'])
        actions.append('把' + p['upper'] + '依指定' + p['contactFace'] + '放到' + p['lower'] + '，鬆手後再觀察。')
    step = 1
    phase = 'place'
    done = 0
    last = '尚未執行觀察。'
    for e in events:
        _r26_require(type(e) is dict and set(e) == {'step', 'action', 'result'}, '操作紀錄欄位不完整。')
        _r26_integer(e['step'], 1, len(plan))
        _r26_enum(e['action'], ('place', 'release-observe', 'remove'))
        _r26_enum(e['result'], ('contact-confirmed', 'stayed', 'slid', 'removed'))
        _r26_require(step <= len(plan) and e['step'] == step, '不可跳過未觀察步驟或完成後多記一步。')
        _r26_require(e['action'] == phase, '原操作順序與當前步驟矛盾，先核對紀錄。')
        if phase == 'place':
            _r26_require(e['result'] == 'contact-confirmed', '放置步只能記已確認接觸。')
            phase = 'release-observe'
            last = '第' + str(step) + '步已放置，還沒有鬆手觀察結果。'
        elif phase == 'release-observe':
            _r26_require(e['result'] in ('stayed', 'slid'), '鬆手後須記原觀察是留在原處或滑落。')
            if e['result'] == 'stayed':
                done = step
                step += 1
                phase = 'place'
                last = '只記錄第' + str(done) + '步鬆手後留在原處，不預測以後一定穩。'
            else:
                phase = 'remove'
                last = '第' + str(step) + '步原紀錄為滑落，先取下再試，不把滑落當不合法題。'
        else:
            _r26_require(e['result'] == 'removed', '取下步須記已取下。')
            phase = 'place'
            last = '第' + str(step) + '步已取下，回到這一步重新放置並觀察。'
    if step > len(plan):
        status = 'complete-record'
        n = None
        hint = '計畫的觀察紀錄已齊；請回實物再試並描述接觸面，這不是能力或穩定性驗證。'
    else:
        status = 'needs-repeat' if phase == 'remove' or (events and events[-1]['action'] == 'remove') else 'awaiting-observation' if phase == 'release-observe' else 'valid-prefix'
        n = {'step': step, 'action': phase}
        hint = '先取下第' + str(step) + '步剛滑落的物件，再重放觀察。' if phase == 'remove' else '第' + str(step) + '步先鬆手觀察，不猜結果。' if phase == 'release-observe' else actions[step - 1]
    a = dict(targetType='堆疊操作紀錄引導', requiredActions=actions, recordStatus=status, observedThroughStep=done, nextAction=n, observationSummary=last, physicalVerified=False, nextStep=hint)
    claim = {k: a[k] for k in ('recordStatus', 'observedThroughStep', 'nextAction', 'physicalVerified')}
    return (a, claim)

def _r26_cross(a, b, p):
    return (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])

def _r26_on(a, b, p):
    return _r26_cross(a, b, p) == 0 and min(a[0], b[0]) <= p[0] <= max(a[0], b[0]) and (min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))

def _r26_hit(a, b, c, d):
    (ca, cb, cc, cd) = (_r26_cross(a, b, c), _r26_cross(a, b, d), _r26_cross(c, d, a), _r26_cross(c, d, b))
    return ca * cb < 0 and cc * cd < 0 or any((v == 0 and _r26_on(x, y, p) for (v, x, y, p) in [(ca, a, b, c), (cb, a, b, d), (cc, c, d, a), (cd, c, d, b)]))

def _r26_point(p):
    _r26_require(type(p) is list and len(p) == 2, '格盤標記資料須為二整數。')
    return [_r26_integer(x, 0, 20) for x in p]

def _r26_locate(poly, p):
    winding = 0
    for (a, b) in zip(poly, poly[1:] + poly[:1]):
        if _r26_on(a, b, p):
            return 'boundary'
        if a[1] <= p[1] < b[1] and _r26_cross(a, b, p) > 0:
            winding += 1
        if b[1] <= p[1] < a[1] and _r26_cross(a, b, p) < 0:
            winding -= 1
    return 'inside' if winding else 'outside'

def _r26_along(poly, a, b):
    if a == b:
        return _r26_locate(poly, a) == 'boundary'
    from fractions import Fraction
    axis = 0 if a[0] != b[0] else 1
    delta = b[axis] - a[axis]
    spans = []
    for (c, d) in zip(poly, poly[1:] + poly[:1]):
        if _r26_cross(a, b, c) == 0 and _r26_cross(a, b, d) == 0:
            (lo, hi) = sorted((Fraction(c[axis] - a[axis], delta), Fraction(d[axis] - a[axis], delta)))
            lo = max(lo, 0)
            hi = min(hi, 1)
            if lo <= hi:
                spans.append((lo, hi))
    end = 0
    for (lo, hi) in sorted(spans):
        if lo > end:
            return False
        end = max(end, hi)
    return end >= 1
_r26_LABEL = {'boundary': '周界', 'inside': '內部', 'outside': '外部'}

def _r26_regions(i):
    _r26_fields(i, ['outline', 'markers', 'path', 'closedOutlineConfirmed', 'observationSource', 'observationConfirmed'])
    _r26_source(i)
    if not _r26_boolean(i['closedOutlineConfirmed']):
        raise _r26_Need('先確認完整封閉外框，不能猜紙片的內外。')
    poly = i['outline']
    _r26_require(type(poly) is list and 3 <= len(poly) <= 8, '本型只收3至8個轉折的單一無孔外框。')
    poly = [_r26_point(p) for p in poly]
    _r26_require(len(set(map(tuple, poly))) == len(poly), '外框轉折不可重複。')
    _r26_require(sum((a[0] * b[1] - a[1] * b[0] for (a, b) in zip(poly, poly[1:] + poly[:1]))) != 0, '輪廓不能退化為線。')
    n = len(poly)
    for j in range(n):
        (a, b, c) = (poly[j - 1], poly[j], poly[(j + 1) % n])
        _r26_require(_r26_cross(a, b, c) != 0 or (b[0] - a[0]) * (c[0] - b[0]) + (b[1] - a[1]) * (c[1] - b[1]) > 0, '相鄰外框不能沿原路折回重疊。')
    for j in range(n):
        for k in range(j + 1, n):
            if k == j + 1 or (j == 0 and k == n - 1):
                continue
            _r26_require(not _r26_hit(poly[j], poly[(j + 1) % n], poly[k], poly[(k + 1) % n]), '本型不收自交或自接輪廓。')
    markers = i['markers']
    path = i['path']
    _r26_require(type(markers) is list and 1 <= len(markers) <= 4 and (type(path) is list) and (len(path) <= 10), '需1至4個標記及至多10個路徑點。')
    vals = [_r26_locate(poly, _r26_point(p)) for p in markers]
    path = [_r26_point(p) for p in path]
    _r26_require(len(path) != 1, '路徑要有起點終點；不問路徑時給空陣列。')
    entire = None if not path else all((_r26_along(poly, a, b) for (a, b) in zip(path, path[1:])))
    closed = None if not path else entire and path[0] == path[-1] and any((path[j] != path[j + 1] for j in range(len(path) - 1)))
    a = dict(markerParts=[_r26_LABEL[v] for v in vals], wholePathOnBoundary=entire, returnsToStartOnBoundary=closed, physicalVerified=False, nextStep='先沿已確認紙片外框摸一段，再指出標記是在外框上、紙片中或紙片外；不算外框多長。')
    return (a, {k: a[k] for k in ('markerParts', 'wholePathOnBoundary', 'returnsToStartOnBoundary', 'physicalVerified')})

def _r26_tolerance(i):
    req = ['targetCm', 'ticksPerCm', 'startTick', 'endTick', 'toleranceTicks', 'method', 'rulerStraight', 'flat', 'endpointMarksConfirmed', 'readingOriginConfirmed', 'reportedLengthTicks', 'observationConfirmed', 'observationSource', 'toleranceAgreed', 'unit']
    _r26_fields(i, req)
    _r26_source(i)
    _r26_enum(i['unit'], ('公分',))
    target = _r26_integer(i['targetCm'], 1, 20)
    scale = _r26_integer(i['ticksPerCm'], 1, 10)
    start = _r26_integer(i['startTick'], 0, 300)
    end = _r26_integer(i['endTick'], 0, 300)
    tol = _r26_integer(i['toleranceTicks'], 0, scale)
    report = _r26_integer(i['reportedLengthTicks'], 0, 300)
    method = _r26_enum(i['method'], ('zero-end', 'subtract-ends'))
    _r26_require(start <= end, '本記錄方法須依尺刻度由小到大記起終點；反向紀錄請重新整理，非判原題不合法。')
    for k in ('rulerStraight', 'flat', 'endpointMarksConfirmed', 'readingOriginConfirmed', 'toleranceAgreed'):
        _r26_boolean(i[k])
    if not i['toleranceAgreed']:
        raise _r26_Need('先請老師約定可接受的兩個小標記範圍，不能自行補容許差。')
    length = end - start
    problems = []
    for (k, msg) in [('rulerStraight', '尺未對準同一方向'), ('flat', '尺未平貼'), ('endpointMarksConfirmed', '兩端標記未確定'), ('readingOriginConfirmed', '把尺邊或錯誤刻度當起點')]:
        if not i[k]:
            problems.append(msg)
    if method == 'zero-end' and start != 0:
        problems.append('宣告的0起點方法與非0起點紀錄不一致')
    if report != length:
        problems.append('報讀量與起終點間隔不一致')
    if problems:
        status = 'operation-needs-repeat'
        tv = 'not-evaluated'
        hint = '先修正' + problems[0] + '，重新平貼並確認兩端，再核老師容許帶。'
    else:
        status = 'record-method-consistent'
        tv = 'within' if abs(length - target * scale) <= tol else 'outside'
        hint = '原紀錄在老師約定範圍內；這只核紀錄，不證明實物已量準。' if tv == 'within' else '原紀錄在老師約定範圍外，先重新量或重畫，不把它直接當能力不足。'
    if problems == ['宣告的0起點方法與非0起點紀錄不一致']:
        hint = '宣告的0起點方法與非0起點紀錄不一致；請確認實際是否數間隔或用終點減起點，再核老師容許帶。'
    a = dict(operationStatus=status, toleranceStatus=tv, correctedLengthTicks=length if all((i[k] for k in ('rulerStraight', 'flat', 'endpointMarksConfirmed', 'readingOriginConfirmed'))) else None, physicalVerified=False, nextStep=hint)
    return (a, {k: a[k] for k in ('operationStatus', 'toleranceStatus', 'correctedLengthTicks', 'physicalVerified')})
_r26_COMPARE = ['trace-vertex', 'trace-first-side', 'trace-second-side', 'move-sheet', 'align-vertex', 'align-first-side', 'observe-opening']
_r26_COPY = ['confirm-right-reference', 'hold-reference', 'trace-vertex', 'trace-first-side', 'trace-second-side', 'lift-reference', 'recheck-overlap']
_r26_WORDS = {'trace-vertex': '描下共同頂點', 'trace-first-side': '沿第一邊描線', 'trace-second-side': '沿第二邊描線', 'move-sheet': '保持透明紙原形移到另一角', 'align-vertex': '對齊兩角頂點', 'align-first-side': '對齊一邊並選同側開口', 'observe-opening': '觀察另一邊的開口位置', 'confirm-right-reference': '先確認工具上的指定角為直角', 'hold-reference': '按住工具不移動', 'lift-reference': '拿開工具', 'recheck-overlap': '再以原直角核對頂點與兩邊'}

def _r26_angles(i):
    _r26_fields(i, ['mode', 'actions', 'shapePreserved', 'vertexAligned', 'sideAligned', 'sameSide', 'position', 'observationSource', 'observationConfirmed'])
    _r26_source(i)
    mode = _r26_enum(i['mode'], ('transfer-compare', 'copy-right'))
    if mode == 'copy-right':
        _r26_fields(i, ['sourceRightConfirmed'])
        if not _r26_boolean(i['sourceRightConfirmed']):
            raise _r26_Need('先確認原工具的指定角確實為直角，不能由名字猜。')
    for k in ('shapePreserved', 'vertexAligned', 'sideAligned', 'sameSide'):
        _r26_boolean(i[k])
    pos = _r26_enum(i['position'], ('inside', 'equal', 'outside'))
    actions = i['actions']
    seq = _r26_COMPARE if mode == 'transfer-compare' else _r26_COPY
    _r26_require(type(actions) is list and len(actions) <= 10, '操作序列超出本型。')
    for x in actions:
        _r26_enum(x, tuple(_r26_WORDS))
    traced = {'trace-vertex', 'trace-first-side', 'trace-second-side'}
    seen = set()
    wrong = None

    def available(action):
        if mode == 'transfer-compare':
            return True if action in traced else traced <= seen if action == 'move-sheet' else 'move-sheet' in seen if action in ('align-vertex', 'align-first-side') else {'align-vertex', 'align-first-side'} <= seen if action == 'observe-opening' else False
        return True if action in ('confirm-right-reference', 'hold-reference') else {'confirm-right-reference', 'hold-reference'} <= seen if action in traced else traced <= seen if action == 'lift-reference' else 'lift-reference' in seen if action == 'recheck-overlap' else False
    for (j, x) in enumerate(actions):
        if x in seen or x not in seq or (not available(x)):
            wrong = j
            break
        seen.add(x)
    pending = next((x for x in seq if x not in seen), None)
    bad = next((k for k in ('shapePreserved', 'vertexAligned', 'sideAligned', 'sameSide') if not i[k]), None)
    complete = wrong is None and len(actions) == len(seq)
    matches = complete and bad is None
    conclusion = ('甲較小' if pos == 'inside' else '甲乙一樣大' if pos == 'equal' else '甲較大') if matches and mode == 'transfer-compare' else ('紀錄支持複製直角的貼合流程' if pos == 'equal' else '描線與原直角尚未貼合，需重描') if matches else None
    nxt = pending if wrong is not None else ({'shapePreserved': 'trace-vertex', 'vertexAligned': 'align-vertex', 'sideAligned': 'align-first-side', 'sameSide': 'align-first-side'}[bad] if mode == 'transfer-compare' else 'trace-vertex') if bad else pending if not complete else None
    if bad:
        hint = {'shapePreserved': '透明紙有拉伸或折動，先重新描原角，不能沿用原大小。', 'vertexAligned': '先把共同頂點對齊，再看開口，不從邊長猜。', 'sideAligned': '先對齊一邊，再看另一邊。', 'sameSide': '先選同一側內部開口，再比較。'}[bad]
    elif wrong is not None:
        hint = '原紀錄次序不合，先回到「' + _r26_WORDS[nxt] + '」再繼續。'
    elif not complete:
        hint = '下一步先「' + _r26_WORDS[nxt] + '」，不要跳過觀察。'
    else:
        hint = conclusion + '；只核外部紀錄，不代表實物或學生能力已驗證。'
    if mode == 'copy-right' and matches and (pos != 'equal'):
        matches = False
        nxt = 'trace-vertex'
    plan = [_r26_WORDS[x] for x in seq] + ['條件齊備時的紀錄說明：' + (conclusion or '尚不能判開口大小，先補／重做指定步驟。')]
    a = dict(targetType='透明紙轉移比較' if mode == 'transfer-compare' else '直角複製紀錄', requiredActions=[_r26_WORDS[x] for x in seq], recordMatchesSteps=matches, plan=plan, physicalVerified=False, nextStep=hint)
    return (a, dict(recordMatchesSteps=matches, conclusion=conclusion, nextAction=nxt, physicalVerified=False))
_r26_FUNCS = {'s23-agreed-tolerance-operation-check': _r26_tolerance}

def _r26_evaluate(subtype_id, input):
    try:
        _r26_bounded(input)
        _r26_require(type(input) is dict, '入參須為物件。')
        _r26_require(type(subtype_id) is str and subtype_id in _r26_FUNCS, '非本型。')
        _r26_fields(input, ['task'])
        task = _r26_enum(input['task'], ('solve', 'check_proposal'))
        (a, claim) = _r26_FUNCS[subtype_id](input)
        if task == 'check_proposal':
            if 'proposal' not in input or input['proposal'] is None:
                raise _r26_Need('請提供要核對的主張。')
            good = _r26_equal(input['proposal'], claim) or _r26_equal(input['proposal'], a)
            return dict(decision='pass' if good else 'reject', answer=a)
        return dict(decision='pass', answer=a)
    except _r26_Need as e:
        return dict(decision='confirm', answer=None, reason=str(e))
    except _r26_Bad as e:
        return dict(decision='block', answer=None, reason=str(e))

def _r26_unique_pairs(pairs):
    d = {}
    for (k, v) in pairs:
        if k in d:
            raise ValueError('duplicate')
        d[k] = v
    return d

def _r26_main():
    if len(_r26_sys.argv) > 1 and _r26_sys.argv[1] in ('evaluate', '--evaluate'):
        try:
            s = _r26_sys.stdin.read(65537)
            if len(s) > 65536:
                raise ValueError('too long')
            d = _r26_json.loads(s, object_pairs_hook=_r26_unique_pairs, parse_float=lambda s: (_ for _ in ()).throw(ValueError('no float')), parse_int=lambda s: int(s) if len(s) <= 13 else (_ for _ in ()).throw(ValueError('long int')), parse_constant=lambda s: (_ for _ in ()).throw(ValueError('no constant')))
            _r26_bounded(d)
            if type(d) is not dict or set(d) != {'subtypeId', 'input'}:
                raise ValueError('root')
            out = _r26_evaluate(d['subtypeId'], d['input'])
        except (ValueError, TypeError, RecursionError, _r26_Bad, OverflowError) as e:
            out = dict(decision='block', answer=None, reason='入參不在有限JSON紀錄範圍。')
        print(_r26_json.dumps(out, ensure_ascii=False))
        return
    path = _r26_sys.argv[1] if len(_r26_sys.argv) > 1 else __file__.replace('check-', '').replace('.py', '.json')
    d = _r26_json.load(open(path))
    errors = []
    for c in d['cases']:
        out = _r26_evaluate(c['subtypeId'], c['input'])
        if out['decision'] != c['expectedDecision'] or not _r26_equal(out['answer'], c['expectedAnswer']):
            errors.append(c['id'])
    print(_r26_json.dumps(dict(cases=len(d['cases']), failures=errors), ensure_ascii=False))
    _r26_sys.exit(bool(errors))


PACK='grade2-ruler-operation-methods'
NEW_SUBTYPE='s23-agreed-tolerance-operation-check'
OWNER_NEW_SUBTYPE='s23-agreed-tolerance-operation-check'
SUBTYPES=dict(_legacy_SUBTYPES,**{NEW_SUBTYPE:'round26-extension'})if type(_legacy_SUBTYPES)is dict else tuple(_legacy_SUBTYPES)+(NEW_SUBTYPE,)
def evaluate(subtype_id,input):
 if type(subtype_id)is str and subtype_id==NEW_SUBTYPE:
  return _r26_evaluate(OWNER_NEW_SUBTYPE,input)
 return _legacy_evaluate(subtype_id,input)
def verify_package(pack):
 errors=[];counts=_legacy_collections.Counter()
 if len(pack['cases'])!=72 or len(pack['subtypes'])!=3:errors.append('merged-counts')
 for sid in SUBTYPES:
  if _legacy_collections.Counter(c['kind']for c in pack['cases']if c['subtypeId']==sid)!=dict(normal=8,negative=6,boundary=4,ambiguous=2,holdout=4):errors.append(sid+':counts')
 for c in pack['cases']:
  r=evaluate(c['subtypeId'],c['input']);counts[r['decision']]+=1
  if not _r26_equal(r['answer'],c['expectedAnswer'])or r['decision']!=c['expectedDecision']:errors.append(c['id'])
  if c['teacherReviewed']is not False or c['appConnected']is not False:errors.append(c['id']+':flags')
 return errors,dict(counts)
def validate_pack(pack):return verify_package(pack)[0]
def check(path=None):
 p=_legacy_json.loads(_legacy_pathlib.Path(path or _legacy_pathlib.Path(__file__).with_name(PACK+'.json')).read_text())
 errors,counts=verify_package(p)
 assert not errors,errors
 # The intact prefixed old selfcheck also runs; its evaluate calls use public dispatch.
 if path is None:_legacy_check()
 else:
  try:_legacy_check(path)
  except TypeError:_legacy_check()
 print(_legacy_json.dumps({'mergedPack':PACK,'cases':72,'subtypes':3,'decisions':counts},ensure_ascii=False))
def _cli_bound(value,depth=0,budget=None):
 if budget is None:budget=[0]
 budget[0]+=1
 if depth>12 or budget[0]>5000:raise ValueError('bounded structure')
 if type(value)is dict:
  if len(value)>100:raise ValueError('bounded object')
  for k,v in value.items():
   if type(k)is not str or len(k)>256:raise ValueError('bounded key')
   _cli_bound(v,depth+1,budget)
 elif type(value)is list:
  if len(value)>2048:raise ValueError('bounded array')
  for v in value:_cli_bound(v,depth+1,budget)
 elif type(value)is str:
  if len(value)>8192:raise ValueError('bounded string')
 elif type(value)is int:
  if value.bit_length()>1024:raise ValueError('bounded integer')
 elif value is not None and type(value)is not bool:raise ValueError('typed JSON')
def _parse_json(text):
 if len(text)>65536:raise ValueError('bounded JSON')
 def integer_text(s):
  if len(s)>256:raise ValueError('bounded integer')
  return int(s)
 def no_float(s):raise ValueError('typed number')
 value=_legacy_json.loads(text,object_pairs_hook=_r26_unique_pairs,parse_int=integer_text,parse_float=no_float,parse_constant=no_float)
 _cli_bound(value)
 return value
def main():
 argv=_legacy_sys.argv[1:]
 if argv and argv[0]in ('evaluate','--evaluate'):
  try:
   if len(argv)==3:
    # Retain the old G2 evaluate SUBTYPE JSON invocation, now bounded before parsing.
    subtype=argv[1];value=_parse_json(argv[2])
   elif len(argv)==1:
    request=_parse_json(_legacy_sys.stdin.read(65537))
    if type(request)is not dict or set(request)!={'subtypeId','input'}:raise ValueError('root shape')
    subtype,value=request['subtypeId'],request['input']
   else:raise ValueError('CLI shape')
   result=evaluate(subtype,value)
  except (ValueError,TypeError,OverflowError,RecursionError,KeyError):result={'decision':'block','answer':None,'reason':'原JSON不在有界紀錄範圍；請整理原資料。'}
  print(_legacy_json.dumps(result,ensure_ascii=False));return
 check(argv[0]if argv else None)
if __name__=='__main__':main()
