#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Exact squared-bound checks; no float roots or calculator-device verification."""
import json,pathlib,re,sys,math
from fractions import Fraction as F
SUBTYPES={'n82-integer-part','n82-tenths-rounding','n82-calculator-report'}
NUMERIC={'integerPart','lowerSquare','upperSquare','lower','upper','rounded','correctValue'}
def number(v,answer=False):
    if type(v)is int:
        if abs(v)>10**18:raise ValueError('數量過大')
        q=F(v)
    elif type(v)is str and len(v)<=60 and re.fullmatch(r'-?[0-9]{1,18}(?:/[1-9][0-9]{0,17}|\.[0-9]{1,12})?',v,re.ASCII):q=F(v)
    else:raise ValueError('僅接受有限白名單精確數值；不收浮點、真假值或指數記法')
    if not answer and (abs(q)>10**8 or q.denominator>10**12):raise ValueError('超出明列有限原量範圍')
    return q

def decimal(k,p):
    if p==0:return str(k)
    text=str(k).zfill(p+1);return text[:-p]+'.'+text[-p:]

def compute(s,r):
    q=number(r['radicand']);real=q>=0
    if s=='n82-integer-part':
        n=math.isqrt(q.numerator//q.denominator)if real else None
        return dict(status='real'if real else'no-real-root',integerPart=str(n)if real else None,lowerSquare=str(n*n)if real else None,upperSquare=str((n+1)**2)if real else None,returnedValueIsExact=(q==n*n)if real else False)
    p=r['precision']
    if type(p)is not int or not 0<=p<=4:raise ValueError('精度須為0至4的小數位數')
    if real:
        scale=10**p;k=math.isqrt((q*scale*scale).numerator//(q*scale*scale).denominator)
        exact=(F(k,scale)**2==q);lower=decimal(k,p);upper=decimal(k if exact else k+1,p)
        # Principal square root is nonnegative: compare with the exact midpoint.
        rounded=decimal(k+int(q>=F(2*k+1,2*scale)**2),p)
    else:exact=False;lower=upper=rounded=None
    if s=='n82-tenths-rounding':return dict(status='real'if real else'no-real-root',precision=p,lower=lower,upper=upper,rounded=rounded,returnedValueIsExact=exact)
    displayed=number(r['display'],answer=True)
    return dict(status='real'if real else'no-real-root',precision=p,correctValue=rounded,reportMatches=(real and displayed==F(rounded)),returnedValueIsExact=exact)

def equivalent(p,a):
    if type(p)is not dict or set(p)!=set(a):return False
    try:
        for k,v in a.items():
            if v is None:
                if p[k]is not None:return False
            elif k in NUMERIC:
                if number(p[k],True)!=number(v,True):return False
            elif type(p[k])is not type(v)or p[k]!=v:return False
        return True
    except(ValueError,TypeError,OverflowError,ZeroDivisionError):return False

def evaluate(s,r):
    def out(d,a=None,why=''):return dict(decision=d,answer=a,reason=why)
    if type(s)is not str or s not in SUBTYPES or type(r)is not dict:return out('block',why='不在本型結構')
    required=['radicand','factsConfirmed','task']+([]if s=='n82-integer-part'else['precision'])+(['display']if s=='n82-calculator-report'else[])
    if any(k not in r or r[k]is None for k in required):return out('confirm',why='先確認原數、所求精度或計算機回報值，不自行補數')
    if set(r)-set(required)-{'proposal'}:return out('block',why='未定義欄位')
    if type(r['factsConfirmed'])is not bool:return out('block',why='確認狀態必須是真假值')
    if not r['factsConfirmed']:return out('confirm',why='原數未確認')
    if type(r['task'])is not str or r['task']not in ['solve','check_proposal']:return out('block',why='不支援本任務')
    try:a=compute(s,r)
    except(ValueError,TypeError,OverflowError,ZeroDivisionError):return out('block',why='原量格式或有限範圍不符；不代表原題在其他方法無解')
    if r['task']=='check_proposal':
        if r.get('proposal')is None:return out('confirm',a,'請先提供要核對的想法')
        if not equivalent(r['proposal'],a):return out('reject',a,'保留原條件，回到平方夾界、精度或近似不等於精確的錯步')
    return out('pass',a,'精確比較平方與中點；不驗計算機實物操作，也不以四捨五入值冒充精確根')

if __name__=='__main__':
    if len(sys.argv)>1 and sys.argv[1]=='evaluate':
        x=json.load(sys.stdin);print(json.dumps(evaluate(x.get('subtypeId'),x.get('input')),ensure_ascii=False))
    else:
        data=json.loads(pathlib.Path(__file__).with_name('grade8-root-approximations.json').read_text())
        for c in data['cases']:
            a=evaluate(c['subtypeId'],c['input']);assert a['decision']==c['expectedDecision']and a['answer']==c['expectedAnswer'],c['id']
        print('PASS',len(data['cases']),'exact root-approximation contracts')
