import json,sys,pathlib,math,copy,collections,re
from fractions import Fraction
PACK='grade2-boundary-length-methods'
SUBTYPES={'g2-geo-boundary-sum': 'boundary-sum', 'g2-geo-equal-edge-complete': 'equal-edge-complete'}
REQ={'touch-features':['observations'],'aligned-length':['aEnd','bEnd','sameStart','sameDirection','orderedMarks'],'plane-classify':['items','allContoursConfirmed'],'solid-classify':['items','allSurfacesConfirmed'],'ruler-read':['start','end','unit','straightAligned'],'ruler-mark':['start','length','maximum','unit'],'boundary-sum':['edges','unit','closedBoundary','allEdgesOnce'],'equal-edge-complete':['shape','edges','unit','shapeConfirmed','equalRelationsConfirmed'],'tile-compare':['aTiles','bTiles','sameTile','aFilled','bFilled','noOverlap'],'cut-preserve':['originalPieces','keptPieces','samePieces','noStretch','noOverlap'],'overlay-containment':['aOnlyRegions','bOnlyRegions','sharedRegions','allRegionsConfirmed','noStretch','noOverlap']}
def out(d,a=None,r=''):return {'decision':d,'answer':a,'reason':r}
def natural(v,lo=0,hi=100):
 if type(v)is not int or not lo<=v<=hi:raise ValueError('原量需有限整數')
 return v
def flag(v):
 if type(v)is not bool:raise ValueError('條件需已確認是或否')
 return v
def enum(v,vs):
 if type(v)is not str or v not in vs:raise ValueError('不在此有限方法')
 return v
def relation(a,b):return '甲較長'if a>b else'乙較長'if a<b else'一樣長'
def same_answer(p,a):
 if type(a)is int:
  if type(p)is bool or type(p)is float:return False
  if type(p)is int:return abs(p)<10**80 and p==a
  # Reject exponent notation before Fraction: short strings may otherwise request huge powers.
  if type(p)is str and 1<=len(p)<=80 and re.fullmatch(r'[+-]?(?:[0-9]{1,80}(?:/[0-9]{1,80}|\.[0-9]{0,80})?|\.[0-9]{1,80})',p,re.ASCII):
   if '/'in p and not any(x!='0'for x in p.split('/')[1]):return False
   try:return Fraction(p)==a
   except(ValueError,ZeroDivisionError):return False
  return False
 if type(a)is bool:return type(p)is bool and p==a
 if type(a)is dict:return type(p)is dict and set(p)==set(a)and all(same_answer(p[k],a[k])for k in a)
 if type(a)is list:return type(p)is list and len(p)==len(a)and all(same_answer(x,y)for x,y in zip(p,a))
 return type(p)is type(a)and p==a
def missing(mode,r):
 if any(k not in r or r[k]is None for k in REQ[mode]):return True
 if mode=='touch-features'and type(r['observations'])is list and len(r['observations'])<=4:return any(x is None for x in r['observations'])
 if mode in('plane-classify','solid-classify')and type(r['items'])is list and len(r['items'])<=4:
  fields=('straightSides','curvedBoundary','closed','circleConfirmed')if mode=='plane-classify'else('flatFaces','curvedSide','roundFlatEnds','boxLayout','ballConfirmed')
  for x in r['items']:
   if type(x)is not dict:continue
   if any(k not in x or x[k]is None for k in fields):return True
   if mode=='solid-classify' and x.get('flatFaces')==2 and x.get('curvedSide')is True and x.get('roundFlatEnds')==2 and x.get('boxLayout')is False:
    if any(k not in x or x[k]is None for k in('equalRoundEnds','uniformThickness','columnLayout')):return True
  return False
 if mode in('boundary-sum','equal-edge-complete')and type(r['edges'])is list and len(r['edges'])<=8:return any(x is None for x in r['edges'])
 return False
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]
 if r.get('confirmed')is not True or missing(mode,r):return out('confirm',r='先確認缺少的原條件，不由圖形名稱或外觀補值')
 if set(r)-set(REQ[mode])-{'confirmed','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=='touch-features':
   xs=r['observations'];mp={'flat-patch':'平平的面','curved-patch':'彎彎的面','two-faces-line':'邊','edges-meet-point':'角'}
   if type(xs)is not list or not 1<=len(xs)<=4:raise ValueError()
   ans={'features':[mp[enum(x,mp)]for x in xs]}
  elif mode=='aligned-length':
   a=natural(r['aEnd'],1,30);b=natural(r['bEnd'],1,30)
   if not all(flag(r[k])for k in('sameStart','sameDirection','orderedMarks')):return out('confirm',r='先把左端排齊、朝同一方向，再確認比較記號的先後')
   ans={'relation':relation(a,b)}
  elif mode in('plane-classify','solid-classify'):
   xs=r['items']
   if type(xs)is not list or not 1<=len(xs)<=4:raise ValueError()
   if not flag(r['allContoursConfirmed'if mode=='plane-classify'else'allSurfacesConfirmed']):return out('confirm',r='需確認完整輪廓或轉動後全部表面，不能猜背面')
   kinds=[]
   for x in xs:
    if type(x)is not dict:raise ValueError()
    if mode=='plane-classify':
     if set(x)!={'straightSides','curvedBoundary','closed','circleConfirmed'}:raise ValueError()
     s=natural(x['straightSides'],0,8);cur=flag(x['curvedBoundary']);cl=flag(x['closed']);circle=flag(x['circleConfirmed'])
     if circle and(s!=0 or not cur):raise ValueError()
     if not cl:return out('confirm',r='先確認要辨認的是完整封閉輪廓')
     if cur and s==0:k='圓形輪廓'
     elif not cur and s==3:k='三角形'
     elif not cur and s==4:k='四邊形'
     else:return out('block',r='本型只已確認圓輪廓或三、四條直邊封閉圖形')
     # A boundary being curved alone does not prove it is a circle.
     if cur and not circle:k='有彎曲邊界，不能只憑此確定是圓'
    else:
     baseKeys={'flatFaces','curvedSide','roundFlatEnds','boxLayout','ballConfirmed'}
     isColumnCandidate=x.get('flatFaces')==2 and x.get('curvedSide')is True and x.get('roundFlatEnds')==2 and x.get('boxLayout')is False
     expectedKeys=baseKeys|{'equalRoundEnds','uniformThickness','columnLayout'} if isColumnCandidate else baseKeys
     if set(x)!=expectedKeys:raise ValueError()
     f=natural(x['flatFaces'],0,6);cur=flag(x['curvedSide']);ends=natural(x['roundFlatEnds'],0,2);box=flag(x['boxLayout']);ball=flag(x['ballConfirmed'])
     if ball and(f!=0 or not cur or ends!=0 or box):raise ValueError()
     if f==6 and not cur and ends==0 and box:k='盒狀物'
     elif f==2 and cur and ends==2 and not box:
      equalEnds=flag(x['equalRoundEnds']);uniform=flag(x['uniformThickness']);layout=flag(x['columnLayout'])
      k='圓柱狀物'if equalEnds and uniform and layout else'有兩個平圓端面與曲側面，但已確認不是本型圓柱狀物'
     elif f==0 and cur and ends==0 and not box:k='球狀物'if ball else'只有曲面，不能只憑此確定是球'
     else:return out('block',r='已確認表面條件與本型特徵不一致，先重新觀察')
    kinds.append(k)
   ans={'classifications':kinds}
  elif mode=='ruler-read':
   s=natural(r['start']);e=natural(r['end']);enum(r['unit'],('cm',))
   if not flag(r['straightAligned']):return out('confirm',r='尺與物品需平貼同方向')
   if e<s:raise ValueError()
   ans={'length':e-s,'unit':'cm'}
  elif mode=='ruler-mark':
   s=natural(r['start']);n=natural(r['length']);mx=natural(r['maximum']);enum(r['unit'],('cm',))
   if s>mx or s+n>mx:return out('block',r='這把尺的已確認可用範圍不夠，換工具或改起點')
   ans={'end':s+n,'length':n,'unit':'cm'}
  elif mode=='boundary-sum':
   es=r['edges'];enum(r['unit'],('cm',))
   if type(es)is not list or not 3<=len(es)<=8:raise ValueError()
   es=[natural(x,1,30)for x in es]
   if not flag(r['closedBoundary'])or not flag(r['allEdgesOnce']):return out('confirm',r='需核對外框封閉並逐邊量過一次')
   if sum(es)>100 or max(es)>=sum(es)-max(es):return out('block',r='原量或已確認外框資料不一致，需重測，不能當有效外框')
   ans={'perimeter':sum(es),'unit':'cm'}
  elif mode=='equal-edge-complete':
   enum(r['shape'],('square','rectangle'));enum(r['unit'],('cm',));es=r['edges']
   if type(es)is not list or len(es)!=4:raise ValueError()
   known=es[:];resolving=set()
   def resolve(i):
    if i in resolving:raise ValueError('等長引用無已知量')
    x=known[i]
    if type(x)is int:return natural(x,1,25)
    if type(x)is not str or x not in('same-as-1','same-as-2','same-as-3','same-as-4'):raise ValueError()
    resolving.add(i);v=resolve(int(x[-1])-1);resolving.remove(i);return v
   es=[resolve(i)for i in range(4)]
   if not flag(r['shapeConfirmed'])or not flag(r['equalRelationsConfirmed']):return out('confirm',r='先確認實物形狀與等長邊關係，不由名字補邊')
   if r['shape']=='square'and len(set(es))!=1 or r['shape']=='rectangle'and(es[0]!=es[2]or es[1]!=es[3]):return out('block',r='逐邊原量與已確認等長關係矛盾，請重測')
   ans={'edges':es,'perimeter':sum(es),'unit':'cm'}
  elif mode=='tile-compare':
   a=natural(r['aTiles'],1,60);b=natural(r['bTiles'],1,60)
   if not all(flag(r[k])for k in('sameTile','aFilled','bFilled','noOverlap')):return out('confirm',r='先用同大方片無重疊、無空隙鋪滿兩張紙，才能比塊數')
   ans={'relation':'甲較大'if a>b else'乙較大'if a<b else'一樣大'}
  elif mode=='cut-preserve':
   n=natural(r['originalPieces'],1,30);kept=natural(r['keptPieces'],0,30)
   if kept>n:raise ValueError()
   if not all(flag(r[k])for k in('samePieces','noStretch','noOverlap')):return out('confirm',r='先確認使用原來那些紙片、沒有拉伸或重疊')
   ans={'relation':'面積不變'if n==kept else'面積變小','lostPieces':n-kept}
  elif mode=='overlay-containment':
   a=natural(r['aOnlyRegions'],0,20);b=natural(r['bOnlyRegions'],0,20);shared=natural(r['sharedRegions'],1,20)
   if not all(flag(r[k])for k in('allRegionsConfirmed','noStretch','noOverlap')):return out('confirm',r='先確認整張重疊分區、紙沒有伸縮，不能只看局部')
   if a and b:return out('confirm',r='兩張各有露出的部分，區塊不保證同大；需再用同大方片或拼補比較')
   ans={'relation':'甲較大'if a else'乙較大'if b else'一樣大'}
  else:raise ValueError()
 except(ValueError,TypeError,KeyError,OverflowError):return out('block',r='原量、單位或已確認特徵不符此有限方法')
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',ans,'請先說說你的想法')
  if not same_answer(r['proposal'],ans):return out('reject',ans,'保留原條件逐步核對，不改題目湊答案')
 return out('pass',ans,'只核對已確認的文字資料；未驗證實物操作或圖片')
def check(path=None):
 d=json.loads(pathlib.Path(path or pathlib.Path(__file__).with_name(PACK+'.json')).read_text());ct=collections.Counter();rt=0
 for sid in SUBTYPES:assert collections.Counter(c['kind']for c in d['cases']if c['subtypeId']==sid)==dict(normal=8,negative=6,boundary=4,ambiguous=2,holdout=4)
 for c in d['cases']:
  res=evaluate(c['subtypeId'],c['input']);assert(res['decision'],res['answer'])==(c['expectedDecision'],c['expectedAnswer']),c['id'];ct[res['decision']]+=1
  if res['answer']is not None:assert evaluate(c['subtypeId'],dict(c['input'],task='check_proposal',proposal=res['answer']))['decision']=='pass';rt+=1
 print(json.dumps({'cases':len(d['cases']),'roundtrips':rt,'decisions':dict(ct)},ensure_ascii=False))
if __name__=='__main__':
 if len(sys.argv)>1 and sys.argv[1]=='evaluate':print(json.dumps(evaluate(sys.argv[2],json.loads(sys.argv[3])),ensure_ascii=False))
 else:check(sys.argv[1]if len(sys.argv)>1 else None)
