#!/usr/bin/env python3
# Standalone merged source; statically prefixed AST preserves both source namespaces.
_legacy_PACK = 'grade1-shape-manipulation'
_legacy_SUBTYPES = ('g1-original-cut-restore', 'g1-face-imprint')
import json as _legacy_json, pathlib as _legacy_pathlib, re as _legacy_re, sys as _legacy_sys, copy as _legacy_copy, collections as _legacy_collections
from fractions import Fraction as _legacy_F
_legacy_REQ = {'g1-length-cover': ['aCount', 'bCount', 'sameUnitsConfirmed', 'coveredConfirmed'], 'g1-length-direct': ['aEnd', 'bEnd', 'alignedConfirmed', 'orderConfirmed'], 'g1-length-string-transfer': ['curvedCount', 'straightCount', 'sameUnitsConfirmed', 'noStretchConfirmed', 'pathTransferConfirmed'], 'g1-length-common-reference': ['aRelation', 'bRelation', 'sameReferenceConfirmed', 'aReference', 'bReference'], 'g1-calendar-neighbor': ['month', 'day', 'when', 'sameMonthConfirmed'], 'g1-clock-whole-half': ['hourStart', 'longAt', 'shortAt', 'handRolesConfirmed'], 'g1-day-period-order': ['first', 'second', 'cardOrderConfirmed'], 'g1-original-cut-restore': ['recipe', 'pieces', 'joins', 'matchedConfirmed'], 'g1-face-imprint': ['solid', 'quarterTurns', 'flatContactConfirmed', 'noSmearConfirmed']}
_legacy_RECIPES = {'square-diagonal': ('正方形', '從一個角連到對面角切成2片', ['A', 'B'], [['A斜切邊', 'B斜切邊']]), 'square-midline': ('正方形', '從上邊中間連到下邊中間直切成2片', ['A', 'B'], [['A內切邊', 'B內切邊']]), 'rectangle-diagonal': ('長方形', '從一角到對面角切成2片', ['A', 'B'], [['A斜切邊', 'B斜切邊']]), 'rectangle-midline': ('長方形', '從上邊中間連到下邊中間直切成2片', ['A', 'B'], [['A內切邊', 'B內切邊']]), 'triangle-fan2': ('三角形', '從頂端連到下面邊的中間切成2片', ['A', 'B'], [['A內切邊', 'B內切邊']]), 'circle-half': ('圓形', '從紙片正中直切成2片', ['A', 'B'], [['A直切邊', 'B直切邊']]), 'square-grid4': ('正方形', '中央一橫一豎切成4片', ['A', 'B', 'C', 'D'], [['A右切邊', 'B左切邊'], ['A下切邊', 'C上切邊'], ['B下切邊', 'D上切邊'], ['C右切邊', 'D左切邊']]), 'rectangle-strips3': ('長方形', '用兩條平行切線分成左中右3片', ['A', 'B', 'C'], [['A右切邊', 'B左切邊'], ['B右切邊', 'C左切邊']]), 'rectangle-grid4': ('長方形', '一橫一豎分成左上右上左下右下4片', ['A', 'B', 'C', 'D'], [['A右切邊', 'B左切邊'], ['A下切邊', 'C上切邊'], ['B下切邊', 'D上切邊'], ['C右切邊', 'D左切邊']]), 'triangle-fan3': ('三角形', '從頂端連兩條線到下面邊，分成左中右3片', ['A', 'B', 'C'], [['A右切邊', 'B左切邊'], ['B右切邊', 'C左切邊']]), 'square-corner-strip': ('正方形', '沿靠右一條直線切成寬窄2片', ['A', 'B'], [['A右切邊', 'B左切邊']]), 'circle-strips3': ('圓形', '用兩條互不交叉的平行直線分成左中右3片', ['A', 'B', 'C'], [['A右切邊', 'B左切邊'], ['B右切邊', 'C左切邊']])}
_legacy_IMPRINTS = {'cube-flat': ('方塊積木', '已確認的一個平正方形面', '正方形'), 'cuboid-wide': ('長盒積木', '已確認的一個長方形面，長邊比短邊長', '長方形'), 'cylinder-end': ('圓柱積木', '一端的平圓面', '圓形'), 'triangle-prism-end': ('三角柱積木', '一端的平三角形面', '三角形')}
_legacy_PERIODS = ('上午', '中午', '下午', '晚上')

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

def _legacy_integer(v, lo, hi):
    if type(v) is not int or not lo <= v <= hi:
        raise ValueError('原觀察數量需契約範圍內整數，布林不是數量')
    return v

def _legacy_enum(v, values):
    if type(v) is not str or v not in values:
        raise ValueError('觀察標記不在已確認的有限資料中')
    return v

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

def _legacy_joins_norm(xs):
    if type(xs) is not list or len(xs) > 8:
        raise ValueError('切邊配對需有限清單')
    _legacy_out = []
    for pair in xs:
        if type(pair) is not list or len(pair) != 2 or any((type(v) is not str or len(v) > 20 for v in pair)):
            raise ValueError('每次配對恰兩條已知切邊')
        _legacy_out.append(tuple(sorted(pair)))
    if len(set(_legacy_out)) != len(_legacy_out):
        raise ValueError('切邊不可重複接合')
    return sorted(_legacy_out)

def _legacy_derived(v):
    if type(v) is int and abs(v) < 10 ** 100:
        return _legacy_F(v)
    if type(v) is not str or len(v) > 260 or (not _legacy_re.fullmatch('-?[0-9]{1,128}(?:/[0-9]{1,128}|\\.[0-9]{1,128})?', v)):
        raise ValueError('有限精確答案格式')
    return _legacy_F(v)

def _legacy_normal(p, a):
    if type(p) is not dict or set(p) != set(a):
        raise ValueError('答案欄位不符')
    z = {}
    for (k, v) in a.items():
        if type(v) is int:
            z[k] = _legacy_derived(p[k])
        elif type(p[k]) is str:
            z[k] = p[k]
        else:
            raise ValueError('答案文字角色不符')
    return z

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='非本有限操作模板')
    fs = _legacy_REQ[subtype_id]
    if r.get('confirmed') is not True or any((r.get(k) is None for k in fs)):
        return _legacy_out('confirm', r='先確認原圖或實體操作的缺少條件，不自行補觀察')
    if subtype_id == 'g1-original-cut-restore' and type(r.get('pieces')) is list and any((v is None for v in r['pieces'])):
        return _legacy_out('confirm', r='先確認全部原拼片')
    if subtype_id == 'g1-original-cut-restore' and type(r.get('joins')) is list and any((p is None or (type(p) is list and any((v is None for v in p))) for p in r['joins'])):
        return _legacy_out('confirm', r='先確認原切邊對應')
    if r.get('task') not in ('solve', 'check_proposal') or set(r) - set(fs) - {'confirmed', 'task', 'proposal'}:
        return _legacy_out('block', r='任務或欄位不符')
    for k in fs:
        if k.endswith('Confirmed'):
            if type(r[k]) is not bool:
                return _legacy_out('block', r='操作確認需明確真偽')
            if not r[k]:
                return _legacy_out('confirm', r='先實際操作或核對圖上標記，再提供確認條件')
    s = subtype_id
    try:
        if s == 'g1-length-cover':
            a = {'relation': _legacy_rel(_legacy_integer(r['aCount'], 1, 20), _legacy_integer(r['bCount'], 1, 20))}
        elif s == 'g1-length-direct':
            a = {'relation': _legacy_rel(_legacy_integer(r['aEnd'], 1, 20), _legacy_integer(r['bEnd'], 1, 20))}
        elif s == 'g1-length-string-transfer':
            a = {'relation': '彎線較短' if _legacy_integer(r['curvedCount'], 1, 20) < _legacy_integer(r['straightCount'], 1, 20) else '彎線較長' if r['curvedCount'] > r['straightCount'] else '一樣長'}
        elif s == 'g1-length-common-reference':
            for name in ('aReference', 'bReference'):
                if type(r[name]) is not str or not _legacy_re.fullmatch('[\\u4e00-\\u9fffA-Za-z0-9]{1,16}', r[name]):
                    raise ValueError('參照帶標記需確認')
            if r['aReference'] != r['bReference']:
                return _legacy_out('confirm', r='不是同一條參照帶，不能把兩個比較直接接起來')
            x = _legacy_enum(r['aRelation'], ('<', '=', '>'))
            y = _legacy_enum(r['bRelation'], ('<', '=', '>'))
            v = {'<': 0, '=': 1, '>': 2}
            a = {'relation': _legacy_rel(v[x], v[y]) if x != y or x == '=' else '不能確定'}
        elif s == 'g1-calendar-neighbor':
            mo = _legacy_integer(r['month'], 1, 12)
            day = _legacy_integer(r['day'], 1, 31)
            when = _legacy_enum(r['when'], ('昨天', '今天', '明天'))
            if not 2 <= day <= 27:
                return _legacy_out('block', r='月底/月初或本有限同月表外，請看原日曆相鄰格，不猜每月天數')
            a = {'month': mo, 'day': day + {'昨天': -1, '今天': 0, '明天': 1}[when]}
        elif s == 'g1-clock-whole-half':
            h = _legacy_integer(r['hourStart'], 1, 12)
            long = _legacy_integer(r['longAt'], 1, 12)
            short = _legacy_enum(r['shortAt'], ('數字上', '兩數之間'))
            if long not in (6, 12):
                return _legacy_out('block', r='只教整點半點；其他鐘面先轉適合活動')
            if short != ('數字上' if long == 12 else '兩數之間'):
                return _legacy_out('confirm', r='長短針相互矛盾，先核對原鐘面，不硬判時刻')
            a = {'hour': h, 'part': '整點' if long == 12 else '半點'}
        elif s == 'g1-day-period-order':
            x = _legacy_enum(r['first'], _legacy_PERIODS)
            y = _legacy_enum(r['second'], _legacy_PERIODS)
            a = {'relation': '甲較早' if _legacy_PERIODS.index(x) < _legacy_PERIODS.index(y) else '甲較晚' if _legacy_PERIODS.index(x) > _legacy_PERIODS.index(y) else '同一時段'}
        elif s == 'g1-original-cut-restore':
            recipe = _legacy_enum(r['recipe'], _legacy_RECIPES)
            (name, cut, pieces, joins) = _legacy_RECIPES[recipe]
            if type(r['pieces']) is not list or any((type(p) is not str for p in r['pieces'])):
                raise ValueError('原片標記需清單')
            if sorted(r['pieces']) != sorted(pieces) or _legacy_joins_norm(r['joins']) != _legacy_joins_norm(joins):
                return _legacy_out('confirm', r='原片或切邊對應不足/矛盾，需重新實作，不從示意補關係')
            a = {'shape': name}
        elif s == 'g1-face-imprint':
            solid = _legacy_enum(r['solid'], _legacy_IMPRINTS)
            _legacy_integer(r['quarterTurns'], 0, 4)
            a = {'shape': _legacy_IMPRINTS[solid][2]}
        else:
            return _legacy_out('block', r='非本有限操作模板')
    except (ValueError, TypeError, KeyError, OverflowError, ZeroDivisionError) as e:
        return _legacy_out('block', r=str(e))
    if r['task'] == 'check_proposal':
        if r.get('proposal') is None:
            return _legacy_out('confirm', a, '先提供要核對的想法')
        try:
            good = _legacy_normal(r['proposal'], a) == _legacy_normal(a, a)
        except (ValueError, TypeError, OverflowError, ZeroDivisionError):
            good = False
        if not good:
            return _legacy_out('reject', a, '保留已確認原操作結果；錯因見具體步驟')
    return _legacy_out('pass', a, '本結論只依已確認實體/圖上結構，不代替原圖理解')

def _legacy_verify_package(p):
    errors = []
    counts = _legacy_collections.Counter()
    for s in _legacy_SUBTYPES:
        if _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):
            errors.append(s + ':counts')
    for c in p['cases']:
        g = evaluate(c['subtypeId'], c['input'])
        counts[g['decision']] += 1
        if (g['decision'], g['answer']) != (c['expectedDecision'], c['expectedAnswer']):
            errors.append(c['id'])
        if c['studentFacing'] != (c['casePurpose'] != 'validator-guard') or c['teacherReviewed'] is not False or c['appConnected'] is not False:
            errors.append(c['id'] + ':flags')
    return (errors, dict(counts))

def _legacy_validate_pack(p):
    return _legacy_verify_package(p)[0]

def _legacy_check(path=None):
    p = _legacy_json.loads(_legacy_pathlib.Path(path or _legacy_pathlib.Path(__file__).with_name(_legacy_PACK + '.json')).read_text())
    (e, c) = _legacy_verify_package(p)
    assert not e, e
    n = 0
    for x in p['cases']:
        if x['expectedAnswer'] is None:
            continue
        r = dict(x['input'], task='check_proposal', proposal=x['expectedAnswer'])
        assert evaluate(x['subtypeId'], r)['decision'] == 'pass'
        n += 1
    print(_legacy_json.dumps(dict(pack=_legacy_PACK, cases=len(p['cases']), roundtrips=n, decisions=c), ensure_ascii=False))

def _legacy_cli_main():
    _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', 'adultSafetyConfirmed', 'observationSource', 'observationConfirmed'])
    for key in ('plan', 'events'):
        if key not in i or i[key] is None:
            raise _r26_Need('請先補上原計畫或操作紀錄。')
    objects = i['objects']
    plan = i['plan']
    events = i['events']
    for (records, required) in ((plan, ('lower', 'upper', 'contactFace')), (events, ('step', 'action', 'result'))):
        _r26_require(type(records) is list, '計畫與操作紀錄須為有限清單。')
        for record in records:
            if record is None:
                raise _r26_Need('請先補上這一項原計畫或操作紀錄。')
            _r26_require(type(record) is dict, '每項操作紀錄須為物件。')
            _r26_require(set(record) <= set(required), '原操作紀錄不能增加未知欄位。')
            _r26_fields(record, required)
    _r26_source(i)
    if not _r26_boolean(i['adultSafetyConfirmed']):
        raise _r26_Need('請成人先確認材料與操作區，再進行堆疊。')
    _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 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 = {'s12-stacking-operation-guidance': _r26_stacking}

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='grade1-shape-manipulation'
NEW_SUBTYPE='s12-stacking-operation-guidance'
OWNER_NEW_SUBTYPE='s12-stacking-operation-guidance'
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()
