# -*- coding: utf-8 -*-
# Static owner/extension merge; source provenance and AST edits in merge-manifest.json.
"""Independent finite-contract exact oracle; no expected-answer lookup, no eval/OCR."""
import json as legacy_json, copy as legacy_copy, re as legacy_re, sys as legacy_sys
from pathlib import Path as legacy_Path
from fractions import Fraction as legacy_F
from collections import Counter as legacy_Counter
legacy_PAT = legacy_re.compile('[+-]?(?:[0-9]{1,12}(?:\\.[0-9]{1,12})?|[0-9]{1,12}/[0-9]{1,12})\\Z')

class legacy_Unknown(Exception):
    pass

class legacy_Invalid(Exception):
    pass

def legacy_num(x):
    if x is None:
        raise legacy_Unknown('missing_coefficient')
    if isinstance(x, bool) or not isinstance(x, (int, str)):
        raise legacy_Invalid('invalid_numeric_input')
    if isinstance(x, int) and abs(x) > 1000000:
        raise legacy_Invalid('numeric_bound_exceeded')
    if not legacy_PAT.fullmatch(str(x)):
        raise legacy_Invalid('invalid_numeric_input')
    try:
        r = legacy_F(str(x))
    except (ValueError, ZeroDivisionError):
        raise legacy_Invalid('invalid_numeric_input')
    if abs(r.numerator) > 1000000 or r.denominator > 1000000:
        raise legacy_Invalid('numeric_bound_exceeded')
    return r
legacy_ANSWER_PAT = legacy_re.compile('[+-]?(?:[0-9]{1,128}(?:\\.[0-9]{1,128})?|[0-9]{1,128}/[0-9]{1,128})\\Z')

def legacy_answer_num(x):
    if x is None:
        raise legacy_Unknown('missing_answer_value')
    if isinstance(x, bool) or not isinstance(x, (int, str)):
        raise legacy_Invalid('invalid_answer_input')
    if isinstance(x, int) and abs(x) >= 10 ** 128:
        raise legacy_Invalid('answer_bound_exceeded')
    literal = str(x)
    if len(literal) > 258 or not legacy_ANSWER_PAT.fullmatch(literal):
        raise legacy_Invalid('invalid_answer_input')
    try:
        r = legacy_F(literal)
    except (ValueError, ZeroDivisionError):
        raise legacy_Invalid('invalid_answer_input')
    if abs(r.numerator) > 10 ** 256 or r.denominator > 10 ** 256:
        raise legacy_Invalid('answer_bound_exceeded')
    return r

def legacy_txt(x):
    x = legacy_F(x)
    return str(x.numerator) if x.denominator == 1 else f'{x.numerator}/{x.denominator}'

def legacy_answer(decision, ans):
    return {'decision': decision, 'answer': ans}

def legacy_reject(reason):
    return legacy_answer('reject', {'accepted': False, 'reasonCode': reason})

def legacy_confirm(reason):
    return legacy_answer('confirm', {'needsConfirmation': True, 'reasonCode': reason})

def legacy_root1(a, b, c):
    if a == 0:
        return {'classification': 'infinite' if b == c else 'none', 'solutions': []}
    return {'classification': 'unique', 'solutions': [legacy_txt((c - b) / a)]}

def legacy_finish(data, correct, normalize):
    if data.get('task') == 'solve':
        return legacy_answer('pass', correct)
    p = data.get('proposal')
    if p is None:
        return legacy_confirm('missing_proposal')
    try:
        equal = normalize(p) == normalize(correct)
    except (legacy_Invalid, legacy_Unknown, TypeError, KeyError, ValueError):
        equal = False
    if not equal:
        return legacy_answer('reject', {'accepted': False, 'reasonCode': 'incorrect_solution_proposal', 'correctSolution': correct})
    return legacy_answer('pass', {'accepted': True, 'correctSolution': correct})

def legacy_base(data):
    if not isinstance(data, dict):
        raise legacy_Invalid('invalid_input_object')
    if data.get('task') not in ('solve', 'verify_proposal'):
        raise legacy_Unknown('task_unknown')
    if data.get('confirmedEquation') is not True:
        raise legacy_Unknown('equation_not_confirmed')
    return data
import math as legacy_math
legacy_SUBTYPES = ('quadratic-factor-first', 'quadratic-completing-square', 'quadratic-formula')

def legacy_square_root(q):
    if q < 0:
        return None
    a, b = (legacy_math.isqrt(q.numerator), legacy_math.isqrt(q.denominator))
    return legacy_F(a, b) if a * a == q.numerator and b * b == q.denominator else None

def legacy_solve_coefficients(a, b, c):
    if a == 0:
        return legacy_root1(b, c, legacy_F(0))
    center = -b / (2 * a)
    square = center * center - c / a
    if square < 0:
        return {'classification': 'no-real', 'solutions': []}
    if square == 0:
        return {'classification': 'unique', 'solutions': [legacy_txt(center)]}
    root = legacy_square_root(square)
    if root is not None:
        return {'classification': 'two-real', 'solutions': [legacy_txt(center - root), legacy_txt(center + root)]}
    return {'classification': 'two-real', 'solutions': [{'rationalPart': legacy_txt(center), 'radicalSquare': legacy_txt(square), 'sign': sign} for sign in (-1, 1)]}

def legacy_normalize_root(r):
    if isinstance(r, (str, int)) and (not isinstance(r, bool)):
        return ('rational', legacy_answer_num(r))
    if not isinstance(r, dict):
        raise legacy_Invalid('invalid_root_expression')
    if not {'rationalPart', 'radicalSquare', 'sign'} <= set(r) or set(r) - {'rationalPart', 'radicalSquare', 'sign', 'radicalCoefficient'}:
        raise legacy_Invalid('invalid_root_expression')
    center = legacy_answer_num(r.get('rationalPart'))
    square = legacy_answer_num(r.get('radicalSquare'))
    coef = legacy_answer_num(r.get('radicalCoefficient', '1'))
    sign = r.get('sign')
    if type(sign) is not int or sign not in (-1, 1) or square < 0:
        raise legacy_Invalid('invalid_root_expression')
    if coef < 0:
        sign = -sign
    square *= coef * coef
    exact = legacy_square_root(square)
    if exact is not None:
        return ('rational', center + sign * exact)
    return ('surd', center, square, sign)

def legacy_normalize(s):
    cls = s['classification']
    roots = s.get('solutions')
    if set(s) != {'classification', 'solutions'}:
        raise legacy_Invalid('invalid_proposal_structure')
    if cls not in ('unique', 'two-real', 'no-real', 'none', 'infinite') or not isinstance(roots, list):
        raise legacy_Invalid('invalid_proposal')
    normalized = set((legacy_normalize_root(r) for r in roots))
    if cls == 'unique' and len(normalized) != 1:
        raise legacy_Invalid('invalid_proposal')
    if cls == 'two-real' and len(normalized) != 2:
        raise legacy_Invalid('invalid_proposal')
    if cls in ('no-real', 'none', 'infinite') and normalized:
        raise legacy_Invalid('invalid_proposal')
    return (cls, tuple(sorted(normalized, key=repr)))

def legacy_evaluate(subtype_id, input_data):
    if subtype_id not in legacy_SUBTYPES:
        return legacy_confirm('subtype_out_of_scope')
    try:
        d = legacy_base(input_data)
        if d.get('realDomainConfirmed') is not True:
            raise legacy_Unknown('real_domain_unknown')
        a, b, c = (legacy_num(d.get(k)) for k in ('a', 'b', 'c'))
        if subtype_id == 'quadratic-completing-square' and a != 1:
            raise legacy_Unknown('monic_method_required')
        if subtype_id == 'quadratic-factor-first' and any((z.denominator != 1 for z in (a, b, c))):
            raise legacy_Unknown('integer_coefficient_contract')
        correct = legacy_solve_coefficients(a, b, c)
        return legacy_finish(d, correct, legacy_normalize)
    except legacy_Unknown as e:
        return legacy_confirm(str(e))
    except legacy_Invalid as e:
        return legacy_reject(str(e))
legacy_PACK = 'grade8-quadratic-equations'
legacy_CODE = 'A-8-7'

def legacy_run_probes(seeds):
    n = 0

    def p(sub, d, decision):
        nonlocal n
        got = legacy_evaluate(sub, d)
        assert got['decision'] == decision, (sub, got)
        n += 1
        return got
    for sub, d0 in seeds.items():
        for bad in (True, 1.0, '1e999999999', '1/0', 10 ** 5000, '9' * 5001):
            d = legacy_copy.deepcopy(d0)
            d['b'] = bad
            p(sub, d, 'reject')
        d = legacy_copy.deepcopy(d0)
        d['c'] = None
        p(sub, d, 'confirm')
        d = legacy_copy.deepcopy(d0)
        d['realDomainConfirmed'] = None
        p(sub, d, 'confirm')
        correct = legacy_evaluate(sub, d0)['answer']
        d = legacy_copy.deepcopy(d0)
        d['task'] = 'verify_proposal'
        d['proposal'] = correct
        p(sub, d, 'pass')
        d['proposal'] = {'classification': 'unique', 'solutions': ['999']}
        got = p(sub, d, 'reject')
        assert got['answer']['correctSolution'] == correct
    d = {'task': 'solve', 'confirmedEquation': True, 'realDomainConfirmed': True, 'a': '1', 'b': '0', 'c': '1'}
    got = p('quadratic-formula', d, 'pass')
    assert got['answer']['classification'] == 'no-real'
    d['a'] = '0'
    d['b'] = '0'
    d['c'] = '0'
    got = p('quadratic-formula', d, 'pass')
    assert got['answer']['classification'] == 'infinite'
    d['c'] = '2'
    got = p('quadratic-formula', d, 'pass')
    assert got['answer']['classification'] == 'none'
    d = {'task': 'verify_proposal', 'confirmedEquation': True, 'realDomainConfirmed': True, 'a': '1', 'b': '2', 'c': '-1', 'proposal': {'classification': 'two-real', 'solutions': [{'rationalPart': '-1', 'radicalSquare': '8', 'radicalCoefficient': '1/2', 'sign': s} for s in (-1, 1)]}}
    got = p('quadratic-formula', d, 'pass')
    assert got['answer']['accepted'] is True
    d['proposal']['solutions'][0]['radicalCoefficient'] = '1'
    p('quadratic-formula', d, 'reject')
    d = {'task': 'solve', 'confirmedEquation': True, 'realDomainConfirmed': True, 'a': '2', 'b': '0', 'c': '-2'}
    p('quadratic-completing-square', d, 'confirm')
    return n

def legacy_roundtrip_probes():
    count = 0
    new_inputs = [('quadratic-formula', {'a': '1/1000000', 'b': '1000000', 'c': '0'}), ('quadratic-completing-square', {'a': '1', 'b': '1000000', 'c': '-1000000'}), ('quadratic-factor-first', {'a': '1', 'b': '-1000000', 'c': '-1000000'})]
    for sub, fields in new_inputs:
        d = {'task': 'solve', 'confirmedEquation': True, 'realDomainConfirmed': True, **fields}
        got = legacy_evaluate(sub, d)
        assert got['decision'] == 'pass'
        correct = got['answer']
        d['task'] = 'verify_proposal'
        d['proposal'] = legacy_copy.deepcopy(correct)
        assert legacy_evaluate(sub, d)['answer']['accepted'] is True
        count += 1
        for i, r in enumerate(d['proposal']['solutions']):
            if isinstance(r, str):
                v = legacy_F(r)
                d['proposal']['solutions'][i] = str(v.numerator * 2) + '/' + str(v.denominator * 2)
            else:
                r['radicalSquare'] = legacy_txt(legacy_F(r['radicalSquare']) * 4)
                r['radicalCoefficient'] = '1/2'
        assert legacy_evaluate(sub, d)['answer']['accepted'] is True
        count += 1
        for bad in (10 ** 5000, '9' * 5001):
            d['proposal'] = {'classification': 'unique', 'solutions': [bad]}
            g = legacy_evaluate(sub, d)
            assert g['decision'] == 'reject' and g['answer']['correctSolution'] == correct
            count += 1
        d['proposal'] = legacy_copy.deepcopy(correct)
        d['proposal']['unverifiedExtra'] = 'wrong'
        assert legacy_evaluate(sub, d)['decision'] == 'reject'
        count += 1
    return count

def legacy_mutation_probes():
    fixtures = [('quadratic-factor-first', {'a': '1', 'b': '-3', 'c': '2'}, 'c', '0'), ('quadratic-completing-square', {'a': '1', 'b': '2', 'c': '-1'}, 'c', '-2'), ('quadratic-formula', {'a': '1', 'b': '-3', 'c': '2'}, 'b', '-4')]
    for sub, fields, key, new in fixtures:
        d = {'task': 'solve', 'confirmedEquation': True, 'realDomainConfirmed': True, **fields}
        old = legacy_evaluate(sub, d)['answer']
        d[key] = new
        now = legacy_evaluate(sub, d)
        assert now['decision'] == 'pass' and legacy_normalize(old) != legacy_normalize(now['answer'])
        d['task'] = 'verify_proposal'
        d['proposal'] = old
        re = legacy_evaluate(sub, d)
        assert re['decision'] == 'reject' and re['answer']['correctSolution'] == now['answer']
    return len(fixtures)

def legacy_check(path=None, pack_data=None):
    pack = pack_data if pack_data is not None else legacy_json.loads((legacy_Path(path) if path else legacy_Path(__file__).with_name(legacy_PACK + '.json')).read_text())
    cases = pack['cases']
    assert len(cases) == 72 and len({c['id'] for c in cases}) == 72
    counts = legacy_Counter()
    seeds = {}
    decisions = legacy_Counter()
    for c in cases:
        assert c['code'] == legacy_CODE and c['subtypeId'] in legacy_SUBTYPES
        assert c['teacherReviewed'] is False and c['appConnected'] is False
        assert c['casePurpose'] in ('teaching-example', 'proposal-review', 'validator-guard')
        assert c['studentFacing'] is (c['casePurpose'] != 'validator-guard')
        assert len(c['solutionSteps']) >= 3 and all(c['solutionSteps'])
        counts[c['subtypeId'], c['kind']] += 1
        got = legacy_evaluate(c['subtypeId'], c['input'])
        wanted = {'decision': c['expectedDecision'], 'answer': c['expectedAnswer']}
        assert got == wanted, (c['id'], got, wanted)
        decisions[got['decision']] += 1
        if c['kind'] == 'normal':
            seeds.setdefault(c['subtypeId'], c['input'])
    for s in legacy_SUBTYPES:
        assert {k: counts[s, k] for k in ('normal', 'negative', 'boundary', 'ambiguous', 'holdout')} == {'normal': 8, 'negative': 6, 'boundary': 4, 'ambiguous': 2, 'holdout': 4}
    probes = legacy_run_probes(seeds) + legacy_roundtrip_probes()
    mutations = legacy_mutation_probes()
    mutated = legacy_copy.deepcopy(cases[0])
    mutated['expectedAnswer'] = {'fabricated': True}
    assert legacy_evaluate(mutated['subtypeId'], mutated['input'])['answer'] != mutated['expectedAnswer']
    return {'code': legacy_CODE, 'caseCount': 72, 'subtypes': 3, 'decisions': dict(decisions), 'counterfactualProbes': probes, 'mathematicalMutationProbes': mutations, 'expectedIsolation': True, 'teacherReviewed': False, 'appConnected': False}

import json as extension_json, sys as extension_sys, re as extension_re, math as extension_math
from fractions import Fraction as extension_F
extension_SUBTYPES = {'a87-tool-quadratic-root-precision'}

class extension_Bad(Exception):
    pass

class extension_Missing(Exception):
    pass

def extension_bounded(x, depth=0, budget=None):
    if budget is None:
        budget = [0]
    budget[0] += 1
    if depth > 10 or budget[0] > 1200:
        raise extension_Bad('資料結構超限')
    if isinstance(x, (dict, list)):
        if len(x) > 64:
            raise extension_Bad('容器超限')
        for k, v in x.items() if isinstance(x, dict) else enumerate(x):
            if isinstance(x, dict) and (not isinstance(k, str) or len(k) > 80):
                raise extension_Bad('鍵不合法')
            extension_bounded(v, depth + 1, budget)
    elif isinstance(x, str) and len(x) > 1024:
        raise extension_Bad('文字超限')
    elif type(x) is float and (not extension_math.isfinite(x)):
        raise extension_Bad('浮點必須是有限字面；數量仍不接受浮點')
    elif not isinstance(x, (str, int, bool, float, type(None))):
        raise extension_Bad('僅收字串、整數與明確旗標')
    elif type(x) is int and x.bit_length() > 4096:
        raise extension_Bad('整數超限')

def extension_num(x, answer=False):
    if type(x) is int:
        s = str(x)
    elif type(x) is str:
        s = x
    else:
        raise extension_Bad('數值不可為布林或浮點')
    if len(s) > (256 if answer else 64) or not extension_re.fullmatch('[+-]?\\d+(?:\\.\\d+|/[1-9]\\d*)?', s):
        raise extension_Bad('只收有界整數、分數或有限小數')
    z = extension_F(s)
    if not answer and (abs(z) > 10 ** 6 or z.denominator > 10 ** 8):
        raise extension_Bad('超出原量範圍')
    return z

def extension_nested_missing(x):
    return x is None or (isinstance(x, (list, dict)) and any((extension_nested_missing(v) for v in (x.values() if isinstance(x, dict) else x))))

def extension_pre(d, required):
    if not isinstance(d, dict):
        raise extension_Bad('輸入須為物件')
    if any((k not in d or extension_nested_missing(d[k]) for k in required)):
        raise extension_Missing('先確認題目缺少的量或條件')
    for k in required:
        if k.endswith('Confirmed'):
            if type(d[k]) is not bool:
                raise extension_Bad('確認旗標須為布林')
            if not d[k]:
                raise extension_Missing('先確認原條件，不從外觀推測')
    extra = set(d) - set(required) - {'task', 'proposal'}
    if extra:
        raise extension_Bad('未知輸入欄位')
    if d.get('task', 'solve') not in ['solve', 'check_proposal']:
        raise extension_Bad('未知操作')
    if d.get('task') == 'check_proposal' and 'proposal' not in d:
        raise extension_Missing('先提供要核對的提案')

def extension_eq(a, b):
    if type(a) is bool or type(b) is bool:
        return type(a) is type(b) and a == b
    if isinstance(a, dict):
        return isinstance(b, dict) and set(a) == set(b) and all((extension_eq(v, b[k]) for k, v in a.items()))
    if isinstance(a, list) and isinstance(b, list) and all((isinstance(x, str) and x in ['AB', 'BC', 'CA'] for x in a + b)):
        return len(a) == len(b) and len(set(b)) == len(b) and (set(a) == set(b))
    if isinstance(a, list):
        return isinstance(b, list) and len(a) == len(b) and all((extension_eq(x, y) for x, y in zip(a, b)))
    if isinstance(a, str) and isinstance(b, (str, int)):
        try:
            return extension_num(a, True) == extension_num(b, True)
        except extension_Bad:
            pass
    return type(a) is type(b) and a == b

def extension_perimeter(d):
    keys = ['firstWidth', 'firstHeight', 'secondWidth', 'secondHeight', 'firstJoinedSide', 'secondJoinedSide', 'sharedLength', 'placementConfirmed', 'interiorsDisjointConfirmed', 'onlySharedSegmentConfirmed', 'unit']
    extension_pre(d, keys)
    a, b, c, e = [extension_num(d[k]) for k in keys[:4]]
    s = extension_num(d['sharedLength'])
    if any((x <= 0 or x.denominator != 1 for x in [a, b, c, e, s])):
        raise extension_Bad('邊長及共享長須為正整數')
    if d['unit'] not in ['公分', '公尺']:
        raise extension_Bad('兩圖須用同一已確認長度單位')
    if d['firstJoinedSide'] not in ['width', 'height'] or d['secondJoinedSide'] not in ['width', 'height']:
        raise extension_Bad('接合邊角色不明')
    l1 = a if d['firstJoinedSide'] == 'width' else b
    l2 = c if d['secondJoinedSide'] == 'width' else e
    if s > min(l1, l2):
        raise extension_Bad('共享長超出接合邊，已知資料矛盾')
    p1 = 2 * (a + b)
    p2 = 2 * (c + e)
    return {'firstPerimeter': str(p1), 'secondPerimeter': str(p2), 'internalEdgeDeduction': str(2 * s), 'outerPerimeter': str(p1 + p2 - 2 * s), 'unit': d['unit'], 'physicalArrangementVerifiedByChecker': False}

def extension_ordering(d):
    keys = ['angles', 'oppositeEdges', 'triangleConfirmed', 'unit']
    if isinstance(d, dict) and isinstance(d.get('angles'), list) and any((v is None for v in d['angles'])):
        raise extension_Missing('先確認三個內角，不能由圖猜缺角')
    extension_pre(d, keys)
    if d['unit'] != '度':
        raise extension_Bad('角須以度表示')
    if not isinstance(d['angles'], list) or len(d['angles']) != 3:
        raise extension_Bad('依A、B、C給三內角')
    v = [extension_num(x) for x in d['angles']]
    if any((x <= 0 for x in v)) or sum(v) != 180:
        raise extension_Bad('三內角必須為正且合計180度')
    if d['oppositeEdges'] != ['BC', 'CA', 'AB']:
        raise extension_Bad('A、B、C對邊映射錯誤，先核標籤')
    groups = []
    for x in sorted(set(v)):
        groups.append(sorted((d['oppositeEdges'][i] for i, z in enumerate(v) if z == x)))
    return {'ascendingOppositeEdgeGroups': groups, 'numericalSideLengthsDetermined': False}

def extension_round_abs(x, p):
    t = x * 10 ** p
    return (1 if t >= 0 else -1) * ((abs(t).numerator * 2 + abs(t).denominator) // (2 * abs(t).denominator))

def extension_rounding_range(lo, hi, lc, hc, p):

    def at(x, side):
        t = x * 10 ** p
        v = extension_round_abs(x, p)
        tie = (2 * abs(t)).denominator == 1 and (2 * abs(t)).numerator % 2 == 1
        if tie and side == 'right' and (t < 0):
            v += 1
        if tie and side == 'left' and (t > 0):
            v -= 1
        return v
    return (at(lo, 'at' if lc else 'right'), at(hi, 'at' if hc else 'left'))

def extension_dec(i, p):
    sign = '-' if i < 0 else ''
    s = str(abs(i)).zfill(p + 1)
    return sign + s if p == 0 else sign + s[:-p] + '.' + s[-p:]

def extension_quadratic(d):
    keys = ['a', 'b', 'c', 'reportedSqrt', 'reportedPlaces', 'reportRounding', 'sourceDescription', 'sourceConfirmed', 'equationConfirmed', 'resultPlaces', 'resultRounding', 'selection', 'selectionConfirmed']
    extension_pre(d, keys)
    a, b, c = [extension_num(d[k]) for k in ['a', 'b', 'c']]
    if a == 0:
        raise extension_Bad('不是二次方程，轉既有非二次原式核對')
    D = b * b - 4 * a * c
    if D <= 0:
        raise extension_Bad('判別式非正，轉既有無實根或重根精確方法')
    if extension_math.isqrt(D.numerator) ** 2 == D.numerator and extension_math.isqrt(D.denominator) ** 2 == D.denominator:
        raise extension_Bad('可精確開根，轉既有精確根模板')
    q = extension_num(d['reportedSqrt'])
    p = d['reportedPlaces']
    r = d['resultPlaces']
    if type(p) is not int or type(r) is not int or (not (0 <= p <= 8 and 0 <= r <= 8)):
        raise extension_Bad('位數須為0至8的整數')
    if d['reportRounding'] != 'half-up-positive' or d['resultRounding'] != 'nearest-ties-away-from-zero':
        raise extension_Bad('須先確認本方法的捨入規則')
    if q < 0 or (q * 10 ** p).denominator != 1:
        raise extension_Bad('主平方根回報須非負且符合回報位數')
    if type(d['sourceDescription']) is not str or not 1 <= len(d['sourceDescription']) <= 200:
        raise extension_Bad('需有界來源說明')
    if d['selection'] not in ['all-real', 'positive']:
        raise extension_Bad('須明列取全部實根或正值情境')
    h = extension_F(1, 2 * 10 ** p)
    l = max(extension_F(0), q - h)
    u = q + h
    lc = True
    hc = False
    if l * l > D or u * u <= D:
        raise extension_Bad('回報區間不含此方程判別式的主平方根，不能用確認旗標蓋過矛盾')
    branches = []
    for sign in [1, -1]:
        lo = (-b + sign * l) / (2 * a)
        hi = (-b + sign * u) / (2 * a)
        cl, ch = (lc, hc)
        if lo > hi:
            lo, hi, cl, ch = (hi, lo, ch, cl)
        estimate = (-b + sign * q) / (2 * a)
        mn, mx = extension_rounding_range(lo, hi, cl, ch, r)
        if sign == 1:
            sg = (1 if D > b * b else -1) if b > 0 else 1
        else:
            sg = (-1 if D > b * b else 1) if b < 0 else -1
        if D == b * b:
            sg = 0
        if a < 0:
            sg = -sg
        keep = d['selection'] == 'all-real' or sg > 0
        branches.append({'branch': 'plus' if sign == 1 else 'minus', 'kept': keep, 'interval': {'lo': str(lo), 'hi': str(hi), 'loClosed': cl, 'hiClosed': ch}, 'estimate': str(estimate), 'estimateRounded': extension_dec(extension_round_abs(estimate, r), r), 'possibleRoundedMinimum': extension_dec(mn, r), 'possibleRoundedMaximum': extension_dec(mx, r), 'precisionGuaranteed': mn == mx, 'guaranteedRoundedValue': extension_dec(mn, r) if mn == mx else None, 'needMorePrecision': mn != mx, 'exactRootSign': sg})
    return {'discriminant': str(D), 'sqrtInterval': {'lo': str(l), 'hi': str(u), 'loClosed': True, 'hiClosed': False}, 'branches': branches, 'resultPlaces': r, 'approximate': True, 'selection': d['selection'], 'toolIndependentlyVerified': False, 'precisionGuaranteeBasis': 'given-tool-report-interval-only', 'equationRootsMathematicallyDeterminate': True, 'representativeEstimateIsFinalAnswerWhenUnguaranteed': False}

def extension_evaluate(subtype_id, input_data):
    try:
        extension_bounded(input_data)
        if subtype_id not in extension_SUBTYPES:
            raise extension_Bad('未知方法')
        ans = {'s43-shared-edge-perimeter': extension_perimeter, 's88-angle-to-opposite-side-order': extension_ordering, 'a87-tool-quadratic-root-precision': extension_quadratic}[subtype_id](input_data)
        if input_data.get('task') == 'check_proposal' and (not extension_eq(ans, input_data['proposal'])):
            return {'decision': 'reject', 'answer': {'correctSolution': ans}, 'reason': '提案與原量關係不一致，保留正確解法'}
        return {'decision': 'pass', 'answer': ans}
    except extension_Missing as e:
        return {'decision': 'confirm', 'answer': None, 'reason': str(e)}
    except (extension_Bad, ValueError, TypeError, KeyError, ZeroDivisionError, OverflowError, RecursionError) as e:
        return {'decision': 'block', 'answer': None, 'reason': str(e)}

def extension_main():
    if len(extension_sys.argv) > 1 and extension_sys.argv[1] in ['evaluate', '--evaluate']:
        try:
            raw = extension_sys.stdin.read(65537)
            if len(raw) > 65536:
                raise extension_Bad('stdin超限')
            x = extension_json.loads(raw)
            if not isinstance(x, dict) or set(x) != {'subtypeId', 'input'}:
                raise extension_Bad('入口須有subtypeId及input')
            out = extension_evaluate(x['subtypeId'], x['input'])
        except (extension_Bad, ValueError, TypeError, RecursionError, OverflowError) as e:
            out = {'decision': 'block', 'answer': None, 'reason': str(e)}
        print(extension_json.dumps(out, ensure_ascii=False))
        return
    path = __file__.replace('check-', '').replace('.py', '.json')
    pack = extension_json.load(open(path))
    errors = []
    for c in pack['cases']:
        got = extension_evaluate(c['subtypeId'], c['input'])
        if got['decision'] != c['expectedDecision'] or not extension_eq(got['answer'], c['expectedAnswer']):
            errors.append(c['id'])
    print(extension_json.dumps({'cases': len(pack['cases']), 'errors': errors, 'passed': not errors}, ensure_ascii=False))
    if errors:
        extension_sys.exit(1)


# Public owner router. Both static namespaces above retain their own globals.
import json as _json
import sys as _sys
import pathlib as _pathlib
import collections as _collections
import math as _math
import copy as _copy
import io as _io
import contextlib as _contextlib
PACK_SLUG='grade8-quadratic-equations'
OWNER_KIND='a87'
LEGACY_TYPES=['quadratic-factor-first', 'quadratic-completing-square', 'quadratic-formula']
EXTENSION_TYPES=['a87-tool-quadratic-root-precision']
SUBTYPES=tuple(LEGACY_TYPES)+tuple(EXTENSION_TYPES)
class _CLIError(ValueError):pass

def evaluate(subtype_id,input_data):
    if type(subtype_id)is not str:
        return {'decision':'block','answer':None,'reason':'方法名稱須為字串'}
    if subtype_id in LEGACY_TYPES:return legacy_evaluate(subtype_id,input_data)
    if subtype_id in EXTENSION_TYPES:return extension_evaluate(subtype_id,input_data)
    return {'decision':'block','answer':None,'reason':'未知方法；不按輸入猜測其他子型'}

def _partition(data,types):
    result=dict(data)
    result['cases']=[c for c in data['cases']if c.get('subtypeId')in types]
    result['subtypes']=[s for s in data['subtypes']if s.get('id')in types]
    return result

def _extension_errors(data):
    errors=[]
    for c in data['cases']:
        z=extension_evaluate(c.get('subtypeId'),c.get('input'))
        if z['decision']!=c.get('expectedDecision')or not extension_eq(z['answer'],c.get('expectedAnswer')):errors.append({'id':c.get('id'),'actual':z})
    return errors

# Keep legacy standalone validators and probes; filter only the appended family.


def _legacy_validation(data):
    old=_partition(data,LEGACY_TYPES)
    if OWNER_KIND=='s43':
        errors,decisions=legacy_verify_package_original(old)
        return errors,{'legacyCaseCount':len(old['cases']),'legacyDecisions':decisions}
    if OWNER_KIND=='a87':
        evidence=legacy_check(pack_data=old)
        return [],{'legacyValidation':evidence}
    errors=legacy_verify_package(old)
    return errors,{'legacyCaseCount':len(old['cases'])}

def check(path=None,self_test=False):
    location=_pathlib.Path(path)if path else _pathlib.Path(__file__).with_name(PACK_SLUG+'.json')
    data=_safe_loads(location.read_text(encoding='utf8'),max_chars=4000000)
    errors=[]
    if len(data.get('cases',[]))!=96:errors.append('expected 96 owner cases')
    if {s.get('id')for s in data.get('subtypes',[])}!=set(SUBTYPES):errors.append('owner must contain exactly four declared subtypes')
    if len({c.get('id')for c in data.get('cases',[])})!=96:errors.append('duplicate/missing case IDs')
    if data.get('teacherReviewed')is not False or data.get('appConnected')is not False:errors.append('draft/offline flags required')
    counts=_collections.Counter((c.get('subtypeId'),c.get('kind'))for c in data.get('cases',[]))
    for s in SUBTYPES:
        for kind,count in [('normal',8),('negative',6),('boundary',4),('ambiguous',2),('holdout',4)]:
            if counts[s,kind]!=count:errors.append('case distribution '+s+'/'+kind)
    for c in data.get('cases',[]):
        if c.get('subtypeId')not in SUBTYPES:errors.append('undeclared case subtype')
        if c.get('casePurpose')not in ('teaching-example','proposal-review','validator-guard')or c.get('studentFacing')is not(c.get('casePurpose')!='validator-guard'):errors.append('case purpose/student visibility')
        if c.get('teacherReviewed')is not False or c.get('appConnected')is not False:errors.append('case falsely reviewed/connected')
    old_errors,evidence=_legacy_validation(data);errors.extend(old_errors)
    extra=_partition(data,EXTENSION_TYPES);errors.extend(_extension_errors(extra))
    if len(extra['cases'])!=24:errors.append('expected 24 extension cases')
    if self_test and OWNER_KIND=='s43':
        buffer=_io.StringIO()
        with _contextlib.redirect_stdout(buffer):status=legacy_main([str(location),'--self-test'])
        legacy_report=_json.loads(buffer.getvalue())
        legacy_report['loadedMergedCaseCount']=legacy_report['caseCount']
        legacy_report['caseCount']=len(_partition(data,LEGACY_TYPES)['cases'])
        if status or not legacy_report['ok']:errors.append('legacy standalone self-test failed')
        evidence['legacyStandaloneSelfTest']=legacy_report
    decisions=_collections.Counter(evaluate(c['subtypeId'],c['input'])['decision']for c in data['cases'])
    return {'ok':not errors,'code':data['code'],'caseCount':len(data['cases']),'subtypeCount':len(SUBTYPES),'decisions':dict(decisions),'preservedLegacyValidator':evidence,'extensionCasesChecked':len(extra['cases']),'errors':errors,'teacherReviewed':False,'appConnected':False,'wholeCodeValidated':False}

def verify_package(data):
    old_errors,_=_legacy_validation(data)
    return old_errors+_extension_errors(_partition(data,EXTENSION_TYPES))

def validate_pack(data):return verify_package(data)

def _pairs(pairs):
    out={}
    for k,v in pairs:
        if k in out:raise _CLIError('JSON有重複欄位')
        out[k]=v
    return out

def _integer(literal):
    if len(literal)>1234:raise _CLIError('整數字面超限')
    x=int(literal)
    if x.bit_length()>4096:raise _CLIError('整數資源超限')
    return x

def _float(literal):
    if len(literal)>128:raise _CLIError('小數字面超限')
    value=float(literal)
    if not _math.isfinite(value):raise _CLIError('禁止非有限數')
    return value

def _constant(literal):raise _CLIError('禁止非JSON有限數常數')

def _shape(value,depth=0,budget=None):
    if budget is None:budget=[0]
    budget[0]+=1
    if depth>32 or budget[0]>100000:raise _CLIError('JSON結構超限')
    if type(value)in(dict,list):
        if len(value)>10000:raise _CLIError('JSON容器超限')
        for child in value.values()if type(value)is dict else value:_shape(child,depth+1,budget)
    elif type(value)is str and len(value)>16384:raise _CLIError('JSON文字超限')

def _safe_loads(raw,max_chars=65536):
    if len(raw)>max_chars:raise _CLIError('JSON輸入超限')
    data=_json.loads(raw,object_pairs_hook=_pairs,parse_int=_integer,parse_float=_float,parse_constant=_constant)
    _shape(data)
    return data

def main(argv=None):
    args=list(_sys.argv[1:]if argv is None else argv)
    if args and args[0]in('evaluate','--evaluate'):
        try:
            if len(args)==3:
                # Preserve the old S88 evaluate SUBTYPE JSON invocation.
                subtype=args[1];data=_safe_loads(args[2])
            elif len(args)==1:
                envelope=_safe_loads(_sys.stdin.read(65537))
                if type(envelope)is not dict or set(envelope)!={'subtypeId','input'}:raise _CLIError('需提供方法名稱與原條件')
                subtype=envelope['subtypeId'];data=envelope['input']
            else:raise _CLIError('evaluate參數不符')
            z=evaluate(subtype,data)
        except (ValueError,TypeError,KeyError,RecursionError,OverflowError)as e:z={'decision':'block','answer':None,'reason':str(e)}
        print(_json.dumps(z,ensure_ascii=False));return 0
    try:
        self_test='--self-test'in args
        paths=[x for x in args if x!='--self-test']
        if len(paths)>1 or any(x.startswith('--')for x in paths):raise _CLIError('僅接受一個離線案例路徑及--self-test')
        report=check(paths[0]if paths else None,self_test=self_test)
    except (OSError,ValueError,TypeError,KeyError,AssertionError,RecursionError,OverflowError)as e:
        report={'ok':False,'error':str(e)}
    print(_json.dumps(report,ensure_ascii=False,indent=2));return 0 if report.get('ok')else 1

if __name__=='__main__':_sys.exit(main())
