import json,pathlib,sys,re,itertools,functools
from fractions import Fraction as F
PACK='grade7-geometry-symbols'
SUBTYPES=['s71-object-symbols', 's71-angle-symbols', 's71-triangle-symbols']
REQ={
's71-object-symbols':['labels','endpointCount','extensionDirections','singlePointConfirmed'],
's71-angle-symbols':['vertex','armA','armB','nonstraightAngleConfirmed'],
's71-triangle-symbols':['vertices','triangleConfirmed'],
's72-height-views':['heights','bottomStackedConfirmed','sameUnitCubesConfirmed','orientationConfirmed'],
's72-view-range':['frontHeights','leftHeights','topOccupied','bottomStackedConfirmed','sameUnitCubesConfirmed','orientationConfirmed'],
's73-perpendicular-symbol':['lineA','lineB','angleDegrees','intersectionConfirmed'],
's73-perpendicular-bisector':['segmentLength','firstPart','secondPart','intersectionAngle','intersectionOnSegmentConfirmed','unit'],
's73-point-line-distance':['perpendicularLength','perpendicularFootConfirmed','otherSegments','unit'],
's74-corresponding-measures':['measureKind','originalMeasure','originalLabel','pairedLabel','correspondenceConfirmed','unit'],
's74-axis-point-relations':['pointOnAxis','pointToAxis','pairConfirmed','unit'],
's75-basic-axis-count':['shape','specialCase','axisQuery','nondegenerateConfirmed'],
's75-shape-equal-measures':['relationCase','knownValue','figureConfirmed','roleConfirmed','unit'],
's75-regular-axis-types':['sides','axisQuery','regularConvexConfirmed']}
FLAGS={'singlePointConfirmed','nonstraightAngleConfirmed','triangleConfirmed','bottomStackedConfirmed','sameUnitCubesConfirmed','orientationConfirmed','intersectionConfirmed','intersectionOnSegmentConfirmed','perpendicularFootConfirmed','correspondenceConfirmed','pointOnAxis','pairConfirmed','nondegenerateConfirmed','figureConfirmed','roleConfirmed','regularConvexConfirmed'}
NUMERIC={'endpointCount','extensionDirections','angleDegrees','axisAngle','midpointDistance','distance','value','eachHalf','pairDistance','axisCount','vertexToVertexAxes','vertexToEdgeAxes','edgeToEdgeAxes','requestedAxisCount','cubeCount','minCubeCount','maxCubeCount','configurationCount'}
def num(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)<=64 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**6 or q.denominator>10000):raise ValueError('超出原量有限域')
 return q
def nstr(v):return str(v)
def nat(v,lo,hi):
 if type(v)is not int or not lo<=v<=hi:raise ValueError('整數或範圍不符')
 return v
def enum(v,allowed):
 if type(v)is not str or len(v)>80 or v not in allowed:raise ValueError('種類不符')
 return v
def label(v):
 if type(v)is not str or not re.fullmatch('[A-Z]',v):raise ValueError('點名須單一大寫英文字母')
 return v
def missing(v,depth=0):
 if v is None:return True
 # Legal arrays have at most two list layers (matrix -> row -> cell).
 # Deeper malformed structures fall through to the existing typed guards.
 if depth<2 and type(v)is list and len(v)<=27:return any(missing(x,depth+1)for x in v)
 return False
def unit(v):return enum(v,['cm','m'])
def positive(v):
 x=num(v)
 if x<=0:raise ValueError('須為正量')
 return x
def grid(v,hi):
 if type(v)is not list or not 1<=len(v)<=3 or any(type(row)is not list or not 1<=len(row)<=3 for row in v)or len({len(row)for row in v})!=1:raise ValueError('只限1到3列欄規則表')
 return [[nat(x,0,hi)for x in row]for row in v]
@functools.lru_cache(maxsize=512)
def enumerate_stacks(front,left,top):
 nr,nc=len(left),len(front);positions=[(i,j)for i in range(nr)for j in range(nc)if top[i][j]];choices=[range(1,min(left[i],front[j])+1)for i,j in positions];counts=[]
 for heights in itertools.product(*choices):
  g=[[0]*nc for _ in range(nr)]
  for (i,j),h in zip(positions,heights):g[i][j]=h
  if tuple(max(g[i][j]for i in range(nr))for j in range(nc))!=front:continue
  if tuple(max(row)for row in g)!=left:continue
  counts.append(sum(heights))
 return tuple(sorted(counts))
class Need(Exception):pass

def compute(s,r):
 for k in FLAGS&set(r):
  if type(r[k])is not bool:raise ValueError('確認旗標需真假')
 if any(not r[k]for k in FLAGS&set(r)if k not in ['singlePointConfirmed','pointOnAxis']):raise Need('先核外部幾何條件')
 if s=='s71-object-symbols':
  a=r['labels'];e=nat(r['endpointCount'],0,2);x=nat(r['extensionDirections'],0,2)
  if type(a)is not list or not 1<=len(a)<=2:raise ValueError('點名表不符')
  a=[label(z)for z in a]
  if len(set(a))!=len(a):raise ValueError('兩相異點不能同名')
  if r['singlePointConfirmed']:
   if (e,x,len(a))!=(0,0,1):raise Need('單點紀錄與端點延伸矛盾')
   kind='point';notation=a[0]
  else:
   kind={(0,2):'line',(1,1):'ray',(2,0):'segment'}.get((e,x))
   if kind is None or len(a)!=2:raise Need('端點與延伸條件需核對')
   notation={'line':'直線','ray':'射線','segment':'線段'}[kind]+''.join(a)
  formal=a[0]if kind=='point'else {'line':r'\overleftrightarrow','segment':r'\overline','ray':r'\overrightarrow'}[kind]+'{'+''.join(a)+'}'
  return dict(objectKind=kind,notation=notation,formalSymbol=formal,endpointCount=e,extensionDirections=x)
 if s=='s71-angle-symbols':
  v,a,b=[label(r[k])for k in ['vertex','armA','armB']]
  if len({v,a,b})!=3:raise ValueError('角三點須相異')
  return dict(vertex=v,notation='∠'+a+v+b)
 if s=='s71-triangle-symbols':
  a=r['vertices']
  if type(a)is not list or len(a)!=3:raise ValueError('三頂點')
  a=[label(v)for v in a]
  if len(set(a))!=3:raise ValueError('三頂點須相異')
  return dict(notation='△'+''.join(a),vertexSet=sorted(a))
 if s=='s72-height-views':
  h=grid(r['heights'],3)
  if not any(any(row)for row in h):raise Need('空配置不是本題已確認立體')
  return dict(frontHeights=[max(row[j]for row in h)for j in range(len(h[0]))],leftHeights=[max(row)for row in h],topOccupied=[[int(v>0)for v in row]for row in h],cubeCount=sum(map(sum,h)))
 if s=='s72-view-range':
  front,left=r['frontHeights'],r['leftHeights'];top=grid(r['topOccupied'],1)
  if type(front)is not list or type(left)is not list or not 1<=len(front)<=3 or not 1<=len(left)<=3:raise ValueError('視圖列欄不符')
  front=[nat(x,0,3)for x in front];left=[nat(x,0,3)for x in left]
  if len(top)!=len(left)or len(top[0])!=len(front):raise Need('三視圖同方向列欄不一致')
  if not any(front)or not any(left):raise Need('空視圖或相互矛盾，回查原資料')
  counts=enumerate_stacks(tuple(front),tuple(left),tuple(tuple(row)for row in top))
  if not counts:raise Need('沒有符合三份已確認紀錄的自底堆疊，回查原視圖與額外堆疊條件')
  return dict(configurationCount=len(counts),possibleCubeCounts=sorted(set(counts)),minCubeCount=min(counts),maxCubeCount=max(counts),cubeCountUnique=min(counts)==max(counts))
 if s=='s73-perpendicular-symbol':
  a=label(r['lineA']);b=label(r['lineB']);ang=num(r['angleDegrees'])
  if a==b or not 0<ang<180:raise ValueError('不同相交直線與非平退角')
  return dict(isPerpendicular=ang==90,notation=a+('⊥'if ang==90 else'不垂直')+b)
 if s=='s73-perpendicular-bisector':
  length=positive(r['segmentLength']);a=num(r['firstPart']);b=num(r['secondPart']);angle=num(r['intersectionAngle']);u=unit(r['unit'])
  if a<0 or b<0 or not 0<angle<180:raise ValueError('分段或交角不符')
  if a+b!=length:raise Need('兩分段和不等原線段，先核原量')
  mid=a==b;perp=angle==90
  return dict(passesMidpoint=mid,isPerpendicular=perp,isPerpendicularBisector=mid and perp,midpointDistance=nstr(length/2),unit=u)
 if s=='s73-point-line-distance':
  d=num(r['perpendicularLength']);other=r['otherSegments'];u=unit(r['unit'])
  if d<0 or type(other)is not list or len(other)>6:raise ValueError('距離或候選紀錄不符')
  other=[num(z)for z in other]
  if any(z<d for z in other):raise Need('已知垂足段卻有更短到直線段，原紀錄矛盾先核')
  return dict(distance=nstr(d),unit=u)
 if s=='s74-corresponding-measures':
  kind=enum(r['measureKind'],['segment','angle']);v=positive(r['originalMeasure']);a=r['originalLabel'];b=r['pairedLabel'];u=enum(r['unit'],['cm','m','degree']);n=2 if kind=='segment'else 3
  if any(type(t)is not str or len(t)!=n or len(set(t))!=n or any(not re.fullmatch('[A-Z]',x)for x in t)for t in [a,b]):raise ValueError('原與對應角色點名不符')
  if (kind=='angle'and(not v<180 or u!='degree'))or(kind=='segment'and u=='degree'):raise Need('量的角色與單位需一致')
  return dict(value=nstr(v),unit=u,relation='對稱線段等長'if kind=='segment'else'對稱角相等')
 if s=='s74-axis-point-relations':
  d=num(r['pointToAxis']);u=unit(r['unit']);on=r['pointOnAxis']
  if d<0:raise ValueError('距離不負')
  if on!=(d==0):raise Need('軸上紀錄與距離矛盾')
  return dict(eachHalf=nstr(d),pairDistance=nstr(d+d),pairCoincides=on,axisAngle=None if on else 90,unit=u)
 if s=='s75-basic-axis-count':
  shape=enum(r['shape'],['isosceles-triangle','square','rhombus','kite']);special=r['specialCase']
  choices={'isosceles-triangle':{'equilateral':3,'non-equilateral':1},'square':{'square':4},'rhombus':{'square':4,'non-square':2},'kite':{'proper-kite':1,'rhombus-nonsquare':2,'square':4}}
  special=enum(special,choices[shape]);n=choices[shape][special]
  desc=('三個頂點各到對邊中點'if shape=='isosceles-triangle'and n==3 else'頂角到不等邊中點'if shape=='isosceles-triangle'else'兩條對角線與兩組對邊中點連線'if n==4 else'兩條對角線'if n==2 else'兩對等長鄰邊各自相接的頂點連線')
  query=enum(r['axisQuery'],['all','diagonal','opposite-midpoints','vertex-midpoint'])
  istri=shape=='isosceles-triangle'
  selected=n if query=='all'else n if istri and query=='vertex-midpoint'else 0 if istri else 2 if query=='diagonal'and n>=2 else 1 if query=='diagonal'and n==1 else 2 if query=='opposite-midpoints'and n==4 else 0
  return dict(axisCount=n,requestedAxisCount=selected,axisDescription=desc)
 if s=='s75-shape-equal-measures':
  case=enum(r['relationCase'],['isosceles-equal-sides','rhombus-opposite-angles','kite-symmetric-angles','square-diagonal-halves']);v=positive(r['knownValue']);u=enum(r['unit'],['cm','m','degree'])
  angular='angles'in case
  if angular!=(u=='degree')or angular and v>=180:raise Need('角與長度單位/範圍要核對')
  ans=v/2 if case=='square-diagonal-halves'else v
  why={'isosceles-equal-sides':'等腰三角形兩腰相等','rhombus-opposite-angles':'菱形對角相等','kite-symmetric-angles':'箏形對稱軸兩側相對應角相等','square-diagonal-halves':'正方形兩對角線互相平分'}[case]
  return dict(value=nstr(ans),unit=u,relation=why)
 if s=='s75-regular-axis-types':
  n=nat(r['sides'],3,12);query=enum(r['axisQuery'],['all','vertex-vertex','vertex-edge','edge-edge']);vv=n//2 if n%2==0 else 0;ve=n if n%2 else 0;ee=vv
  return dict(axisCount=n,vertexToVertexAxes=vv,vertexToEdgeAxes=ve,edgeToEdgeAxes=ee,requestedAxisCount={'all':n,'vertex-vertex':vv,'vertex-edge':ve,'edge-edge':ee}[query])
 raise ValueError('unknown method')
def equivalent(p,a,s):
 if type(p)is not dict or set(p)!=set(a):return False
 try:
  for k,v in a.items():
   if k=='formalSymbol':
    if type(p[k])is not str:return False
    valid={v}
    if a['objectKind']in ['line','segment']:valid.add(v[:-3]+v[-3:-1][::-1]+v[-1])
    if p[k]not in valid:return False
   elif k=='notation':
    if type(p[k])is not str:return False
    valid={v}
    if s=='s71-object-symbols'and a['objectKind']in ['line','segment']:valid.add(v[:-2]+v[-2:][::-1])
    if s=='s71-angle-symbols':valid.add(v[0]+v[1:][::-1])
    if s=='s71-triangle-symbols':valid={'△'+''.join(t)for t in itertools.permutations(a['vertexSet'])}
    if s=='s73-perpendicular-symbol':valid.add(v[-1]+v[1:-1]+v[0])
    if p[k]not in valid:return False
   elif type(v)is bool:
    if type(p[k])is not bool or p[k]!=v:return False
   elif v is None:
    if p[k]is not None:return False
   elif k in NUMERIC:
    if num(p[k],True)!=num(v,True):return False
   elif k=='possibleCubeCounts':
    if type(p[k])is not list or len(p[k])!=len(v)or sorted(num(z,True)for z in p[k])!=list(map(F,v)):return False
   elif k in ['frontHeights','leftHeights']:
    if type(p[k])is not list or len(p[k])!=len(v)or any(num(x,True)!=y for x,y in zip(p[k],v)):return False
   elif k=='topOccupied':
    if type(p[k])is not list or len(p[k])!=len(v):return False
    if any(type(x)is not list or len(x)!=len(y)or any(num(xx,True)!=yy for xx,yy in zip(x,y))for x,y in zip(p[k],v)):return False
   elif k=='vertexSet':
    if type(p[k])is not list or len(p[k])!=3 or any(type(z)is not str for z in p[k])or sorted(p[k])!=v:return False
   elif type(p[k])is not type(v)or p[k]!=v:return False
  return True
 except(ValueError,TypeError,KeyError,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='不在此有限文字方法')
 req=REQ[s]+['factsConfirmed','task']
 if any(k not in r or missing(r[k])for k in req):return out('confirm',why='先補原題缺量/角色/原觀察，不猜圖')
 if set(r)-set(req)-{'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 Need as e:return out('confirm',why=str(e))
 except(ValueError,TypeError,KeyError,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,s):return out('reject',a,'只指出錯提案，保留原題正解與外部觀察限制')
 return out('pass',a,'僅核已確認文字幾何條件，不驗圖像、實物或學生能力')
if __name__=='__main__':
 if len(sys.argv)>1 and sys.argv[1]=='evaluate':
  try:
   raw=sys.stdin.read(65537)
   if len(raw)>65536:raise ValueError('request too large')
   x=json.loads(raw)
   if type(x)is not dict:raise ValueError('request must be an object')
   result=evaluate(x.get('subtypeId'),x.get('input'))
  except(ValueError,TypeError,RecursionError,OverflowError):
   result=dict(decision='block',answer=None,reason='請求JSON格式、大小或巢狀深度超出此有限文字方法')
  print(json.dumps(result,ensure_ascii=False))
 else:
  d=json.loads(pathlib.Path(__file__).with_name(PACK+'.json').read_text())
  for c in d['cases']:
   a=evaluate(c['subtypeId'],c['input']);assert(a['decision'],a['answer'])==(c['expectedDecision'],c['expectedAnswer']),c['id']
  print('PASS',len(d['cases']),'finite geometry text contracts')
