import json,pathlib,re,sys
from fractions import Fraction
PACK='grade5-symmetry-methods'
SUBTYPES={'s54-symmetry-relation': 'symmetry-relation', 's54-symmetry-observations': 'symmetry-observations', 's54-symmetry-completion-guidance': 'symmetry-completion-guidance'}
REQ={'angle-sum':['polygon','knownAngles','simpleBoundaryConfirmed'],'triangle-sides':['lengths','unit'],'parallelogram':['angleA','sideAB','sideBC','parallelogramConfirmed','unit'],'sector-definition':['circleRadius','straightLengths','straightCount','arcCount','centerIdentified','bothSegmentsReachCenter','endpointsOnCircle','sameCircle','selectedRegionConfirmed'],'sector-fraction':['direction','circleRadius','centerIdentified','radialBoundariesConfirmed','selectedRegionConfirmed'],'sector-drawing-guidance':['radiusCm','targetDegrees','selectedSweep','actions','observationSource'],'symmetry-relation':['quantity','axisOrientation','axisPosition','wholeSymmetryConfirmed'],'symmetry-observations':['shape','observations','wholeBoundaryChecked','originalShapePreserved','distinctCandidateAxesConfirmed'],'symmetry-completion-guidance':['axisOrientation','axisPosition','givenPoints','unitGridConfirmed','actions','observationSource']}
ACTIONS={'sector-drawing-guidance':['mark-center','draw-circle','draw-start-radius','mark-directed-angle','join-end-radius','identify-selected-arc','check-radius-and-angle'],'symmetry-completion-guidance':['confirm-axis','count-perpendicular-gaps','mark-partner-points','join-corresponding-edges','check-fold-match']}
LABEL={'mark-center':'標定圓心','draw-circle':'依半徑畫圓','draw-start-radius':'畫始邊半徑','mark-directed-angle':'依旋向標指定角','join-end-radius':'連終邊半徑','identify-selected-arc':'標明指定大小弧','check-radius-and-angle':'現場核對半徑與圓心角','confirm-axis':'確認對稱軸','count-perpendicular-gaps':'沿垂直於對稱軸的方向朝軸數格','mark-partner-points':'在軸另一側標等距點','join-corresponding-edges':'依原順序連對應邊','check-fold-match':'現場摺合核對整體'}
def out(d,a=None,r=''):return dict(decision=d,answer=a,reason=r)
def integer(v,lo=0,hi=360):
 if type(v)is not int or not lo<=v<=hi:raise ValueError()
 return v
def enum(v,values):
 if type(v)is not str or v not in values:raise ValueError()
 return v
def flag(v):
 if type(v)is not bool:raise ValueError()
 return v
def numeric(v):
 if type(v)is int and abs(v)<10**80:return Fraction(v)
 if type(v)is not str or not 1<=len(v)<=80 or not re.fullmatch(r'[+-]?(?:[0-9]{1,80}(?:/[0-9]{1,80}|\.[0-9]{0,80})?|\.[0-9]{1,80})',v,re.ASCII):raise ValueError()
 if '/'in v and not any(c!='0'for c in v.split('/')[1]):raise ValueError()
 return Fraction(v)
def eq(p,a,key=''):
 if type(a)is bool:return type(p)is bool and p==a
 if type(a)is int:
  try:return numeric(p)==a
  except(ValueError,TypeError,ZeroDivisionError):return False
 if type(a)is str:
  if key in ('fraction',):
   try:return numeric(p)==numeric(a)
   except(ValueError,TypeError,ZeroDivisionError):return False
  return type(p)is str and p==a
 if type(a)is dict:return type(p)is dict and set(p)==set(a)and all(eq(p[k],a[k],k)for k in a)
 if type(a)is list:
  if type(p)is not list or len(p)!=len(a):return False
  if key in ('confirmedAxes','rejectedAxes'):return all(type(v)is str for v in p)and len(set(p))==len(p)and set(p)==set(a)
  return all(eq(x,y)for x,y in zip(p,a))
 return p is None and a is None

def extra(mode,r):
 if mode=='sector-fraction':return ['angleDegrees']if r.get('direction')=='angle-to-fraction'else['numerator','denominator']if r.get('direction')=='fraction-to-angle'else[]
 if mode=='symmetry-relation':return ['point']if r.get('quantity')=='point'else['knownValue','unit']if r.get('quantity')in ('side','angle')else[]
 return []
def point(p):
 if type(p)is not dict or set(p)!= {'column','row'}:raise ValueError()
 return {'column':integer(p['column'],1,60),'row':integer(p['row'],1,60)}
def reflected(p,o,a):
 q=point(p);k='column'if o=='vertical'else'row';q[k]=2*a-q[k]
 if not 1<=q[k]<=60:raise ValueError()
 return q

def evaluate(subtype_id,r):
 if type(subtype_id)is not str or subtype_id not in SUBTYPES or type(r)is not dict:return out('block',r='非本有限方法')
 mode=SUBTYPES[subtype_id];required=REQ[mode]+extra(mode,r)
 if r.get('factsConfirmed')is not True or any(k not in r or r[k]is None for k in required):return out('confirm',r='先確認缺少的原條件，不自行補圖或數值')
 for k in ['knownAngles','lengths','straightLengths','actions','observations','givenPoints']:
  if k in r and type(r[k])is list and len(r[k])<=12 and any(v is None for v in r[k]):return out('confirm',r='必要列表有缺項，先回原題確認')
 if mode in ('symmetry-relation','symmetry-completion-guidance'):
  ps=[r['point']]if mode=='symmetry-relation'and r.get('quantity')=='point'else r.get('givenPoints',[])
  if type(ps)is list and len(ps)<=8 and any(type(p)is dict and any(k not in p or p[k]is None for k in ['column','row'])for p in ps):return out('confirm',r='格紙原點位置缺項，先確認')
 if mode=='symmetry-observations'and type(r['observations'])is list and len(r['observations'])<=8 and any(type(p)is dict and any(k not in p or p[k]is None for k in ['axisLabel','orientation','fullOverlap'])for p in r['observations']):return out('confirm',r='摺合觀察缺項，先補完整原紀錄')
 if set(r)-set(required)-{'factsConfirmed','task','proposal'}or type(r.get('task'))is not str or r['task']not in ('solve','check_proposal'):return out('block',r='欄位或任務不合')
 try:
  if mode=='angle-sum':
   poly=enum(r['polygon'],['triangle','quadrilateral']);n=3 if poly=='triangle'else 4;xs=r['knownAngles']
   if not flag(r['simpleBoundaryConfirmed']):return out('confirm',r='先確認封閉不交叉的三邊或四邊圖形')
   if type(xs)is not list or len(xs)!=n-1:raise ValueError()
   xs=[integer(x,1,179 if n==3 else 359)for x in xs];total=180 if n==3 else 360;remaining=total-sum(xs);possible=0<remaining<(180 if n==3 else 360)
   ans={'possible':possible,'missingDegrees':remaining if possible else None,'totalDegrees':total}
  elif mode=='triangle-sides':
   xs=r['lengths'];enum(r['unit'],['cm'])
   if type(xs)is not list or len(xs)!=3:raise ValueError()
   xs=[integer(v,1,100)for v in xs];ans={'canFormTriangle':2*max(xs)<sum(xs),'unit':'cm'}
  elif mode=='parallelogram':
   if not flag(r['parallelogramConfirmed']):return out('confirm',r='先確認兩組對邊平行，不能從外觀或一組等邊猜')
   a=integer(r['angleA'],1,179);b=integer(r['sideAB'],1,100);c=integer(r['sideBC'],1,100);enum(r['unit'],['cm']);ans={'anglesABCD':[a,180-a,a,180-a],'sidesABCD':[b,c,b,c],'angleUnit':'degree','lengthUnit':'cm'}
  elif mode=='sector-definition':
   radius=integer(r['circleRadius'],1,100);n=integer(r['straightCount'],0,4);arcs=integer(r['arcCount'],0,3);xs=r['straightLengths']
   if type(xs)is not list or len(xs)!=n:raise ValueError()
   xs=[integer(v,1,100)for v in xs]
   if not flag(r['centerIdentified'])or not flag(r['selectedRegionConfirmed']):return out('confirm',r='先標原圓心與所取區域，不猜扇形')
   same=flag(r['sameCircle']);center=flag(r['bothSegmentsReachCenter']);ends=flag(r['endpointsOnCircle'])
   if n==2 and same and center and ends and any(v!=radius for v in xs):raise ValueError()
   yes=n==2 and arcs==1 and same and center and ends and xs==[radius,radius];ans={'isSector':yes,'boundaryReason':'同圓兩條半徑與一段指定弧'if yes else'邊界不是同圓兩條半徑與一段弧'}
  elif mode=='sector-fraction':
   integer(r['circleRadius'],1,100)
   if not all(flag(r[k])for k in ['centerIdentified','radialBoundariesConfirmed','selectedRegionConfirmed']):return out('confirm',r='先確認圓心、兩半徑與指定大小扇形，不能拿小角替大扇形')
   direction=enum(r['direction'],['angle-to-fraction','fraction-to-angle'])
   if direction=='angle-to-fraction':a=integer(r['angleDegrees'],1,360);f=Fraction(a,360)
   else:
    num=integer(r['numerator'],1,360);den=integer(r['denominator'],1,360)
    if num>den:raise ValueError()
    f=Fraction(num,den);aa=360*f
    if aa.denominator!=1:raise ValueError()
    a=aa.numerator
   ans={'angleDegrees':a,'fraction':str(f),'largerThanSemicircle':a>180,'regionKind':'whole-circle'if a==360 else'proper-sector'}
  elif mode in ('sector-drawing-guidance','symmetry-completion-guidance'):
   acts=r['actions'];allowed=ACTIONS[mode]
   if type(acts)is not list or len(acts)>12:raise ValueError()
   acts=[enum(v,allowed)for v in acts];enum(r['observationSource'],['learner-operation-log','teacher-operation-log'])
   if mode=='sector-drawing-guidance':
    radius=integer(r['radiusCm'],1,30);a=integer(r['targetDegrees'],1,359);direction=enum(r['selectedSweep'],['clockwise','counterclockwise']);target='sector';label='順時針'if direction=='clockwise'else'逆時針';plan=[f'標圓心，畫半徑{radius}公分的圓與始邊半徑。',f'從始邊按{label}取{a}度；'+(f'大於180度，先標180度再沿同向補{a-180}度，不改取較小扇形。'if a>180 else'以量角器中心對圓心，0刻度對始邊，沿指定方向標角。'),'連終點至圓心，標清所取的弧；現場量兩半徑及指定圓心角，操作紀錄不代表已畫對。']
   else:
    o=enum(r['axisOrientation'],['vertical','horizontal']);a=integer(r['axisPosition'],1,60);ps=r['givenPoints']
    if not flag(r['unitGridConfirmed']):return out('confirm',r='先確認同大方格與軸位置，不從外觀猜距離')
    if type(ps)is not list or not 1<=len(ps)<=6:raise ValueError()
    ps=[point(x)for x in ps];qs=[reflected(x,o,a)for x in ps];target='line-symmetric-completion';k='column'if o=='vertical'else'row';plan=[f'確認'+('垂直軸在第'if o=='vertical'else'水平軸在第')+str(a)+('欄線。'if o=='vertical'else'排線。'),'按原順序處理各點：'+ '；'.join(f'原點第{x["column"]}欄第{x["row"]}排，'+('此點在軸上，相距0格，原位保留'if x[k]==a else f'沿垂直於對稱軸的方向（{"左右"if o=="vertical"else"上下"}），朝軸數{abs(x[k]-a)}格，再在軸另一側標同樣格數')for x in ps)+'。','依原有邊的順序連對應點；若只給點而未給邊順序，先確認連線方式。保留原紙不拉伸，再現場沿軸摺合核對整體。']
   match=acts==allowed;nextStep='紀錄已含必要步驟，仍需現場核對成品；不判定掌握'if match else '下一步：'+LABEL[next((x for x,y in zip(allowed,acts)if x!=y),allowed[len(acts)]if len(acts)<len(allowed)else allowed[0])]
   ans={'targetType':target,'requiredActions':allowed[:],'recordMatchesSteps':match,'plan':plan,'physicalVerified':False,'nextStep':nextStep}
  elif mode=='symmetry-relation':
   o=enum(r['axisOrientation'],['vertical','horizontal']);a=integer(r['axisPosition'],1,60);q=enum(r['quantity'],['point','side','angle'])
   if not flag(r['wholeSymmetryConfirmed']):return out('confirm',r='先確認整體可沿指定軸重合，不從單一對點猜整體對稱')
   if q=='point':ans={'quantity':'point','partnerPoint':reflected(r['point'],o,a)}
   else:
    v=integer(r['knownValue'],1,100 if q=='side'else 359);u=enum(r['unit'],['cm']if q=='side'else['degree']);ans={'quantity':q,'partnerValue':v,'unit':u}
  else:
   shape=enum(r['shape'],['equilateral-triangle','isosceles-triangle','square','rectangle','rhombus','two-adjacent-equal-pairs','isosceles-trapezoid','other']);xs=r['observations']
   if not flag(r['wholeBoundaryChecked'])or not flag(r['originalShapePreserved'])or not flag(r['distinctCandidateAxesConfirmed']):return out('confirm',r='需原紙片與整體摺合紀錄，只對上一角不夠')
   if type(xs)is not list or not 1<=len(xs)<=6:raise ValueError()
   yes=[];no=[];labels=[]
   for x in xs:
    if type(x)is not dict or set(x)!= {'axisLabel','orientation','fullOverlap'}:raise ValueError()
    label=x['axisLabel'];enum(x['orientation'],['vertical','horizontal','operation-fold'])
    if type(label)is not str or not 1<=len(label)<=16:raise ValueError()
    labels.append(label);(yes if flag(x['fullOverlap'])else no).append(label)
   if len(set(labels))!=len(labels):raise ValueError()
   limit={'equilateral-triangle':3,'isosceles-triangle':1,'square':4,'rectangle':2,'rhombus':2,'two-adjacent-equal-pairs':1,'isosceles-trapezoid':1,'other':6}[shape]
   if len(yes)>limit:raise ValueError()
   positive=[x['orientation']for x in xs if x['fullOverlap']and x['orientation']!='operation-fold']
   if len(positive)!=len(set(positive)):raise ValueError()
   if shape=='equilateral-triangle'and {'vertical','horizontal'}<=set(positive):return out('block',r='已確認正三角形與互相垂直的兩條整體摺合紀錄矛盾，請回原紙片核對；這是資料一致性守衛，不要求學生證明軸夾角')
   ans={'confirmedAxes':yes,'rejectedAxes':no,'examinedCount':len(xs),'allPossibleAxesAccountedFor':shape!='other'and len(yes)==limit}
 except(ValueError,KeyError,TypeError,ZeroDivisionError,OverflowError):return out('block',r='有限資料或型別矛盾，不以外觀補條件')
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',r='先補待核對提案')
  return out('pass'if eq(r['proposal'],ans)else'reject',ans,'只核文字方法與已確認紀錄，不驗實物或學生掌握')
 return out('pass',ans,'只核文字方法與已確認紀錄，不驗實物或學生掌握')
if __name__=='__main__':
 p=pathlib.Path(__file__).with_name(PACK+'.json');d=json.load(open(p));bad=[]
 for c in d['cases']:
  r=evaluate(c['subtypeId'],c['input'])
  if r['decision']!=c['expectedDecision']or r['answer']!=c['expectedAnswer']:bad.append(c['id'])
 print(json.dumps(dict(ok=not bad,cases=len(d['cases']),failed=bad),ensure_ascii=False));sys.exit(bool(bad))
