#!/usr/bin/env python3
# Standalone merged source; statically prefixed AST preserves both source namespaces.
import json as _legacy_json, pathlib as _legacy_pathlib, re as _legacy_re, sys as _legacy_sys, collections as _legacy_collections
from fractions import Fraction as _legacy_F
_legacy_PACK = 'grade3-angle-shapes'
_legacy_SUBTYPES = {'s31-angle-overlay': 'angle-overlay', 's31-angle-right': 'angle-right'}
_legacy_REQ = {'angle-overlay': ['vertexAligned', 'sideAligned', 'sameHalfPlane', 'position'], 'angle-right': ['vertexAligned', 'sideAligned', 'sameHalfPlane', 'position'], 'area-whole': ['rowCounts', 'cellUnit', 'sameCells', 'noOverlap'], 'area-half': ['fullCells', 'halfCells', 'cellUnit', 'sameCells', 'exactHalves', 'noOverlap'], 'quad-features': ['sides', 'rightAngles', 'simpleQuad'], 'quad-turn': ['sides', 'rightAngles', 'simpleQuad', 'rotationOnly', 'startShift'], 'circle-segment': ['ends'], 'circle-compass': ['givenLength', 'givenRole', 'unit'], 'activity-pieces': ['originalPieces', 'usedPieces', 'actions', 'overlap', 'observationSource'], 'activity-fold': ['trialA', 'trialB', 'layoutsDifferentRecorded', 'observationSource']}

class _legacy_Invalid(Exception):
    pass

class _legacy_Need(Exception):
    pass

class _legacy_Route(Exception):
    pass

def _legacy_q(x, positive=False):
    if type(x) is int and 0 <= x <= 1000:
        r = _legacy_F(x)
    elif type(x) is str and len(x) <= 32 and _legacy_re.fullmatch('[0-9]{1,8}(?:/[1-9][0-9]{0,7}|\\.[0-9]{1,3})?', x, _legacy_re.ASCII):
        r = _legacy_F(x)
    else:
        raise _legacy_Invalid('數量需非負有界精確數，不收浮點真假值')
    if not 0 <= r <= 1000 or r.denominator > 1000:
        raise _legacy_Route('原量超出本有限方法，轉相符方法，不稱原題無解')
    if positive and r <= 0:
        raise _legacy_Need('已確認邊長或半徑需正，0與形體條件矛盾，先核對')
    return r

def _legacy_integer(x, lo=0, hi=100):
    if type(x) is not int or not lo <= x <= hi:
        raise _legacy_Invalid('件數或位置需在本包範圍的真正整數')
    return x

def _legacy_enum(x, values):
    if type(x) is not str or x not in values:
        raise _legacy_Invalid('操作或已確認觀察不在本型選項')
    return x

def _legacy_yes(x):
    if type(x) is not bool:
        raise _legacy_Invalid('觀察確認欄須真偽值')
    if not x:
        raise _legacy_Need('對齊、同大單位格或操作前提尚未成立，請先操作確認，不能憑外觀猜')

def _legacy_quad(d):
    _legacy_yes(d['simpleQuad'])
    xs = d['sides']
    rr = d['rightAngles']
    if type(xs) is not list or len(xs) != 4 or type(rr) is not list or (len(rr) != 4):
        raise _legacy_Invalid('需依周圍順序記四邊與四角')
    xs = [_legacy_q(x, True) for x in xs]
    if any((type(x) is not bool for x in rr)):
        raise _legacy_Invalid('四角需逐一記是否貼合直角板')
    if max(xs) >= sum(xs) - max(xs):
        raise _legacy_Need('四邊數據無法圍成非退化四邊形，需重查原量')
    n = sum(rr)
    op = xs[0] == xs[2] and xs[1] == xs[3]
    if n == 3 or (n == 4 and (not op)) or (n < 4 and n > 0 and op):
        raise _legacy_Need('邊長與直角觀察彼此矛盾，先重查原量，不讓確認旗標蓋過矛盾')
    if n == 1:
        i = rr.index(True)
        di = xs[i - 1] ** 2 + xs[i] ** 2
        (a, b) = (xs[(i + 1) % 4], xs[(i + 2) % 4])
        if not (a - b) ** 2 < di < (a + b) ** 2:
            raise _legacy_Need('直角兩邊與其餘邊無法圍成此四邊形，需重查')
    if n == 2:
        ii = [i for (i, v) in enumerate(rr) if v]
        if (ii[1] - ii[0]) % 2 == 0:
            i = ii[0]
            if xs[i - 1] ** 2 + xs[i] ** 2 != xs[(i + 1) % 4] ** 2 + xs[(i + 2) % 4] ** 2:
                raise _legacy_Need('兩個對角直角與邊長記錄矛盾')
        else:
            i = next((i for i in range(4) if rr[i] and rr[(i + 1) % 4]))
            if xs[(i + 2) % 4] ** 2 != xs[i] ** 2 + (xs[i - 1] - xs[(i + 1) % 4]) ** 2:
                raise _legacy_Need('相鄰兩個直角與邊長記錄矛盾')
    rect = n == 4
    square = rect and len(set(xs)) == 1
    return (xs, rr, {'isSquare': square, 'isRectangle': rect, 'name': '正方形' if square else '長方形' if rect else '不是正方形或長方形'})

def _legacy_pid(x):
    if type(x) is not str or not _legacy_re.fullmatch('p[1-8]', x):
        raise _legacy_Invalid('原片標記需為明列p1到p8，不接受任意長字串')
    return x

def _legacy_trial(t):
    if type(t) is not dict or set(t) != set(['completed', 'closure', 'overlap', 'observedSolid']):
        raise _legacy_Invalid('每份操作紀錄欄位需完整且無額外欄')
    if type(t['completed']) is not bool:
        raise _legacy_Invalid('操作完成與否須為真偽值')
    closure = _legacy_enum(t['closure'], ['closed', 'open', 'unknown'])
    overlap = _legacy_enum(t['overlap'], ['none', 'present', 'unknown'])
    shape = _legacy_enum(t['observedSolid'], ['cube', 'rectangular-box-noncube', 'unknown'])
    return t['completed'] and closure == 'closed' and (overlap == 'none') and (shape != 'unknown')

def _legacy_compute(mode, d):
    if mode in ['angle-overlay', 'angle-right']:
        for k in ['vertexAligned', 'sideAligned', 'sameHalfPlane']:
            _legacy_yes(d[k])
        pos = _legacy_enum(d['position'], ['inside', 'coincides', 'outside'])
        if 'armLengths' in d and d['armLengths'] is not None:
            arms = d['armLengths']
            if type(arms) is not list or len(arms) != 4:
                raise _legacy_Invalid('四條已記邊長需完整列表')
            [_legacy_q(x, True) for x in arms]
        rel = {'inside': '<', 'coincides': '=', 'outside': '>'}[pos]
        if mode == 'angle-overlay':
            return {'relation': rel}
        return {'comparisonToRight': rel, 'isRight': pos == 'coincides'}
    if mode == 'area-whole':
        for k in ['sameCells', 'noOverlap']:
            _legacy_yes(d[k])
        _legacy_enum(d['cellUnit'], ['1平方公分'])
        rows = d['rowCounts']
        if type(rows) is not list or len(rows) > 100:
            raise _legacy_Invalid('需已點好的百格板逐排格數列表')
        rows = [_legacy_integer(x, 0, 100) for x in rows]
        total = sum(rows)
        if total > 100:
            raise _legacy_Route('本包百格板最多100格，較大圖形轉其他點數方法')
        return {'area': str(total), 'unit': '平方公分'}
    if mode == 'area-half':
        for k in ['sameCells', 'exactHalves', 'noOverlap']:
            _legacy_yes(d[k])
        _legacy_enum(d['cellUnit'], ['1平方公分'])
        full = _legacy_integer(d['fullCells'], 0, 100)
        halves = _legacy_integer(d['halfCells'], 0, 200)
        area = _legacy_F(full) + _legacy_F(halves, 2)
        if area > 100:
            raise _legacy_Route('本包先核百格板內區域，較大面積轉其他格板方法')
        return {'area': str(area), 'wholeUnits': full + halves // 2, 'halfUnitLeft': bool(halves % 2), 'unit': '平方公分'}
    if mode in ['quad-features', 'quad-turn']:
        (xs, rr, a) = _legacy_quad(d)
        if mode == 'quad-turn':
            _legacy_yes(d['rotationOnly'])
            shift = _legacy_integer(d['startShift'], 0, 3)
            a.update(featuresUnchanged=True, afterSides=list(map(str, xs[shift:] + xs[:shift])), afterRightAngles=rr[shift:] + rr[:shift])
        return a
    if mode == 'circle-segment':
        ends = d['ends']
        if type(ends) is not list or len(ends) != 2:
            raise _legacy_Invalid('線段需兩端已確認位置')
        ends = [_legacy_enum(x, ['center', 'circumference', 'inside-noncenter', 'outside']) for x in ends]
        through = d.get('throughCenter')
        if through is None:
            if 'center' in ends:
                through = True
            elif ends == ['circumference', 'circumference']:
                raise _legacy_Need('兩端雖在圓周，是否通過圓心尚未確認')
            else:
                through = False
        if type(through) is not bool:
            raise _legacy_Invalid('是否過心需真偽值')
        if 'center' in ends and (not through):
            raise _legacy_Need('端點在圓心卻記不過圓心，觀察矛盾，需核對')
        if ends == ['center', 'center']:
            raise _legacy_Need('兩端都在同一圓心不是所述非零線段，先核對')
        radius = sorted(ends) == ['center', 'circumference']
        diam = ends == ['circumference', 'circumference'] and through
        return {'role': '半徑' if radius else '直徑' if diam else '不是半徑也不是直徑', 'centerOnCircumference': False}
    if mode == 'circle-compass':
        v = _legacy_q(d['givenLength'], True)
        _legacy_enum(d['unit'], ['公分'])
        role = _legacy_enum(d['givenRole'], ['radius', 'diameter'])
        r = v if role == 'radius' else v / 2
        return {'radius': str(r), 'diameter': str(r + r), 'compassOpening': str(r), 'unit': '公分', 'centerOnCircumference': False}
    if mode == 'activity-pieces':
        _legacy_enum(d['observationSource'], ['learner-operation-log', 'teacher-operation-log'])
        orig = d['originalPieces']
        used = d['usedPieces']
        acts = d['actions']
        if type(orig) is not list or not 1 <= len(orig) <= 8 or type(used) is not list or (len(used) > 16) or (type(acts) is not list) or (len(acts) > 16):
            raise _legacy_Invalid('分片與操作紀錄清單不符本有限流程')
        orig = [_legacy_pid(x) for x in orig]
        used = [_legacy_pid(x) for x in used]
        if len(set(orig)) != len(orig):
            raise _legacy_Need('原片標記重複，先核對紀錄')
        if set(used) - set(orig):
            raise _legacy_Need('重組紀錄出現未列原片，先核對原材料')
        for x in acts:
            _legacy_enum(x, ['move', 'turn', 'flip', 'stretch', 'cut-more'])
        ov = _legacy_enum(d['overlap'], ['none-recorded', 'present-recorded', 'not-observed'])
        each = _legacy_collections.Counter(used) == _legacy_collections.Counter(orig)
        changed = any((x in ['stretch', 'cut-more'] for x in acts))
        supports = each and (not changed) and (ov == 'none-recorded')
        step = '先重新逐片核對有無漏片或重複' if not each else '先更新分片/變形紀錄，不沿用原片結論' if changed else '先實際檢查有無重疊與缺漏並記下' if ov == 'not-observed' else '先重排排除已記錄重疊，再重新觀察' if ov == 'present-recorded' else '保留本次紀錄，請教師在現場核對'
        return {'recordSupportsSamePieces': supports, 'nextStep': step, 'physicalVerified': False}
    _legacy_enum(d['observationSource'], ['learner-operation-log', 'teacher-operation-log'])
    if type(d['layoutsDifferentRecorded']) is not bool:
        raise _legacy_Invalid('不同排列是否有紀錄需真偽值')
    (aa, bb) = (_legacy_trial(d['trialA']), _legacy_trial(d['trialB']))
    same = aa and bb and (d['trialA']['observedSolid'] == d['trialB']['observedSolid'])
    supports = same and d['layoutsDifferentRecorded']
    step = '先把兩份都實際摺合，記錄封口、重疊與觀察到的形體' if not (aa and bb) else '先補不同原排列的紀錄，不能只看最後形體' if not d['layoutsDifferentRecorded'] else '兩份記錄形體不同，回現場核對，不套同形結論' if not same else '保留兩份操作記錄並請教師現場核對'
    return {'recordSupportsSameShape': supports, 'nextStep': step, 'physicalVerified': False}

def _legacy_derived(x):
    if type(x) is int and abs(x) < 10 ** 64:
        return _legacy_F(x)
    if type(x) is str and len(x) <= 132 and _legacy_re.fullmatch('-?[0-9]{1,64}(?:/[1-9][0-9]{0,63}|\\.[0-9]{1,64})?', x, _legacy_re.ASCII):
        return _legacy_F(x)
    raise _legacy_Invalid('答案數量需有界精確數')

def _legacy_equivalent(p, a, key=''):
    if type(a) is dict:
        return type(p) is dict and set(p) == set(a) and all((_legacy_equivalent(p[k], v, k) for (k, v) in a.items()))
    if type(a) is list:
        return type(p) is list and len(p) == len(a) and all((_legacy_equivalent(x, y, key) for (x, y) in zip(p, a)))
    if type(a) is bool:
        return type(p) is bool and p == a
    if key in ['area', 'wholeUnits', 'afterSides', 'radius', 'diameter', 'compassOpening']:
        try:
            return _legacy_derived(p) == _legacy_derived(a)
        except (_legacy_Invalid, ValueError, ZeroDivisionError, TypeError):
            return False
    return type(p) is type(a) and p == a

def _legacy_missing_required(mode, d):
    required = _legacy_REQ[mode] + ['factsConfirmed']
    if any((k not in d or d[k] is None for k in required)):
        return True
    for k in required:
        if type(d[k]) is list and any((x is None for x in d[k])):
            return True
    if mode == 'activity-fold':
        for k in ['trialA', 'trialB']:
            t = d[k]
            if type(t) is dict and any((t.get(x) is None for x in ['completed', 'closure', 'overlap', 'observedSolid'])):
                return True
    return False

def _legacy_evaluate(s, d):

    def out(k, a=None, r=''):
        return dict(decision=k, answer=a, reason=r)
    if type(s) is not str or s not in _legacy_SUBTYPES or type(d) is not dict:
        return out('block', r='非本有限文字/活動引導方法')
    mode = _legacy_SUBTYPES[s]
    required = _legacy_REQ[mode]
    if _legacy_missing_required(mode, d):
        return out('confirm', r='原題或操作紀錄必要條件缺漏，先補清；不從文字假稱看過實物')
    if type(d['factsConfirmed']) is not bool:
        return out('block', r='原條件確認須真偽值')
    if not d['factsConfirmed']:
        return out('confirm', r='原條件未確認，先核對紀錄來源')
    optional = {'armLengths'} if mode.startswith('angle') else {'throughCenter'} if mode == 'circle-segment' else set()
    if set(d) - set(required) - optional - {'task', 'factsConfirmed', 'proposal'}:
        return out('block', r='未知欄位不可冒充原條件')
    if type(d.get('task')) is not str or d['task'] not in ['solve', 'check_proposal']:
        return out('block', r='未知任務')
    try:
        a = _legacy_compute(mode, d)
    except _legacy_Need as e:
        return out('confirm', r=str(e))
    except (_legacy_Route, _legacy_Invalid, ValueError, TypeError, ZeroDivisionError, OverflowError) as e:
        return out('block', r=str(e))
    if d['task'] == 'check_proposal':
        if d.get('proposal') is None:
            return out('confirm', a, '請提供待核對AI想法；原條件結論保留')
        if not _legacy_equivalent(d['proposal'], a):
            return out('reject', a, '錯提案不改已確認觀察；不給學生掌握程度分數')
    return out('pass', a, '只核已提供條件/紀錄；不代表實物操作或OCR已驗證')

def _legacy_check():
    p = _legacy_json.load(open(_legacy_pathlib.Path(__file__).with_name(_legacy_PACK + '.json')))
    for s in _legacy_SUBTYPES:
        assert _legacy_collections.Counter((c['kind'] for c in p['cases'] if c['subtypeId'] == s)) == dict(normal=8, negative=6, boundary=4, ambiguous=2, holdout=4)
    for c in p['cases']:
        r = evaluate(c['subtypeId'], c['input'])
        assert (r['decision'], r['answer']) == (c['expectedDecision'], c['expectedAnswer']), c['id']
    print(_legacy_json.dumps({'package': _legacy_PACK, 'routeCases': len(p['cases']), 'passed': True}))

def _legacy_cli_main():
    if len(_legacy_sys.argv) > 1 and _legacy_sys.argv[1] == 'evaluate':
        x = _legacy_json.load(_legacy_sys.stdin)
        print(_legacy_json.dumps(evaluate(x.get('subtypeId'), x.get('input')), ensure_ascii=False))
    else:
        _legacy_check()

"""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，卻直接把終點刻度當長度')
    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 '原紀錄在老師約定範圍外，先重新量或重畫，不把它直接當能力不足。'
    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 == seq[-1] and set(seq) <= seen:
            continue
        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 set(seq) <= seen
    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 or seq[0] 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 = {'n313-trace-transfer-and-right-copy': _r26_angles}

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='grade3-angle-shapes'
NEW_SUBTYPE='s31-trace-transfer-and-right-copy'
OWNER_NEW_SUBTYPE='n313-trace-transfer-and-right-copy'
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()
