import json,pathlib,re,sys,collections
from fractions import Fraction
PACK='grade2-add-sub-relations';SUBTYPES=['r2-check-subtraction', 'r2-rebuild-whole']
REQ={'r1-story':['a','b','event'],'r1-equality':['leftA','leftB','leftOp','rightA','rightB','rightOp'],'r1-swap':['a','b'],'r1-two-sums':['a','b','c','d'],'r2-compare':['a','b','unitA','unitB'],'r2-chain':['middle','firstToMiddle','middleToLast'],'r2-reorder':['terms'],'r2-group':['a','b','c','firstPair'],'r2-array-turn':['rows','columns'],'r2-two-arrays':['rows','columns','otherRows','otherColumns'],'r2-check-subtraction':['whole','taken','claimedRemaining'],'r2-rebuild-whole':['remaining','taken']}
class Invalid(Exception):pass
class Need(Exception):pass
class Scope(Exception):pass

def integer(x,hi=1000):
 if type(x)is not int or x<0:raise Invalid('已確認數量需為非負整數，不能是小數、真假值或文字')
 if x>hi:raise Scope('超出本包年級數量範圍；轉交相符數量方法，不表示原題無解')
 return x

def enum(x,choices):
 if type(x)is not str or x not in choices:raise Invalid('原題符號或操作不在明定選項')
 return x

def expr(a,b,op):
 if op=='+':return a+b
 if b>a:raise Need('拿走數多於原有數，請核對原題；本階段不寫負數剩量')
 return a-b

def numanswer(x):
 if type(x)is int:
  if abs(x)>10**12:raise Invalid('答案數字過大')
  return Fraction(x)
 if type(x)is str and len(x)<=60 and re.fullmatch(r'[0-9]{1,24}(?:/[1-9][0-9]{0,23}|\.[0-9]{1,12})?',x,re.ASCII):return Fraction(x)
 raise Invalid('答案須為有界精確數')

def eq(p,a):
 if type(p)is not dict or set(p)!=set(a):return False
 try:
  for k,v in a.items():
   if type(v)is bool:
    if type(p[k])is not bool or p[k]!=v:return False
   elif type(v)is str and k in ['operator','relation','unit']:
    if type(p[k])is not str or p[k]!=v:return False
   elif numanswer(p[k])!=numanswer(v):return False
  return True
 except(Invalid,ValueError,ZeroDivisionError,TypeError):return False

def chain_ranges(d):
 b=integer(d['middle']);ab=enum(d['firstToMiddle'],['<','>','=']);bc=enum(d['middleToLast'],['<','>','='])
 def interval(op,reverse=False):
  if reverse:op={'<':'>','>':'<','=':'='}[op]
  return (0,b-1)if op=='<'else(b+1,1000)if op=='>'else(b,b)
 ar=interval(ab);cr=interval(bc,True)
 if ar[0]>ar[1] or cr[0]>cr[1]:raise Need('已確認的大小關係與本題數量範圍不相容，先核對條件')
 return ar,cr

def compute(s,d):
 hi=100 if s.startswith('r1-')else 1000
 if s=='r1-story':
  a,b=integer(d['a'],hi),integer(d['b'],hi);event=enum(d['event'],['merge','take']);op='+'if event=='merge'else'−';v=expr(a,b,'+'if event=='merge'else'-')
  if v>hi:raise Scope('結果超過一年級一百內，本包轉相符方法，不稱原題錯誤')
  return {'operator':op,'value':v}
 if s=='r1-equality':
  nums=[integer(d[k],hi)for k in ['leftA','leftB','rightA','rightB']];lo=enum(d['leftOp'],['+','-']);ro=enum(d['rightOp'],['+','-']);l=expr(*nums[:2],lo);r=expr(*nums[2:],ro)
  if max(l,r)>hi:raise Scope('本包先處理一百內兩邊同量')
  return {'left':l,'right':r,'equal':l==r}
 if s in ['r1-swap','r1-two-sums']:
  a,b=integer(d['a'],hi),integer(d['b'],hi);v=a+b
  if v>hi:raise Scope('兩群總量超過一年級一百內，轉相符方法')
  if s=='r1-swap':return {'total':v,'swappedTotal':b+a,'unchanged':True}
  c,e=integer(d['c'],hi),integer(d['d'],hi)
  if c+e>hi:raise Scope('兩群總量超過一年級一百內，轉相符方法')
  return {'firstTotal':v,'secondTotal':c+e,'sameTerms':sorted([a,b])==sorted([c,e]),'sameTotal':v==c+e}
 if s=='r2-compare':
  a,b=integer(d['a']),integer(d['b']);ua=enum(d['unitA'],['個','公分','公尺','公斤']);ub=enum(d['unitB'],['個','公分','公尺','公斤'])
  if ua!=ub:raise Need('本型比較同一單位；請先確認並換成同單位，不能只比較數字')
  return {'relation':'>'if a>b else'<'if a<b else'='}
 if s=='r2-chain':
  ar,cr=chain_ranges(d);rel='<'if ar[1]<cr[0]else'>'if ar[0]>cr[1]else'='if ar==cr and ar[0]==ar[1]else'不能確定';return {'relation':rel}
 if s=='r2-reorder':
  xs=d['terms'];order=d.get('order') if d.get('order')is not None else [0,1,2]
  if type(xs)is not list or len(xs)!=3:raise Invalid('三群需完整三個數')
  xs=[integer(x)for x in xs]
  if type(order)is not list or len(order)!=3 or any(type(i)is not int for i in order)or sorted(order)!=[0,1,2]:raise Invalid('每一群必須剛好保留一次，不能漏群或重複群')
  total=sum(xs)
  if total>1000:raise Scope('總量超過二年級一千內，轉相符方法')
  return {'total':total,'reorderedTotal':sum(xs[i]for i in order),'unchanged':True}
 if s=='r2-group':
  a,b,c=[integer(d[k])for k in ['a','b','c']];pair=enum(d['firstPair'],['ab','ac','bc']);v=a+b+c
  if v>1000:raise Scope('總量超過二年級一千內，轉相符方法')
  sub={'ab':a+b,'ac':a+c,'bc':b+c}[pair];return {'firstSubtotal':sub,'total':v}
 if s in ['r2-array-turn','r2-two-arrays']:
  rows,cols=integer(d['rows'],10),integer(d['columns'],10);v=sum(cols for _ in range(rows))
  if s=='r2-array-turn':return {'total':v,'turnedRows':cols,'turnedColumns':rows,'turnedTotal':sum(rows for _ in range(cols))}
  rr,cc=integer(d['otherRows'],10),integer(d['otherColumns'],10);w=sum(cc for _ in range(rr));return {'firstTotal':v,'secondTotal':w,'isTurn':(rr,cc)==(cols,rows),'sameTotal':v==w}
 if s=='r2-check-subtraction':
  whole,taken,remaining=[integer(d[k])for k in ['whole','taken','claimedRemaining']]
  if taken>whole:raise Need('拿走數超過原有數，先確認題意；不寫負數剩量')
  # Correct remainder obtained by counting forward from taken, not subtracting to check addition.
  correct=len(range(taken,whole));combined=remaining+taken;return {'correctRemaining':correct,'checkTotal':combined,'isCorrect':combined==whole}
 if s=='r2-rebuild-whole':
  remaining,taken=integer(d['remaining']),integer(d['taken']);v=remaining+taken
  if v>1000:raise Scope('原有總量超過二年級一千內，轉相符方法')
  return {'whole':v}
 raise Invalid('未知型')

def evaluate(s,d):
 def out(decision,answer=None,reason=''):return dict(decision=decision,answer=answer,reason=reason)
 if type(s)is not str or s not in SUBTYPES or type(d)is not dict:return out('block',reason='不屬本有限文字方法')
 required=REQ[s]
 if any(d.get(k)is None for k in required+['factsConfirmed']):return out('confirm',reason='先補清缺少的原題數量、符號或條件，不猜圖或物件')
 for k in ['terms','order']:
  if k in required and type(d[k])is list and any(x is None for x in d[k]):return out('confirm',reason='三群數量或移動次序有缺項，請補清原條件')
 if type(d['factsConfirmed'])is not bool:return out('block',reason='原條件確認狀態須明確')
 if not d['factsConfirmed']:return out('confirm',reason='原數量或情境尚未確認，不能宣稱已辨識實物')
 if set(d)-set(required)-({'task','factsConfirmed','proposal'}|({'order'}if s=='r2-reorder'else set())):return out('block',reason='未知欄位不可冒充已確認原量')
 if type(d.get('task'))is not str or d['task']not in ['solve','check_proposal']:return out('block',reason='未知任務')
 try:a=compute(s,d)
 except Need as e:return out('confirm',reason=str(e))
 except Scope as e:return out('block',reason=str(e))
 except(Invalid,ValueError,ZeroDivisionError,TypeError,OverflowError)as e:return out('block',reason=str(e))
 if d['task']=='check_proposal':
  if d.get('proposal')is None:return out('confirm',a,'請提供要核對的想法，原量正解保留')
  if not eq(d['proposal'],a):return out('reject',a,'錯提案不改原條件，回到相同群量與算式核對')
 return out('pass',a,'僅依已確認文字/原量計算，不宣稱實物辨識')

def check():
 p=json.load(open(pathlib.Path(__file__).with_name(PACK+'.json')))
 for s in SUBTYPES:assert collections.Counter(c['kind']for c in p['cases']if c['subtypeId']==s)==dict(normal=8,negative=6,boundary=4,ambiguous=2,holdout=4)
 for c in p['cases']:
  r=evaluate(c['subtypeId'],c['input']);assert(r['decision'],r['answer'])==(c['expectedDecision'],c['expectedAnswer']),c['id']
 print(json.dumps({'package':PACK,'cases':len(p['cases']),'passed':True}))
if __name__=='__main__':
 if len(sys.argv)>1 and sys.argv[1]=='evaluate':
  q=json.load(sys.stdin);print(json.dumps(evaluate(q.get('subtypeId'),q.get('input')),ensure_ascii=False))
 else:check()
