import json,pathlib,sys,re,collections
from fractions import Fraction as F
PACK='grade5-laws-distribution';SUBTYPES=['r52-distribute', 'r52-chain-division', 'r52-product-quotient']
REQ={'r52-distribute':['groups','first','second','operation','unit'],'r52-chain-division':['total','firstGroups','subgroups','structure','unit'],'r52-product-quotient':['perBatch','batches','people','unit'],'r53-geometry-symbols':['shape','symbols','values','lengthUnit'],'r53-fraction-symbols':['wholeSymbol','fractionSymbol','targetSymbol','wholeValue','fractionValue','unit']}
SHAPES={'rectangle':(['length','width'],'S',1,2),'triangle':(['base','height'],'S',2,2),'parallelogram':(['base','height'],'S',1,2),'cube':(['side','side','side'],'V',1,3),'cuboid':(['length','width','height'],'V',1,3)}
class Bad(Exception):pass
class Need(Exception):pass
class Route(Exception):pass

def number(v,answer=False):
 b=10**256 if answer else 10**6
 if type(v)is int:
  if abs(v)>b: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)>b or not answer and q.denominator>10000:raise Route('數量或細分程度超出本有限模板，轉別法')
 return q

def nat(v,positive=False):
 if type(v)is not int:raise Bad('本整數規律型的原量需JSON整數，不收真假值')
 if abs(v)>1000000:raise Route('較大數量轉別法，不先轉巨大字串')
 if v<0 or positive and v==0:raise Bad('本型自然數量或除數條件不符；除數不能0')
 return v

def enum(v,xs):
 if type(v)is not str or v not in xs:raise Bad('量的角色、單位或式子結構不在本型')
 return v

def symbol(v):
 if type(v)is not str or not re.fullmatch('[A-Za-z]',v,re.ASCII):raise Bad('本初步符號型使用一個明定英文字母，不解析任意符號式')
 return v

def pos(v):
 q=number(v)
 if q<=0:raise Need('幾何長度需為正，先核對零/負長度是否抄錯；代數式另路由')
 return q

def geometry(d):
 shape=enum(d['shape'],SHAPES);roles,out,div,dim=SHAPES[shape];sy=d['symbols'];vs=d['values'];u=enum(d['lengthUnit'],['公分','公尺'])
 if type(sy)is not dict or type(vs)is not dict:raise Bad('符號與數量需有明確對照，不推任意文句')
 if set(sy)!=set(roles):raise Bad('量名與既定公式不一致，不能把斜邊當垂直高')
 names=[symbol(sy[k])for k in roles]
 if out in names:raise Need('結果符號與已知量符號重用，需確認原約定，不能暗自換義')
 if set(vs)!=set(names):raise Bad('代入值必須和已定義符號逐一對應，不接受額外未定義字母')
 vals=[pos(vs[n])for n in names];v=F(1)
 for a in vals:v*=a
 return {'outputSymbol':out,'formulaFactors':names,'divideBy':str(div),'value':str(v/div),'unit':('平方'if dim==2 else'立方')+u}

def compute(s,d):
 if s=='r52-distribute':
  g,a,b=[nat(d[k])for k in ['groups','first','second']];op=enum(d['operation'],['add','subtract']);u=enum(d['unit'],['枝','元','公尺'])
  if op=='subtract'and a<b:raise Route('本生活剩量型先限每組移去量不超原量；負數轉後續方法')
  return {'firstProduct':str(g*a),'secondProduct':str(g*b),'value':str(g*(a+b if op=='add'else a-b)),'unit':u}
 if s=='r52-chain-division':
  a=nat(d['total']);b,c=nat(d['firstGroups'],True),nat(d['subgroups'],True);u=enum(d['unit'],['公尺','公升']);structure=enum(d['structure'],['left-chain','divide-a-quotient'])
  if structure!='left-chain':raise Route('正式範圍不做a÷(b÷c)去括號；保留原括號轉別法，不當成連除')
  return {'afterFirst':str(F(a,b)),'combinedDivisor':str(b*c),'value':str(F(a,b*c)),'unit':u+'/份'}
 if s=='r52-product-quotient':
  a,b,c=nat(d['perBatch']),nat(d['batches']),nat(d['people'],True);u=enum(d['unit'],['公尺','公升']);g=__import__('math').gcd(a,c);aa,cc=a//g,c//g
  # Exact integer cancellation first; not a change of the purchase/stock event order.
  return {'cancelFactor':str(g),'reducedPerBatch':str(aa),'reducedDivisor':str(cc),'value':str(F(a*b,c)),'unit':u+'/人'}
 if s=='r53-geometry-symbols':return geometry(d)
 if s=='r53-fraction-symbols':
  w,f,t=[symbol(d[k])for k in ['wholeSymbol','fractionSymbol','targetSymbol']]
  if len({w,f,t})!=3:raise Need('全量、倍數與結果的符號重用，需先確認原符號約定')
  whole,fraction=number(d['wholeValue']),number(d['fractionValue']);u=enum(d['unit'],['公尺','公斤','公升'])
  if whole<0 or fraction<0:raise Route('此五年級量與分數倍模板不處理負量，轉後續方法')
  return {'outputSymbol':t,'formulaFactors':[w,f],'divideBy':'1','value':str(whole*fraction),'unit':u}
 raise Bad('非本型')

NUMERIC={'firstProduct','secondProduct','value','afterFirst','combinedDivisor','cancelFactor','reducedPerBatch','reducedDivisor','divideBy'}
def equivalent(p,a):
 if type(p)is not dict or set(p)!=set(a):return False
 try:
  for k,v in a.items():
   if k=='formulaFactors':
    if type(p[k])is not list or len(p[k])!=len(v)or any(type(x)is not str or len(x)!=1 for x in p[k])or collections.Counter(p[k])!=collections.Counter(v):return False
   elif k in NUMERIC:
    if number(p[k],True)!=number(v,True):return False
   elif type(p[k])is not str or p[k]!=v:return False
  return True
 except(Bad,Route,ValueError,TypeError,OverflowError,ZeroDivisionError):return False

def valid_product_quotient_proposal(original,proposal,canonical):
 """Canonical explanation uses gcd; any exact common-factor route is valid."""
 if type(proposal)is not dict or set(proposal)!=set(canonical):return False
 try:
  # Use the separate derived-number parser, retaining strict typed/size guards.
  k=number(proposal['cancelFactor'],True)
  aa=number(proposal['reducedPerBatch'],True)
  cc=number(proposal['reducedDivisor'],True)
  result=number(proposal['value'],True)
  if k.denominator!=1 or k<=0 or aa.denominator!=1 or aa<0 or cc.denominator!=1 or cc<=0:return False
  a,c=original['perBatch'],original['people']
  if c<=0 or a%k.numerator or c%k.numerator:return False
  if aa*k!=a or cc*k!=c:return False
  if result!=number(canonical['value'],True) or aa*original['batches']/cc!=result:return False
  return type(proposal['unit'])is str and proposal['unit']==canonical['unit']
 except(Bad,Route,ValueError,TypeError,OverflowError,ZeroDivisionError):return False

def evaluate(s,d):
 def out(k,a=None,reason=''):return {'decision':k,'answer':a,'reason':reason}
 if type(s)is not str or s not in SUBTYPES or type(d)is not dict:return out('block',reason='非本有限文字方法')
 if any(d.get(k)is None for k in REQ[s]+['factsConfirmed']):return out('confirm',reason='必要原量、符號或角色未明，先補原條件')
 if s=='r53-geometry-symbols'and type(d['shape'])is str and d['shape']in SHAPES and type(d['symbols'])is dict:
  roles=SHAPES[d['shape']][0]
  if any(d['symbols'].get(k)is None for k in roles):return out('confirm',reason='符號對照還缺必要量名，先確認')
  if type(d['values'])is dict and any(type(d['symbols'][k])is str and re.fullmatch('[A-Za-z]',d['symbols'][k],re.ASCII) and d['values'].get(d['symbols'][k])is None for k in roles):return out('confirm',reason='必要符號的數量還缺，先補清，不猜圖')
 if set(d)-set(REQ[s])-{'task','proposal','factsConfirmed'}:return out('block',reason='未知欄位，不當作已確認原條件')
 if type(d['factsConfirmed'])is not bool:return out('block',reason='確認狀態需明確真假值')
 if not d['factsConfirmed']:return out('confirm',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(Bad,Route,ValueError,TypeError,OverflowError,ZeroDivisionError)as e:return out('block',reason=str(e))
 if d['task']=='check_proposal':
  if d.get('proposal')is None:return out('confirm',a,'先提供要核對的想法，保留原題正解')
  if s=='r52-product-quotient':
   ok=valid_product_quotient_proposal(d,d['proposal'],a)
  else:ok=equivalent(d['proposal'],a)
  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()
