import json,pathlib,sys,re,collections
from fractions import Fraction as F
PACK='grade9-quadratic-meaning';SUBTYPES=['g9-quadratic-value', 'g9-rectangle-model']
REQ={'g9-prism':['solid','length','width','height','unit'],'g9-cone':['solid','radius','radiusRole','sideLength','heightRole','unit','piRule'],'g9-pyramid':['solid','baseSide','sideFaceHeight','heightRole','unit'],'g9-quadratic-value':['a','b','c','x'],'g9-rectangle-model':['offset','x','unit'],'g9-vertex-features':['a','h','k','domain'],'g9-vertex-bounds':['a','h','k','domain']}
class Invalid(Exception):pass
class Need(Exception):pass
class Route(Exception):pass

def rational(x):
 if type(x)is int and abs(x)<=1000:return F(x)
 if type(x)is str and len(x)<=40 and re.fullmatch(r'-?[0-9]{1,12}(?:/[1-9][0-9]{0,11}|\.[0-9]{1,6})?',x,re.ASCII):
  n=F(x)
  if abs(n)<=1000 and n.denominator<=1000:return n
 raise Invalid('原量需為有界精確整數/有理數文字，拒浮點真假值；較大原量轉相符方法')
def derived(x):
 if type(x)is int and abs(x)<10**256:return F(x)
 if type(x)is str and len(x)<=520 and re.fullmatch(r'-?[0-9]{1,256}(?:/[1-9][0-9]{0,255}|\.[0-9]{1,256})?',x,re.ASCII):return F(x)
 raise Invalid('答案需為有界精確數，不收浮點真假值')
def enum(x,choices):
 if type(x)is not str or x not in choices:raise Invalid('原條件的形體、角色、單位或規則不在本方法')
 return x

def positive(x):
 q=rational(x)
 if q<=0:raise Need('正立體需正長度；0或負長度與題面矛盾，先核對，不當真實立體算')
 return q

def unit(x):return enum(x,['公分','公尺'])
def domain(d):
 if type(d)is not dict:raise Invalid('定義域需明確結構資料')
 if d.get('kind')is None:raise Need('請先確認函數定義域，不把缺域自動補成全實數')
 if set(d)-{'kind','lower','upper'}:raise Invalid('定義域未知欄位')
 kind=enum(d['kind'],['all-real','closed'])
 if kind=='closed':
  if d.get('lower')is None or d.get('upper')is None:raise Need('區間端點還缺資料，先補清')
  lo,hi=rational(d['lower']),rational(d['upper'])
  if lo>hi:raise Need('閉區間左右端點次序矛盾，先核對')
  raise Route('已確認是閉區間，本包不把原域改成全實數；閉區間端點極值另列未覆蓋方法')
 if set(d)!={'kind'}:raise Invalid('全實數域不額外附區間端點')
 return kind

def compute(s,d):
 if s=='g9-prism':
  enum(d['solid'],['right-rectangular-prism']);u=unit(d['unit']);l,w,h=[positive(d[k])for k in ['length','width','height']]
  return {'surface':str(2*(l*w+l*h+w*h)),'volume':str(l*w*h),'areaUnit':'平方'+u,'volumeUnit':'立方'+u}
 if s=='g9-cone':
  enum(d['solid'],['right-circular-cone']);u=unit(d['unit']);role=enum(d['radiusRole'],['radius','diameter']);hr=enum(d['heightRole'],['slant','vertical'])
  if role!='radius' or hr!='slant':raise Route('本型需已確認半徑與斜高；直徑先換半徑，垂高先轉斜高方法，不能直接混用')
  r,l=positive(d['radius']),positive(d['sideLength'])
  if l<=r:raise Need('正直圓錐的斜高必大於半徑；目前長度矛盾或退化，不能只靠確認旗標算面積')
  rule=enum(d['piRule'],['symbolic','3.14','22/7']);c=r*r+r*l
  if rule=='symbolic':return {'piCoefficient':str(c),'piRule':rule,'approximate':False,'areaUnit':'平方'+u}
  return {'value':str(c*F(rule)),'piRule':rule,'approximate':True,'areaUnit':'平方'+u}
 if s=='g9-pyramid':
  enum(d['solid'],['regular-square-pyramid']);u=unit(d['unit']);hr=enum(d['heightRole'],['slant','vertical'])
  if hr!='slant':raise Route('本型需已確認側面三角形的高；垂直高不是側面高，先轉求斜高方法')
  b,l=positive(d['baseSide']),positive(d['sideFaceHeight'])
  if l<=b/2:raise Need('正四角錐側面高須大於底邊一半，否則正立體條件矛盾或退化')
  return {'surface':str(b*b+2*b*l),'areaUnit':'平方'+u}
 if s=='g9-quadratic-value':
  a,b,c,x=[rational(d[k])for k in ['a','b','c','x']];return {'isQuadratic':a!=0,'value':str(a*x*x+b*x+c)}
 if s=='g9-rectangle-model':
  c,x=rational(d['offset']),rational(d['x']);u=unit(d['unit'])
  if x<=0 or x+c<=0:raise Need('長方形長寬必正；本次指定寬或長與形體矛盾，先確認，代數式本身仍可另外代值')
  return {'a':'1','b':str(c),'c':'0','area':str(x*(x+c)),'areaUnit':'平方'+u,'lowerBound':str(max(F(0),-c)),'lowerStrict':True}
 a,h,k=[rational(d[x])for x in ['a','h','k']];domain(d['domain'])
 if a==0:raise Route('a已確認為0，這是常數函數，不套拋物線頂點；是否二次的合法判別可交給係數判讀型回答否')
 if s=='g9-vertex-features':return {'opening':'up'if a>0 else'down','vertexX':str(h),'vertexY':str(k),'axisX':str(h),'horizontalShift':str(h),'verticalShift':str(k)}
 return {'minimumExists':a>0,'minimum':str(k)if a>0 else None,'minimumAt':str(h)if a>0 else None,'maximumExists':a<0,'maximum':str(k)if a<0 else None,'maximumAt':str(h)if a<0 else None}

def equivalent(p,a):
 if type(p)is not dict or set(p)!=set(a):return False
 numeric={'surface','volume','piCoefficient','value','a','b','c','area','lowerBound','vertexX','vertexY','axisX','horizontalShift','verticalShift','minimum','minimumAt','maximum','maximumAt'}
 try:
  for k,v in a.items():
   if v is None:
    if p[k]is not None:return False
   elif type(v)is bool:
    if type(p[k])is not bool or p[k]!=v:return False
   elif k in numeric:
    if derived(p[k])!=derived(v):return False
   elif type(p[k])is not str or p[k]!=v:return False
  return True
 except(Invalid,ValueError,ZeroDivisionError,TypeError):return False

def evaluate(s,d):
 def out(k,a=None,why=''):return dict(decision=k,answer=a,reason=why)
 if type(s)is not str or s not in SUBTYPES or type(d)is not dict:return out('block',why='非本有限文字方法')
 if any(d.get(k)is None for k in REQ[s]+['factsConfirmed']):return out('confirm',why='原題必要數量、形體、角色或定義域尚缺，請補清，不猜照片')
 if 'domain'in REQ[s]and type(d['domain'])is dict:
  dom=d['domain']
  if dom.get('kind')is None or dom.get('kind')=='closed'and any(dom.get(k)is None for k in ['lower','upper']):return out('confirm',why='定義域必要條件缺漏，先補清，不改成全實數')
 if type(d['factsConfirmed'])is not bool:return out('block',why='條件確認狀態需明確真假值')
 if not d['factsConfirmed']:return out('confirm',why='原形體、代數式或條件未確認，先核對')
 if set(d)-set(REQ[s])-{'factsConfirmed','task','proposal'}:return out('block',why='未知欄位不可當作已確認條件')
 if type(d.get('task'))is not str or d['task']not in ['solve','check_proposal']:return out('block',why='未知任務')
 try:a=compute(s,d)
 except Need as e:return out('confirm',why=str(e))
 except(Route,Invalid,ValueError,TypeError,ZeroDivisionError,OverflowError)as e:return out('block',why=str(e))
 if d['task']=='check_proposal':
  if d.get('proposal')is None:return out('confirm',a,'先提供要核對的想法，原條件正解保留')
  if not equivalent(d['proposal'],a):return out('reject',a,'錯提案不改原形體/代數式/原域，保留正解並回到具體錯步')
 return out('pass',a,'由已確認原條件重算，不宣稱圖像或實測辨識')

def check():
 p=json.load(open(pathlib.Path(__file__).with_name(PACK+'.json')))
 for s in SUBTYPES:assert 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(json.dumps({'package':PACK,'cases':len(p['cases']),'passed':True}))
if __name__=='__main__':
 if len(sys.argv)>1 and sys.argv[1]=='evaluate':
  q=json.load(sys.stdin);print(json.dumps(evaluate(q.get('subtypeId'),q.get('input')),ensure_ascii=False))
 else:check()
