#!/usr/bin/env python3
"""Finite confirmed-text geometry, not OCR or a physical construction assessor."""
import json,sys,re,math,pathlib,copy
from fractions import Fraction
TYPES={'s812-angle-bisector-reason','s812-construction-guidance','s812-perpendicular-bisector-reason'}
REQ={
's88-isosceles':['mode','angle'], 's88-side-relations':['a','b','c'], 's88-exterior':['remoteA','remoteB'],
's89-edges-angles':['a','b','angleA'], 's89-diagonal-halves':['ac','bd','crossAngle'],
's810-rectangle-diagonals':['shape','ac'], 's810-kite-diagonals':['ao','co','bo','do','axisACConfirmed','interiorIntersectionConfirmed'],
's811-isosceles-trapezoid':['top','bottom','lowerAngle','equalLegsConfirmed','parallelBasesConfirmed'],
's811-midsegment':['top','bottom','legMidpointsConfirmed','parallelBasesConfirmed'],
's812-perpendicular-bisector-reason':['ab','radiusA','radiusB','oppositeIntersectionsConfirmed'],
's812-angle-bisector-reason':['angle','oa','ob','pa','pb','insideConfirmed','distinctFromVertexConfirmed'],
's812-construction-guidance':['targetType','actions','observationSource','conditionsConfirmed'],
'g81-distance':['ax','ay','bx','by','xUnit','yUnit','xScale','yScale','perpendicularAxesConfirmed']}

ACT={
'copy-segment':['在射線上指定起點C','圓規開口取原線段AB','以C為圓心畫弧交射線於D','記錄CD與AB等長並請老師核對'],
'copy-circle':['指定新圓心P','圓規開口取原圓已確認半徑','保持開口以P為圓心畫圓','記錄新圓心與等半徑並請老師核對'],
'copy-angle':['從新頂點作起始射線','同半徑在原角與新頂點畫弧','圓規取原角弧上兩交點距離','把該距離移到新弧指定一側並連新頂點','記錄兩角對應弦與半徑相等並請老師核對'],
'copy-triangle':['依原AB長作新底邊CD','以C為圓心取原AC長畫弧','以D為圓心取原BC長畫弧','取指定一側交點E連CE與DE','記錄三邊對應等長並請老師核對'],
'perpendicular-bisector':['確認兩端點A與B不同','取同半徑且大於AB一半','以A與B畫弧取線段兩側相異交點P與Q','連接PQ並記錄兩交點到A與B等距','請老師現場核對中垂線'],
'angle-bisector':['確認非退化角的頂點O與兩射線','以O為圓心同弧取兩邊點A與B','以A與B為圓心用OA長畫弧取角內且非O交點P','連OP並記錄兩小三角形三邊對應相等','請老師現場核對內角平分線'],
'parallel-line':['確認P在線l外','以P為圓心取足夠半徑畫弧交l於相異A與B','以A與B為圓心用AP長畫弧另取異於P的交點Q','連PQ得到過P垂直l的直線m','以P為m上點再作m的垂線並請老師核對與l平行'],
'perpendicular-line':['確認指定點P在直線l上','以P為圓心畫弧交l於兩側A與B','以A與B為圓心取大於AB一半的同半徑畫弧得線外交點Q','連PQ並記錄PA等於PB及QA等於QB','請老師現場核對過P的垂線']}

class Ask(Exception):pass
class Bound(Exception):pass
def shape(v,depth=0,budget=None):
 if budget is None:budget=[0]
 budget[0]+=1
 if budget[0]>512 or depth>5:raise Bound('結構超出有限範圍')
 if type(v)is dict:
  if len(v)>24 or any(type(k)is not str or len(k)>64 for k in v):raise Bound('物件欄位不符')
  for x in v.values():shape(x,depth+1,budget)
 elif type(v)is list:
  if len(v)>16:raise Bound('清單過長')
  for x in v:shape(x,depth+1,budget)
 elif type(v)is str:
  if len(v)>96:raise Bound('文字過長')
 elif type(v)is int:
  if abs(v)>10**12:raise Bound('數量過大')
 elif type(v)not in (bool,type(None),float):raise Bound('資料型別不符')
def need(r,k):
 if k not in r or r[k]is None:raise Ask('請補清原題缺少的已知量或幾何關係，不能從外觀看出答案')
 return r[k]
def exact(v):
 if type(v)is int and abs(v)<=10**12:return Fraction(v)
 if type(v)is str and len(v)<=40 and re.fullmatch(r'-?[0-9]{1,12}(?:/[0-9]{1,12}|\.[0-9]{1,8})?',v,re.ASCII):
  if '/'in v and int(v.split('/')[1])==0:raise Bound('分母不能為0')
  q=Fraction(v)
  if abs(q)<=10**12:return q
 raise Bound('數量須用有界整數、分數或有限小數，不讀指數算式')
def raw(v,lo=0,hi=1000,strict=False):
 q=exact(v)
 if not lo<=q<=hi or strict and q==lo:raise Bound('原量超出本型範圍')
 if q.denominator>100:raise Bound('原量分母至多100')
 return q
def integer(v,lo=-100,hi=100):
 if type(v)is not int or not lo<=v<=hi:raise Bound('本型坐標須為範圍內整數')
 return v
def txt(q):return str(q.numerator)if q.denominator==1 else str(q.numerator)+'/'+str(q.denominator)
def flag(r,k,require=True):
 if type(r[k])is not bool:raise Bound('關係確認須為布林')
 if require and not r[k]:raise Ask('請先確認題目明給的幾何關係；不能只憑照片判斷')
 return r[k]
def angle(v):
 q=raw(v,0,180,True)
 if q>=180:raise Bound('本型角須介於0與180度')
 return q
def root(n):
 if n==0:return dict(coefficient='0',radicand=1)
 factor=1;rad=n;p=2
 while p*p<=rad:
  while rad%(p*p)==0:rad//=p*p;factor*=p
  p+=1
 return dict(coefficient=str(factor),radicand=rad)
def compute(s,r):
 if s=='s88-isosceles':
  if r['mode']not in ('apex','base')or type(r['mode'])is not str:raise Bound('角的位置須明確')
  x=angle(r['angle']);ap=x if r['mode']=='apex'else 180-2*x
  if not 0<ap<180:raise Ask('兩底角與頂角無法構成非退化三角形，先核對原題')
  b=(180-ap)/2
  return dict(apex=txt(ap),baseB=txt(b),baseC=txt(b),equilateral=ap==60,unit='度')
 if s=='s88-side-relations':
  a,b,c=[raw(r[k],0,100,True)for k in ('a','b','c')];valid=max(a,b,c)<a+b+c-max(a,b,c)
  groups=[]
  if valid:
   for v in sorted(set((a,b,c)),reverse=True):groups.append('＝'.join(k for k,x in [('A',a),('B',b),('C',c)]if x==v))
  return dict(triangleExists=valid,thirdLower=txt(abs(a-b)),thirdUpper=txt(a+b),endpointsExcluded=True,oppositeAngleOrder='＞'.join(groups)if valid else None,lengthUnit='公分')
 if s=='s88-exterior':
  a,b=angle(r['remoteA']),angle(r['remoteB'])
  if a+b>=180:raise Ask('兩個內對角和需小於180度，請核對原題')
  return dict(interiorAtExtension=txt(180-a-b),exterior=txt(a+b),unit='度')
 if s=='s89-edges-angles':
  a,b=raw(r['a'],0,100,True),raw(r['b'],0,100,True);t=angle(r['angleA'])
  return dict(ab=txt(a),bc=txt(b),cd=txt(a),da=txt(b),angleA=txt(t),angleB=txt(180-t),angleC=txt(t),angleD=txt(180-t),lengthUnit='公分',angleUnit='度')
 if s=='s89-diagonal-halves':
  ac,bd=raw(r['ac'],0,100,True),raw(r['bd'],0,100,True);t=angle(r['crossAngle'])
  return dict(ao=txt(ac/2),co=txt(ac/2),bo=txt(bd/2),do=txt(bd/2),diagonalsEqual=ac==bd,perpendicular=t==90,unit='公分')
 if s=='s810-rectangle-diagonals':
  if type(r['shape'])is not str or r['shape']not in ('rectangle','square'):raise Bound('需確認為長方形或正方形')
  ac=raw(r['ac'],0,100,True)
  return dict(ac=txt(ac),bd=txt(ac),ao=txt(ac/2),bo=txt(ac/2),co=txt(ac/2),do=txt(ac/2),perpendicular=True if r['shape']=='square'else None,unit='公分')
 if s=='s810-kite-diagonals':
  ao,co,bo,do=[raw(r[k],0,100,True)for k in ('ao','co','bo','do')]
  flag(r,'axisACConfirmed');flag(r,'interiorIntersectionConfirmed')
  if bo!=do:raise Ask('已知左右半段不等，與AC為箏形對稱軸矛盾，先核原數據')
  return dict(ac=txt(ao+co),bd=txt(bo+do),acBisectsBD=True,bdBisectsAC=ao==co,perpendicular=True,rhombus=ao==co,square=ao==co==bo,unit='公分')
 if s in ('s811-isosceles-trapezoid','s811-midsegment'):
  top,bottom=raw(r['top'],0,100,True),raw(r['bottom'],0,100,True)
  if top>=bottom:raise Ask('本型指定上底短於下底；相等或相反的條件需先另行確認')
  flag(r,'parallelBasesConfirmed')
  if s=='s811-midsegment':
   flag(r,'legMidpointsConfirmed');return dict(midsegment=txt((top+bottom)/2),parallelToBases=True,unit='公分')
  flag(r,'equalLegsConfirmed');t=angle(r['lowerAngle'])
  if t>=90:raise Ask('此上下底配置的下底角須為銳角，先核對角的位置與底邊')
  return dict(lowerLeft=txt(t),lowerRight=txt(t),upperLeft=txt(180-t),upperRight=txt(180-t),symmetryAxes=1,angleUnit='度')
 if s=='s812-perpendicular-bisector-reason':
  ab,ra,rb=[raw(r[k],0,100,True)for k in ('ab','radiusA','radiusB')]
  if ra!=rb:raise Ask('此推理以等半徑為前提；兩個半徑不同不能直接套用')
  flag(r,'oppositeIntersectionsConfirmed',False)
  if 2*ra<=ab:
   if r['oppositeIntersectionsConfirmed']:raise Ask('半徑條件不容許兩個分居兩側的交點，請核對記錄')
   return dict(status='one-intersection'if 2*ra==ab else'no-intersection',halfAB=None,perpendicularAngle=None,physicalConstructionVerified=False,lengthUnit='公分',angleUnit='度')
  flag(r,'oppositeIntersectionsConfirmed')
  return dict(status='reason-established',halfAB=txt(ab/2),perpendicularAngle='90',physicalConstructionVerified=False,lengthUnit='公分',angleUnit='度')
 if s=='s812-angle-bisector-reason':
  t=angle(r['angle']);oa,ob,pa,pb=[raw(r[k],0,100,True)for k in ('oa','ob','pa','pb')]
  if not oa==ob==pa==pb:raise Ask('本型等距條件有不一致，先核對四條線段的已知長度')
  flag(r,'insideConfirmed');flag(r,'distinctFromVertexConfirmed')
  return dict(leftHalf=txt(t/2),rightHalf=txt(t/2),triangleReason='SSS',physicalConstructionVerified=False,unit='度')
 if s=='s812-construction-guidance':
  if type(r['targetType'])is not str or r['targetType']not in ACT:raise Bound('本型只含明列八種基本作圖')
  if type(r['observationSource'])is not str or r['observationSource']not in ('learner-operation-log','teacher-operation-log'):raise Bound('須為已轉寫的外部操作紀錄')
  flag(r,'conditionsConfirmed');actions=r['actions'];required=ACT[r['targetType']]
  if type(actions)is not list or len(actions)>8:raise Bound('操作紀錄長度不符')
  allowed=set(x for seq in ACT.values()for x in seq)|{'直接用量角器量角','只憑外觀看起來相等','改動圓規開口','只找一個交點就畫中垂線','把角外交點當內角平分點','以直尺量長代替圓規複製'}
  for x in actions:
   if x is None:raise Ask('請補清缺少的一項操作紀錄')
   if type(x)is not str or x not in allowed:raise Bound('操作不在有限紀錄字典')
  n=0
  while n<min(len(actions),len(required))and actions[n]==required[n]:n+=1
  consistent=n==len(actions)and len(actions)<=len(required);complete=consistent and n==len(required)
  return dict(targetType=r['targetType'],requiredActions=required,recordMatchesSteps=complete,plan=required,physicalVerified=False,nextStep='回到現場請老師核對作品與操作'if complete else required[n]if n<len(required)else'移除超出此作圖流程的紀錄並請老師核對')
 if s=='g81-distance':
  ax,ay,bx,by=[integer(r[k])for k in ('ax','ay','bx','by')]
  if any(type(r[k])is not str or r[k]not in ('公分','公尺','公里')for k in ('xUnit','yUnit')):raise Bound('軸單位須為本型明列長度單位')
  xs,ys=raw(r['xScale'],0,10,True),raw(r['yScale'],0,10,True);flag(r,'perpendicularAxesConfirmed')
  if r['xUnit']!=r['yUnit']or xs!=ys:raise Ask('兩軸單位或每格實長不同，先換成一致尺度，不能直接套此型公式')
  dx,dy=bx-ax,by-ay;n=dx*dx+dy*dy;rt=root(n);rt['coefficient']=txt(exact(rt['coefficient'])*xs)
  return dict(dx=dx,dy=dy,squaredCoordinateDistance=n,distance=rt,unit=r['xUnit'])
 raise Bound('未知子型')
def same(v,e):
 if type(e)is dict:
  if type(v)is not dict or set(v)!=set(e):return False
  if set(e)=={'coefficient','radicand'}:
   c=exact(v['coefficient']);n=integer(v['radicand'],0,10**6);ec=exact(e['coefficient'])
   return c>=0 and c*c*n==ec*ec*e['radicand']
  return all(same(v[k],x)for k,x in e.items())
 if type(e)is list:return type(v)is list and len(v)==len(e)and all(same(x,y)for x,y in zip(v,e))
 if type(e)is bool:return type(v)is bool and v==e
 if e is None:return v is None
 if type(e)is int:return exact(v)==e
 if type(e)is str and re.fullmatch(r'-?[0-9]+(?:/[0-9]+)?',e):return exact(v)==exact(e)
 return type(v)is str and v==e
def evaluate(s,r):
 try:
  if type(s)is not str or s not in TYPES:raise Bound('未知子型')
  if type(r)is not dict:raise Bound('原題須為結構化記錄')
  shape(r)
  for k in ['task','confirmed',*REQ[s]]:need(r,k)
  if s=='s812-construction-guidance'and type(r['actions'])is list and len(r['actions'])<=8 and any(x is None for x in r['actions']):raise Ask('請補清缺少的一項操作紀錄')
  if type(r['confirmed'])is not bool:raise Bound('確認值須為布林')
  if not r['confirmed']:raise Ask('先確認題目文字關係')
  if type(r['task'])is not str or r['task']not in ('solve','check_proposal'):raise Bound('任務不符')
  if set(r)-set(REQ[s])-{'task','confirmed','proposal'}:raise Bound('有未定義欄位')
  if r['task']=='check_proposal':need(r,'proposal')
  ans=compute(s,r)
  if r['task']=='solve':return dict(decision='pass',answer=ans,reason='依已確認文字條件推理；不是圖像辨識或實物操作驗證')
  try:ok=same(r['proposal'],ans)
  except (Bound,ValueError,ZeroDivisionError):ok=False
  return dict(decision='pass'if ok else'reject',answer=dict(accepted=ok,correctSolution=ans),reason='逐一核對指定關係、數值與單位，不只核最後數字')
 except Ask as e:return dict(decision='confirm',answer=None,reason=str(e))
 except (Bound,ValueError,ZeroDivisionError,TypeError,RecursionError,OverflowError)as e:return dict(decision='block',answer=None,reason=str(e))
def verify_package(d):
 errors=[]
 for c in d['cases']:
  z=evaluate(c['subtypeId'],copy.deepcopy(c['input']))
  if(z['decision'],z['answer'])!=(c['expectedDecision'],c['expectedAnswer']):errors.append(dict(id=c['id'],actual=z))
 return errors
def validate_pack(d):return verify_package(d)
if __name__=='__main__':
 if len(sys.argv)>1 and sys.argv[1]=='evaluate':
  try:
   if len(sys.argv[3])>65536:raise ValueError('輸入過長')
   value=json.loads(sys.argv[3]);z=evaluate(sys.argv[2],value)
  except (ValueError,RecursionError,OverflowError):z=dict(decision='block',answer=None,reason='JSON不合法或過大')
  print(json.dumps(z,ensure_ascii=False));sys.exit(0)
 if len(sys.argv)>1:
  p=pathlib.Path(sys.argv[1]);d=json.loads(p.read_text());errors=verify_package(d);print(json.dumps(dict(ok=not errors,cases=len(d['cases']),errors=errors),ensure_ascii=False));sys.exit(bool(errors))
 try:
  raw_stdin=sys.stdin.read(65537)
  if len(raw_stdin)>65536:raise ValueError('輸入過長')
  d=json.loads(raw_stdin);z=evaluate(d.get('subtypeId'),d.get('input'))if type(d)is dict else dict(decision='block',answer=None,reason='JSON頂層須為物件')
 except (ValueError,RecursionError,OverflowError):z=dict(decision='block',answer=None,reason='JSON不合法或過大')
 print(json.dumps(z,ensure_ascii=False))
