import pathlib,json,sys,re,collections,copy
from fractions import Fraction
PACK='grade4-lines-methods'
SUBTYPES={'s45-right-angle-lines': 'right-angle-lines', 's45-parallel-evidence': 'parallel-evidence', 's45-line-drawing-guidance': 'line-drawing-guidance'}
REQ={'right-angle-lines':['angleDegrees','intersectingStraightLinesConfirmed'],'parallel-evidence':['basis','samePlane','distinctLines'],'line-drawing-guidance':['targetType','pointDistanceCm','actions','observationSource'],'congruence-correspondence':['quantity','partCount','sourceIndex','knownValue','mapping','fullCongruenceConfirmed'],'overlap-guidance':['edgeCount','actions','overlapRecord','noStretch','originalPiecePreserved','observationSource'],'triangle-sides':['sideLengths','triangleConfirmed'],'triangle-angles':['largestAngle','maximumConfirmed','triangleConfirmed'],'triangle-drawing-guidance':['targetType','baseCm','leftBaseAngle','rightBaseAngle','actions','observationSource'],'quadrilateral-classify':['items','closedSimpleShapesConfirmed'],'quadrilateral-side':['shape','propertiesConfirmed','sourceSide','knownCm','targetSide'],'quadrilateral-drawing-guidance':['targetType','baseCm','heightCm','shiftCm','unitGridConfirmed','actions','observationSource']}
ACTIONS={'line-drawing-guidance':['place-reference-edge','hold-ruler','slide-board','pass-point','draw-line','check-right-or-gap'],'overlap-guidance':['move','turn','turn-over'],'triangle-drawing-guidance':['draw-base','mark-left-angle','mark-right-angle','join-intersection','measure-three-sides','measure-three-angles'],'quadrilateral-drawing-guidance':['draw-base','mark-height','mark-top-shift','draw-top','join-sides','check-parallel-and-right']}
ALABEL={'place-reference-edge':'三角板一邊貼基準直線','hold-ruler':'固定直尺與三角板方向','slide-board':'沿直尺滑動三角板','pass-point':'調整到新線會經過指定點','draw-line':'沿板邊畫新線','check-right-or-gap':'用直角或垂直間距重新核對','move':'把紙片向旁搬','turn':'把紙片轉個方向','turn-over':'把紙片翻面','draw-base':'畫底邊','mark-left-angle':'從左端標向內角','mark-right-angle':'從右端標向內角','join-intersection':'連接兩射線交點','measure-three-sides':'實量三邊','measure-three-angles':'實量三角','mark-height':'沿垂直方向量高','mark-top-shift':'標上邊同向挪移量','draw-top':'畫同方向上邊','join-sides':'連左右邊','check-parallel-and-right':'核對兩組平行與指定直角等邊'}
PAIRS={'equilateral':[(60,60)],'isosceles':[(40,40),(50,50),(70,70)],'right':[(90,20),(90,30),(90,45),(20,90)],'acute':[(40,60),(50,60),(60,70),(70,70)],'obtuse':[(100,30),(110,25),(120,20),(130,15)]}
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,vs):
 if type(v)is not str or v not in vs:raise ValueError()
 return v
def flag(v):
 if type(v)is not bool:raise ValueError()
 return v
def number(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(x!='0'for x 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 number(p)==a
  except(ValueError,ZeroDivisionError,TypeError):return False
 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=='familySet':return all(type(x)is str for x in p)and len(set(p))==len(p)and set(p)==set(a)
  return all(eq(x,y,'familySet'if key=='classifications'else'')for x,y in zip(p,a))
 return type(p)is type(a)and p==a
def subreq(mode,r):
 if mode=='parallel-evidence':return ['angleA','angleB']if r.get('basis')=='common-perpendicular'else['gaps','gapPattern']if r.get('basis')=='observed-gap'else[]
 return []
def names(profile):
 p=integer(profile['parallelPairs'],0,2);same=flag(profile['allSidesEqual']);right=flag(profile['allAnglesRight']);opp=flag(profile['oppositeSidesEqual'])
 if(same or right or opp)and p!=2 or(p==2 and not opp):raise ValueError()
 if p==2:return ['正方形','長方形','菱形','平行四邊形']if same and right else['長方形','平行四邊形']if right else['菱形','平行四邊形']if same else['平行四邊形']
 return ['梯形']if p==1 else['其他四邊形（未符合上述特殊類）']
def action_plan(mode,r):
 acts=r['actions'];allowed=ACTIONS[mode]
 if type(acts)is not list or len(acts)>10:raise ValueError()
 acts=[enum(v,allowed)for v in acts];enum(r['observationSource'],('learner-operation-log','teacher-operation-log'))
 if mode=='line-drawing-guidance':
  target=enum(r['targetType'],('perpendicular','parallel'));gap=integer(r['pointDistanceCm'],0,20)
  if target=='parallel'and gap==0:raise ValueError()
  required=allowed[:];plan=['確認基準直線與指定點；點在'+('線上。'if gap==0 else f'已量得離線的垂直距離{gap}公分。')]
  if target=='perpendicular':plan+=['三角板一條直角邊貼原線，配直尺固定並滑動板，直到另一條直角邊會經過指定點。','沿會經過指定點的直角邊畫新線；現場再用直角核對交角90度。']
  else:plan+=['三角板一邊貼原線，另一邊靠固定直尺；保持方向沿尺滑動到同一畫線邊會經過指定點。','沿該邊畫線；現場核對兩線同方向、在不同位置的垂直間距，不能只憑兩筆看似平行。']
 elif mode=='triangle-drawing-guidance':
  target=enum(r['targetType'],PAIRS);base=integer(r['baseCm'],1,30);l=integer(r['leftBaseAngle'],1,179);rr=integer(r['rightBaseAngle'],1,179)
  if(l,rr)not in PAIRS[target]:raise ValueError()
  required=allowed[:];plan=[f'畫{base}公分底邊；在左端以朝右底邊為0，向底邊同一側標{l}度射線。',f'在右端以朝左底邊為0，也向同一側標{rr}度射線；兩射線相遇的點作第三頂點，連成封閉三邊。','現場實量三邊與三角，核對題目指定的'+{'equilateral':'三邊等長','isosceles':'兩腰等長且非三邊全等','right':'有直角','acute':'三個角都小於90度','obtuse':'有大於90度的角'}[target]+'；逐項實測核對，紀錄本身不能證明已畫對。']
 elif mode=='quadrilateral-drawing-guidance':
  target=enum(r['targetType'],('square','rectangle','parallelogram'));b=integer(r['baseCm'],1,20);h=integer(r['heightCm'],1,20);shift=integer(r['shiftCm'],0,10)
  if not flag(r['unitGridConfirmed']):raise ValueError()
  if target=='square'and(b!=h or shift!=0)or target=='rectangle'and shift!=0:raise ValueError()
  required=allowed[:];plan=[f'使用已確認1公分方格紙，畫底邊{b}公分，從兩端各沿垂直方向往上量{h}公分。',f'把上方兩個點都向右挪{shift}格，沿同方向連成{b}公分上邊，再連左右側邊。','現場核對兩組相對邊平行；'+('四邊等長且四角直角。'if target=='square'else'四角直角。'if target=='rectangle'else'不把畫成傾斜外觀當成平行證據，逐項量與操作確認。')]
 else:raise ValueError()
 match=acts==required;i=0
 while i<min(len(acts),len(required))and acts[i]==required[i]:i+=1
 nextStep='請教師現場量與核對，本紀錄不代表實物已驗或學生已掌握'if match else('先回現場補或核對「'+ALABEL[required[i]]+'」並補記操作'if i<len(required)else'固定計畫之外還有額外操作，先請教師核對紀錄')
 return dict(targetType=target,requiredActions=required,recordMatchesSteps=match,plan=plan,physicalVerified=False,nextStep=nextStep)
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];fields=REQ[mode]+subreq(mode,r)
 if r.get('factsConfirmed')is not True or any(k not in r or r[k]is None for k in fields):return out('confirm',r='先確認必要原觀察、量值或操作紀錄，不由外觀補值')
 for k in('actions','mapping','sideLengths','gaps'):
  if k in r and type(r[k])is list and len(r[k])<=10 and any(v is None for v in r[k]):return out('confirm',r='原列表缺少必要觀察，不猜被遮住的部分')
 if mode=='quadrilateral-classify'and type(r['items'])is list and len(r['items'])<=4:
  if any(type(x)is dict and any(k not in x or x[k]is None for k in('parallelPairs','allSidesEqual','allAnglesRight','oppositeSidesEqual'))for x in r['items']):return out('confirm',r='平行、邊角條件有缺項，先確認')
 if set(r)-set(fields)-{'factsConfirmed','task','proposal'}-({'angleRange'}if mode=='right-angle-lines'else{'maximumRange'}if mode=='triangle-angles'else set())or type(r.get('task'))is not str or r['task']not in('solve','check_proposal'):return out('block',r='結構或任務不符')
 try:
  if mode=='right-angle-lines':
   a=integer(r['angleDegrees'],1,179)
   if 'angleRange'in r:
    bounds=r['angleRange']
    if type(bounds)is not list or len(bounds)!=2 or not integer(bounds[0],1,179)<=a<=integer(bounds[1],1,179):raise ValueError()
   if not flag(r['intersectingStraightLinesConfirmed']):return out('confirm',r='先確認兩條相交直線與實測交角')
   ans={'perpendicular':a==90,'rightAngle':a==90,'unit':'degree'}
  elif mode=='parallel-evidence':
   basis=enum(r['basis'],('common-perpendicular','observed-gap'))
   if not flag(r['samePlane'])or not flag(r['distinctLines']):return out('confirm',r='先確認同一平面上的兩條不同直線')
   if basis=='common-perpendicular':
    a=integer(r['angleA'],1,179);b=integer(r['angleB'],1,179);con='平行'if a==b==90 else'不平行'if a!=b and a+b!=180 else'資料不足，不能判平行或不平行'
   else:
    xs=r['gaps'];pattern=enum(r['gapPattern'],('everywhere-same','known-different','two-samples-only'))
    if type(xs)is not list or not 2<=len(xs)<=4:raise ValueError()
    xs=[integer(x,1,30)for x in xs]
    if pattern in('everywhere-same','two-samples-only')and len(set(xs))!=1 or pattern=='known-different'and len(set(xs))==1:raise ValueError()
    con='平行'if pattern=='everywhere-same'else'不平行'if pattern=='known-different'else'資料不足，不能判平行或不平行'
   ans={'conclusion':con}
  elif mode in('line-drawing-guidance','triangle-drawing-guidance','quadrilateral-drawing-guidance'):
   if mode=='quadrilateral-drawing-guidance'and type(r['unitGridConfirmed'])is bool and not r['unitGridConfirmed']:return out('confirm',r='先確認方格同大且每格1公分，再規劃量長')
   ans=action_plan(mode,r)
  elif mode=='congruence-correspondence':
   q=enum(r['quantity'],('side','angle'));n=integer(r['partCount'],3,6);i=integer(r['sourceIndex'],1,n);v=integer(r['knownValue'],1,30 if q=='side'else 179);mp=r['mapping']
   if not flag(r['fullCongruenceConfirmed']):return out('confirm',r='先確認整體同形同大及完整對應，不能用局部相等判全等')
   if type(mp)is not list or len(mp)!=n:raise ValueError()
   mp=[integer(x,1,n)for x in mp]
   if len(set(mp))!=n:raise ValueError()
   ans={'correspondingPartIndex':mp[i-1],'value':v,'unit':'cm'if q=='side'else'degree'}
  elif mode=='overlap-guidance':
   n=integer(r['edgeCount'],3,6);acts=r['actions'];state=enum(r['overlapRecord'],('complete','not-yet','not-recorded'));stretch=flag(r['noStretch']);original=flag(r['originalPiecePreserved']);enum(r['observationSource'],('learner-operation-log','teacher-operation-log'))
   if type(acts)is not list or len(acts)>6:raise ValueError()
   acts=[enum(x,ACTIONS[mode])for x in acts];supports=True if state=='complete'and stretch and original else None
   plan=[f'保留原紙片，不拉伸不另切；逐一核對全部{n}邊與內部區域。','可以把紙片向旁搬、轉個方向或翻面，再嘗試整體貼合；不只對一角或一邊。']
   nextStep='本紀錄支持同形同大，仍請教師現場核對，不宣稱實物已驗'if supports else'先恢復原形原片再試疊合'if not stretch or not original else'換個方向或把紙片翻面再試，補記整體貼合；這次沒疊上不能判不全等'
   ans={'recordSupportsCongruence':supports,'plan':plan,'physicalVerified':False,'nextStep':nextStep}
  elif mode=='triangle-sides':
   xs=r['sideLengths']
   if type(xs)is not list or len(xs)!=3:raise ValueError()
   xs=[integer(x,1,30)for x in xs]
   if not flag(r['triangleConfirmed']):return out('confirm',r='先確認實物是封閉三邊圖形')
   if max(xs)>=sum(xs)-max(xs):raise ValueError()
   count=len(set(xs));ans={'sideClass':'正三角形'if count==1 else'等腰但非正三角形'if count==2 else'三邊不等的三角形','atLeastTwoEqual':count<3}
  elif mode=='triangle-angles':
   a=integer(r['largestAngle'],60,179)
   if 'maximumRange'in r:
    bounds=r['maximumRange']
    if type(bounds)is not list or len(bounds)!=2 or not integer(bounds[0],60,179)<=a<=integer(bounds[1],60,179):raise ValueError()
   if not flag(r['triangleConfirmed'])or not flag(r['maximumConfirmed']):return out('confirm',r='先逐角量過確認最大角，不以一個小角猜三角類別')
   ans={'angleClass':'銳角三角形'if a<90 else'直角三角形'if a==90 else'鈍角三角形'}
  elif mode=='quadrilateral-classify':
   xs=r['items']
   if type(xs)is not list or not 1<=len(xs)<=4:raise ValueError()
   if not flag(r['closedSimpleShapesConfirmed']):return out('confirm',r='先確認四邊封閉不交叉及全部邊角條件')
   if any(type(x)is not dict or set(x)!={'parallelPairs','allSidesEqual','allAnglesRight','oppositeSidesEqual'}for x in xs):raise ValueError()
   ans={'classifications':[names(x)for x in xs]}
  elif mode=='quadrilateral-side':
   shape=enum(r['shape'],('square','rectangle','rhombus','parallelogram'));src=integer(r['sourceSide'],1,4);target=integer(r['targetSide'],1,4);v=integer(r['knownCm'],1,30)
   if not flag(r['propertiesConfirmed']):return out('confirm',r='先確認實物形狀及等邊關係，不由名稱猜量')
   if shape not in('square','rhombus')and src!=target and(src-target)%2!=0:return out('confirm',r='相鄰邊不保證等長，先補目標邊實測')
   ans={'sideIndex':target,'lengthCm':v,'unit':'cm'}
  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 eq(r['proposal'],ans):return out('reject',ans,'保留原條件，回到同一具體關係或操作紀錄')
 return out('pass',ans,'只核已確認文字/操作紀錄，不驗實物或學生掌握')
def check(path=None):
 d=json.load(open(path or pathlib.Path(__file__).with_name(PACK+'.json')));ct=collections.Counter()
 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
 print(json.dumps({'cases':len(d['cases']),'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)
