import json,pathlib,re,sys,collections
from fractions import Fraction as F
PACK='grade3-circle-parts';SUBTYPES={'s33-circle-segment': 'circle-segment', 's33-circle-compass': 'circle-compass'}
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 Invalid(Exception):pass
class Need(Exception):pass
class Route(Exception):pass

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

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

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

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

def quad(d):
 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 Invalid('需依周圍順序記四邊與四角')
 xs=[q(x,True)for x in xs]
 if any(type(x)is not bool for x in rr):raise Invalid('四角需逐一記是否貼合直角板')
 if max(xs)>=sum(xs)-max(xs):raise 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 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 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 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 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 pid(x):
 if type(x)is not str or not re.fullmatch(r'p[1-8]',x):raise Invalid('原片標記需為明列p1到p8，不接受任意長字串')
 return x

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

def compute(mode,d):
 if mode in ['angle-overlay','angle-right']:
  for k in ['vertexAligned','sideAligned','sameHalfPlane']:yes(d[k])
  pos=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 Invalid('四條已記邊長需完整列表')
   [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']:yes(d[k])
  enum(d['cellUnit'],['1平方公分']);rows=d['rowCounts']
  if type(rows)is not list or len(rows)>100:raise Invalid('需已點好的百格板逐排格數列表')
  rows=[integer(x,0,100)for x in rows];total=sum(rows)
  if total>100:raise Route('本包百格板最多100格，較大圖形轉其他點數方法')
  return {'area':str(total),'unit':'平方公分'}
 if mode=='area-half':
  for k in ['sameCells','exactHalves','noOverlap']:yes(d[k])
  enum(d['cellUnit'],['1平方公分']);full=integer(d['fullCells'],0,100);halves=integer(d['halfCells'],0,200);area=F(full)+F(halves,2)
  if area>100:raise Route('本包先核百格板內區域，較大面積轉其他格板方法')
  return {'area':str(area),'wholeUnits':full+halves//2,'halfUnitLeft':bool(halves%2),'unit':'平方公分'}
 if mode in ['quad-features','quad-turn']:
  xs,rr,a=quad(d)
  if mode=='quad-turn':
   yes(d['rotationOnly']);shift=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 Invalid('線段需兩端已確認位置')
  ends=[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 Need('兩端雖在圓周，是否通過圓心尚未確認')
   else:through=False
  if type(through)is not bool:raise Invalid('是否過心需真偽值')
  if 'center'in ends and not through:raise Need('端點在圓心卻記不過圓心，觀察矛盾，需核對')
  if ends==['center','center']:raise 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=q(d['givenLength'],True);enum(d['unit'],['公分']);role=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':
  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 Invalid('分片與操作紀錄清單不符本有限流程')
  orig=[pid(x)for x in orig];used=[pid(x)for x in used]
  if len(set(orig))!=len(orig):raise Need('原片標記重複，先核對紀錄')
  if set(used)-set(orig):raise Need('重組紀錄出現未列原片，先核對原材料')
  for x in acts:enum(x,['move','turn','flip','stretch','cut-more'])
  ov=enum(d['overlap'],['none-recorded','present-recorded','not-observed']);each=collections.Counter(used)==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}
 enum(d['observationSource'],['learner-operation-log','teacher-operation-log'])
 if type(d['layoutsDifferentRecorded'])is not bool:raise Invalid('不同排列是否有紀錄需真偽值')
 aa,bb=trial(d['trialA']),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 derived(x):
 if type(x)is int and abs(x)<10**64:return F(x)
 if type(x)is str and len(x)<=132 and re.fullmatch(r'-?[0-9]{1,64}(?:/[1-9][0-9]{0,63}|\.[0-9]{1,64})?',x,re.ASCII):return F(x)
 raise Invalid('答案數量需有界精確數')
def equivalent(p,a,key=''):
 if type(a)is dict:return type(p)is dict and set(p)==set(a)and all(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(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 derived(p)==derived(a)
  except(Invalid,ValueError,ZeroDivisionError,TypeError):return False
 return type(p)is type(a)and p==a

def missing_required(mode,d):
 required=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 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 SUBTYPES or type(d)is not dict:return out('block',r='非本有限文字/活動引導方法')
 mode=SUBTYPES[s];required=REQ[mode]
 if 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=compute(mode,d)
 except Need as e:return out('confirm',r=str(e))
 except(Route,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 equivalent(d['proposal'],a):return out('reject',a,'錯提案不改已確認觀察；不給學生掌握程度分數')
 return out('pass',a,'只核已提供條件/紀錄；不代表實物操作或OCR已驗證')

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,'routeCases':len(p['cases']),'passed':True}))
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:check()
