import json,pathlib,sys,re,collections
from fractions import Fraction as F
PACK='grade7-inequality-meaning';SUBTYPES=['a77-check', 'a77-model']
REQ={'a71-law':['law','a','b','c'],'a71-simplify':['terms','domain'],'a71-story':['scenario','multiplier','constant','symbol','quantityUnit'],'a72-check':['a','b','c','d','candidate','domain'],'a72-model':['unknownRole','coefficient','fixed','total','unit'],'a74-check':['equations','x','y','domain'],'a74-model':['mode','xRole','yRole','totalCount','priceX','priceY','totalPrice'],'a76-line':['a','b','c','pointX','pointY','xUnit','yUnit'],'a76-intersection':['equations','xUnit','yUnit'],'a77-check':['a','b','c','relation','candidate','domain'],'a77-model':['price','fixed','limit','word','unit'],'g71-location':['x','y','xUnit','yUnit'],'g71-move':['startX','startY','xScale','yScale','xPositive','yPositive','distanceUnit','moves']}
LAWS={'add-commute':('a+b','b+a'),'multiply-commute':('a*b','b*a'),'add-associate':('(a+b)+c','a+(b+c)'),'multiply-associate':('(a*b)*c','a*(b*c)'),'distribute-add':('a*(b+c)','a*b+a*c'),'distribute-subtract':('a*(b-c)','a*b-a*c')}
class Bad(Exception):pass
class Need(Exception):pass
class Route(Exception):pass

def num(v,answer=False):
 bound=10**256 if answer else 10**6
 if type(v)is int:
  if abs(v)>bound:raise Route('超出有限安全數域，保留原題轉方法，不判無解')
  return F(v)
 n=256 if answer else 12
 if type(v)is not str or len(v)>(520 if answer else 40)or not re.fullmatch(r'-?[0-9]{1,'+str(n)+r'}(?:/[1-9][0-9]{0,'+str(n-1)+r'}|\.[0-9]{1,'+str(n)+r'})?',v,re.ASCII):raise Bad('需精確整數/白名單小數分數，不收真假值、浮點、巨指數或任意算式')
 q=F(v)
 if abs(q)>bound or not answer and q.denominator>10000:raise Route('本模板數域有限，較大或更細原量另路由')
 return q

def en(v,xs):
 if type(v)is not str or v not in xs:raise Bad('角色、單位、規則或語意不明確')
 return v

def sym(v):
 if type(v)is not str or not re.fullmatch('[a-z]',v,re.ASCII):raise Bad('本型未知量須先明定一個小寫字母')
 return v

def nonneg(v):
 q=num(v)
 if q<0:raise Need('生活原量需非負，先核對抄寫條件')
 return q

def positive(v):
 q=num(v)
 if q<=0:raise Need('單位刻度或單價須正，先核對原條件')
 return q

def domain(v):return en(v,['all-real','nonnegative-real','nonnegative-integers'])
def in_domain(v,d):return d=='all-real'or v>=0 and(d=='nonnegative-real'or v.denominator==1)
def rows(v):
 if type(v)is not list or not 1<=len(v)<=2:raise Bad('本型只用明定一或兩條原等式')
 out=[]
 for r in v:
  if type(r)is not dict or set(r)!={'a','b','c'}:raise Bad('每式需明定x係數、y係數、右量')
  out.append(tuple(num(r[k])for k in ['a','b','c']))
 return out

def relation(op,l,r):return {'lt':l<r,'le':l<=r,'gt':l>r,'ge':l>=r}[en(op,['lt','le','gt','ge'])]
def position(x,y):
 if x==0 and y==0:return 'origin'
 if y==0:return 'x-axis'
 if x==0:return 'y-axis'
 return 'I'if x>0 and y>0 else'II'if x<0 and y>0 else'III'if x<0 and y<0 else'IV'

def compute(s,d):
 if s=='a71-law':
  law=en(d['law'],LAWS);a,b,c=[num(d[k])for k in ['a','b','c']];lf,rf=LAWS[law]
  if law=='add-commute':v=a+b
  elif law=='multiply-commute':v=a*b
  elif law=='add-associate':v=a+b+c
  elif law=='multiply-associate':v=a*b*c
  elif law=='distribute-add':v=a*(b+c)
  else:v=a*(b-c)
  return {'leftFormula':lf,'rightFormula':rf,'validForAllReal':True,'leftValue':str(v),'rightValue':str(v)}
 if s=='a71-simplify':
  dom=domain(d['domain']);ts=d['terms']
  if type(ts)is not list or not 1<=len(ts)<=4:raise Bad('只處理最多四個單層一次括號，非任意符號parser')
  aa=bb=F(0)
  for t in ts:
   if type(t)is not dict or set(t)!={'factor','coefficient','constant'}:raise Bad('單層括號需外乘數、一次項係數與常數')
   f,a,b=[num(t[k])for k in ['factor','coefficient','constant']];aa+=f*a;bb+=f*b
  return {'coefficient':str(aa),'constant':str(bb),'degree':1 if aa else 0,'domain':dom}
 if s=='a71-story':
  sc=en(d['scenario'],['purchase','box-content']);k=nonneg(d['multiplier']);b=nonneg(d['constant']);x=sym(d['symbol']);u=en(d['quantityUnit'],['元','枝'])
  if sc=='purchase'and u!='元'or sc=='box-content'and u!='枝':raise Bad('金額與物件量角色不一致')
  return {'symbol':x,'coefficient':str(k),'constant':str(b),'unit':u,'domain':'nonnegative-integers','unknownRole':'count'if sc=='purchase'else'per-box-count'}
 if s=='a72-check':
  a,b,c,e,x=[num(d[k])for k in ['a','b','c','d','candidate']];dom=domain(d['domain']);l=a*x+b;r=c*x+e
  return {'isLinearEquation':a!=c,'leftValue':str(l),'rightValue':str(r),'equalityHolds':l==r,'domainValid':in_domain(x,dom),'candidateSolution':l==r and in_domain(x,dom),'domain':dom}
 if s=='a72-model':
  role=en(d['unknownRole'],['count','unit-price']);a=positive(d['coefficient']);b=nonneg(d['fixed']);c=nonneg(d['total']);u=en(d['unit'],['元'])
  return {'a':str(a),'b':str(b),'c':str(c),'unit':u,'unknownRole':role,'domain':'nonnegative-integers'if role=='count'else'nonnegative-real'}
 if s=='a74-check':
  rr=rows(d['equations']);x,y=num(d['x']),num(d['y']);dom=domain(d['domain']);lv=[a*x+b*y for a,b,c in rr];flags=[v==r[2]for v,r in zip(lv,rr)];valid=in_domain(x,dom)and in_domain(y,dom)
  return {'isLinearEquations':[a!=0 or b!=0 for a,b,c in rr],'leftValues':[str(v)for v in lv],'rightValues':[str(r[2])for r in rr],'eachHolds':flags,'satisfiesAll':all(flags),'domainValid':valid,'candidateSolution':all(flags)and valid,'domain':dom}
 if s=='a74-model':
  mode=en(d['mode'],['count-only','price-only','both']);xr=en(d['xRole'],['pen','book']);yr=en(d['yRole'],['pen','book'])
  if xr==yr:raise Need('兩未知量需先分清各指哪種物件，不能同名混用')
  n=nonneg(d['totalCount'])if mode in ['count-only','both']else F(0)
  px,py,total=[nonneg(d[k])for k in ['priceX','priceY','totalPrice']]if mode in ['price-only','both']else[F(0)]*3
  if n.denominator!=1:raise Need('物件總數需整數，先核對')
  eq=[]
  if mode in ['count-only','both']:eq.append({'a':'1','b':'1','c':str(n),'unit':'個'})
  if mode in ['price-only','both']:eq.append({'a':str(px),'b':str(py),'c':str(total),'unit':'元'})
  return {'equations':eq,'domain':'nonnegative-integers','xRole':xr,'yRole':yr}
 if s=='a76-line':
  a,b,c,x,y=[num(d[k])for k in ['a','b','c','pointX','pointY']];xu=en(d['xUnit'],['坐標單位','公尺']);yu=en(d['yUnit'],['坐標單位','秒'])
  if a==b==0:return {'kind':'all-plane'if c==0 else'empty','constantCoordinate':None,'point1':None,'point2':None,'candidateOnLine':False,'equationHolds':c==0,'xUnit':xu,'yUnit':yu}
  if b==0:kind='vertical';k=c/a;p=[k,F(0)];q=[k,F(1)]
  else:kind='horizontal'if a==0 else'oblique';k=c/b if a==0 else None;p=[F(0),c/b];q=[F(1),(c-a)/b]
  return {'kind':kind,'constantCoordinate':str(k)if k is not None else None,'point1':[str(z)for z in p],'point2':[str(z)for z in q],'candidateOnLine':a*x+b*y==c,'equationHolds':a*x+b*y==c,'xUnit':xu,'yUnit':yu}
 if s=='a76-intersection':
  rr=rows(d['equations']);xu=en(d['xUnit'],['坐標單位','公尺']);yu=en(d['yUnit'],['坐標單位','秒'])
  if len(rr)!=2:raise Need('兩直線共同點需兩條原式，先補另一式')
  (a,b,c),(e,f,g)=rr
  if a==b==0 or e==f==0:return {'kind':'not-two-lines','point':None,'sharedPointVerified':False,'xUnit':xu,'yUnit':yu}
  det=a*f-e*b
  if det==0:
   same=a*g==e*c and b*g==f*c
   return {'kind':'coincident-boundary'if same else'parallel-boundary','point':None,'sharedPointVerified':False,'xUnit':xu,'yUnit':yu}
  x=(c*f-g*b)/det;y=(a*g-e*c)/det
  return {'kind':'unique-intersection','point':[str(x),str(y)],'sharedPointVerified':a*x+b*y==c and e*x+f*y==g,'xUnit':xu,'yUnit':yu}
 if s=='a77-check':
  a,b,c,x=[num(d[k])for k in ['a','b','c','candidate']];dom=domain(d['domain']);l=a*x+b;holds=relation(d['relation'],l,c)
  return {'isLinearInequality':a!=0,'leftValue':str(l),'rightValue':str(c),'holds':holds,'domainValid':in_domain(x,dom),'candidateSolution':holds and in_domain(x,dom),'boundaryIncluded':d['relation']in ['le','ge'],'domain':dom}
 if s=='a77-model':
  a=positive(d['price']);b=nonneg(d['fixed']);c=nonneg(d['limit']);word=en(d['word'],['at-least','at-most','under','over']);u=en(d['unit'],['元']);op={'at-least':'ge','at-most':'le','under':'lt','over':'gt'}[word]
  return {'a':str(a),'b':str(b),'c':str(c),'relation':op,'boundaryIncluded':op in ['le','ge'],'domain':'nonnegative-integers','unit':u}
 if s=='g71-location':
  x,y=num(d['x']),num(d['y']);xu=en(d['xUnit'],['坐標單位','公尺']);yu=en(d['yUnit'],['坐標單位','秒']);return {'x':str(x),'y':str(y),'position':position(x,y),'xUnit':xu,'yUnit':yu}
 if s=='g71-move':
  x,y=num(d['startX']),num(d['startY']);xs,ys=positive(d['xScale']),positive(d['yScale']);xp=en(d['xPositive'],['east','west']);yp=en(d['yPositive'],['north','south']);u=en(d['distanceUnit'],['公尺','公里']);ms=d['moves']
  if type(ms)is not list or not 1<=len(ms)<=4:raise Bad('只用已確認的一至四次橫縱移動，不算斜距')
  for v in ms:
   if type(v)is not dict or set(v)!={'direction','distance'}:raise Bad('每次移動需方位與距離')
   dr=en(v['direction'],['east','west','north','south']);q=nonneg(v['distance'])
   if dr in ['east','west']:x+=(1 if dr==xp else-1)*q/xs
   else:y+=(1 if dr==yp else-1)*q/ys
  return {'x':str(x),'y':str(y),'position':position(x,y),'distanceUnit':u}
 raise Bad('未知型')

NUMERIC={'a','b','c','coefficient','constant','leftValue','rightValue','value','x','y','constantCoordinate'}
NUMERIC_LIST={'leftValues','rightValues','point','point1','point2'}
def equivalent(p,a,key=''):
 try:
  if a is None:return p is None
  if type(a)is bool:return type(p)is bool and p==a
  if type(a)is int:return type(p)is int and p==a
  if type(a)is dict:return type(p)is dict and set(p)==set(a)and all(equivalent(p[k],v,k)for k,v in a.items())
  if type(a)is list:return type(p)is list and len(p)==len(a)and all(equivalent(x,v,'value'if key in NUMERIC_LIST else key)for x,v in zip(p,a))
  if key in NUMERIC:return num(p,True)==num(a,True)
  return type(p)is str and p==a
 except(Bad,Route,ValueError,TypeError,ZeroDivisionError,OverflowError):return False

def scaled_equation(p,a,inequality=False,twoVariable=False):
 try:
  aa,bb,cc=[num(a[k],True)for k in ['a','b','c']];pa,pb,pc=[num(p[k],True)for k in ['a','b','c']]
  if twoVariable:
   originals=[aa,bb,cc];proposed=[pa,pb,pc];pivot=next((i for i,v in enumerate(originals)if v!=0),None)
   if pivot is None:
    if any(proposed):return False
    scale=F(1)
   else:scale=proposed[pivot]/originals[pivot]
   if scale==0 or any(p!=v*scale for p,v in zip(proposed,originals)):return False
  else:
   if aa==0:return equivalent(p,a)
   scale=pa/aa
   if scale==0 or pb-pc!=(bb-cc)*scale:return False
  for k in a:
   if k in ['a','b','c']:continue
   wanted=a[k]
   if inequality and k=='relation'and scale<0:wanted={'lt':'gt','le':'ge','gt':'lt','ge':'le'}[wanted]
   if not equivalent(p[k],wanted,k):return False
  return True
 except(KeyError,Bad,Route,ValueError,TypeError,ZeroDivisionError,OverflowError):return False

def valid_line_proposal(original,p,canonical):
 if type(p)is not dict or set(p)!=set(canonical):return False
 if canonical['kind']in ['all-plane','empty']:return equivalent(p,canonical)
 rest={k:v for k,v in p.items()if k not in ['point1','point2']};wanted={k:v for k,v in canonical.items()if k not in ['point1','point2']}
 if not equivalent(rest,wanted):return False
 try:
  pts=[]
  for key in ['point1','point2']:
   v=p[key]
   if type(v)is not list or len(v)!=2:return False
   x,y=[num(z,True)for z in v]
   if num(original['a'])*x+num(original['b'])*y!=num(original['c']):return False
   pts.append((x,y))
  return pts[0]!=pts[1]
 except(Bad,Route,ValueError,TypeError,ZeroDivisionError,OverflowError):return False

def required(s,d):
 r=REQ[s][:]
 if s=='a74-model':
  if d.get('mode')=='count-only':r=[k for k in r if k not in ['priceX','priceY','totalPrice']]
  if d.get('mode')=='price-only':r=[k for k in r if k!='totalCount']
 return r

def evaluate(s,d):
 def out(k,a=None,why=''):return {'decision':k,'answer':a,'reason':why}
 if type(s)is not str or s not in SUBTYPES or type(d)is not dict:return out('block',why='非本有限方法')
 if any(d.get(k)is None for k in required(s,d)+['factsConfirmed']):return out('confirm',why='原量、符號、原域或坐標單位未確認，先補原條件')
 nested={'terms':['factor','coefficient','constant'],'equations':['a','b','c'],'moves':['direction','distance']}
 for field,ks in nested.items():
  if field in REQ[s]and type(d[field])is list and len(d[field])<=4:
   if any(type(v)is dict and any(v.get(k)is None for k in ks)for v in d[field]):return out('confirm',why='已確認結構內仍缺必要原量，先補清')
 if set(d)-set(REQ[s])-{'factsConfirmed','task','proposal'}:return out('block',why='未知欄位不當作已確認事實')
 if type(d['factsConfirmed'])is not bool:return out('block',why='確認狀態格式不明')
 if not d['factsConfirmed']:return out('confirm',why='原量與語意尚未確認')
 if type(d.get('task'))is not str or d['task']not in ['solve','check_proposal']:return out('block',why='非本型任務')
 try:a=compute(s,d)
 except Need as e:return out('confirm',why=str(e))
 except(Bad,Route,ValueError,TypeError,ZeroDivisionError,OverflowError)as e:return out('block',why=str(e))
 if d['task']=='check_proposal':
  p=d.get('proposal')
  if p is None:return out('confirm',a,'先提供要核對的想法，保留原題結論')
  ok=equivalent(p,a)
  if type(p)is dict and set(p)==set(a):
   if s=='a76-line':ok=valid_line_proposal(d,p,a)
   if s=='a72-model':ok=scaled_equation(p,a)
   if s=='a77-model':ok=scaled_equation(p,a,True)
   if s=='a74-model'and type(p.get('equations'))is list and len(p['equations'])==len(a['equations']):
    rest={k:v for k,v in p.items()if k!='equations'};expected={k:v for k,v in a.items()if k!='equations'};unused=list(a['equations']);ok=equivalent(rest,expected)
    for row in p['equations']:
     match=next((i for i,z in enumerate(unused)if type(row)is dict and set(row)==set(z)and scaled_equation(row,z,twoVariable=True)),None)
     if match is None:ok=False;break
     unused.pop(match)
  if not ok: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()
