import json,re,sys
from fractions import Fraction as F
SUBTYPES=['scientific-encode', 'scientific-decode', 'scientific-role']
REQ={'power-expand':['base','exponent','signScope'],'power-zero':['base','exponent'],'power-compare':['base','leftExponent','rightExponent'],'law-same':['base','m','n','operation'],'law-nested':['base','m','n'],'law-product':['a','b','exponent'],'scientific-encode':['value'],'scientific-decode':['coefficient','exponent'],'scientific-role':['coefficient','exponent','role']}
class Guard(Exception):pass

def num(x,derived=False):
 if type(x)is int:
  if abs(x)>10**(400 if derived else 6):raise Guard('數量超出有限範圍')
  return F(x)
 if type(x)is not str or len(x)>(810 if derived else 44):raise Guard('必須是有界整數、有限小數或分數文字')
 pat=r'-?\d{1,400}(?:/\d{1,400}|\.\d{1,400})?' if derived else r'-?\d{1,22}(?:/\d{1,22}|\.\d{1,22})?'
 if not re.fullmatch(pat,x):raise Guard('不是允許的精確數字格式')
 try:q=F(x)
 except (ValueError,ZeroDivisionError):raise Guard('分母不能為0')
 if abs(q)>10**(400 if derived else 22):raise Guard('數量超出有限範圍')
 return q

def integer(x,low=0,high=12):
 if type(x)is not int or not low<=x<=high:raise Guard('指數必須在明定整數範圍，不接受巨大指數文字')
 return x

def st(q):return str(F(q))
def human(q):
 q=F(q);d=q.denominator;t=0
 while d%2==0:d//=2
 while d%5==0:d//=5
 if d!=1:return str(q)
 scale=1
 while scale%q.denominator:scale*=10;t+=1
 n=q.numerator*(scale//q.denominator);sign='−' if n<0 else '';n=abs(n)
 if not t:return sign+str(n)
 z=str(n).zfill(t+1);return sign+z[:-t]+'.'+z[-t:]
def powq(a,n):
 if a==0 and n==0:raise Guard('本模板不定義0的0次方')
 return a**n

def normalize(a,model):
 if type(a)is not dict or set(a)!=set(model):raise Guard('提案欄位必須完整且無額外欄')
 out={}
 for k,v in model.items():
  if k in ['value','left','right','coefficient']:out[k]=st(num(a[k],True))
  elif k in ['exponent','combinedExponent']:
   if type(a[k])is not int or abs(a[k])>144:raise Guard('答案指數須為有限整數')
   out[k]=a[k]
  elif type(v)is bool:
   if type(a[k])is not bool:raise Guard('判斷須為真假值')
   out[k]=a[k]
  else:
   if type(a[k])is not str:raise Guard('答案角色須為文字')
   out[k]=a[k]
 return out

def compute(s,d):
 steps=[]
 if s.startswith('power') or s.startswith('law'):
  if s=='law-product':
   a,b=num(d['a']),num(d['b']);n=integer(d['exponent']);
   if any(abs(q.numerator)>100 or q.denominator>100 for q in (a,b)):raise Guard('積的兩底數既約分子分母上限100')
   v=powq(a*b,n);va=powq(a,n);vb=powq(b,n)
   ans={'value':st(v)};steps=[f'先算積：{st(a)}×{st(b)}＝{st(a*b)}。',f'積的{n}次方可寫成{st(a)}的{n}次方乘{st(b)}的{n}次方。',f'兩部分分別為{st(va)}與{st(vb)}，乘得{st(v)}。',f'直接從積驗算：({st(a*b)})的{n}次方＝{st(v)}。']
  else:
   a=num(d['base'])
   if abs(a.numerator)>100 or a.denominator>100:raise Guard('本教學模板底數既約分子絕對值及分母不超過100')
   if s=='power-expand':
    n=integer(d['exponent']);scope=d['signScope']
    if type(scope)is not str or scope not in ['inside','outside']:raise Guard('需確認負號是在次方內或外')
    if a<0:raise Guard('此槽輸入非負大小，負號範圍由已確認括號決定')
    v=powq(-a,n) if scope=='inside' else -powq(a,n)
    factors='×'.join([f'({st(-a)})' if scope=='inside' else st(a)]*n) if n else '1（非零底數的零次方）'
    ans={'value':st(v)};steps=[f'負號在'+('括號內，底數是'+st(-a) if scope=='inside' else '次方外，先算'+st(a)+'的次方')+'。',f'連乘部分：{factors}。',f'依負因數個數或外部負號，得到{st(v)}。',f'再次依原括號範圍連乘，結果為{st(v)}，不是底數乘指數。']
   elif s=='power-zero':
    n=integer(d['exponent']);v=powq(a,n);ans={'value':st(v)}
    steps=[f'底數為{st(a)}，指數為{n}。',('指數為0且底數不為0，所以值是1。' if n==0 else f'將{st(a)}連乘{n}次，得到{st(v)}。'),f'核對原式，值為{st(v)}；零次方規則不可套在0⁰。']
   elif s=='power-compare':
    m,n=integer(d['leftExponent']),integer(d['rightExponent']);l,r=powq(a,m),powq(a,n);rel='>' if l>r else '<' if l<r else '=';ans={'left':st(l),'right':st(r),'relation':rel}
    steps=[f'先看底數{st(a)}的正負與大小，不直接用指數大小猜答案。',f'左式{st(a)}的{m}次方＝{st(l)}。',f'右式{st(a)}的{n}次方＝{st(r)}。',f'以實際值比較：{st(l)} {rel} {st(r)}。']
   else:
    m,n=integer(d['m']),integer(d['n'])
    if s=='law-same':
     op=d['operation']
     if type(op)is not str or op not in ['multiply','divide']:raise Guard('需確認乘法或除法')
     if op=='divide' and (a==0 or m<n):raise Guard('除式底數非0且本碼限定前指數不少於後指數')
     x,y=powq(a,m),powq(a,n);e=m+n if op=='multiply' else m-n;v=x*y if op=='multiply' else x/y
     steps=[f'確認同底數{st(a)}'+('且除數非0、前指數不少於後指數。' if op=='divide' else '，乘法才可合併。'),f'新指數＝{m}'+('＋' if op=='multiply' else '−')+f'{n}＝{e}。',f'所以值＝({st(a)})的{e}次方＝{st(v)}。',f'原量驗算：{st(x)}'+('×' if op=='multiply' else '÷')+f'{st(y)}＝{st(v)}。']
    else:
     x=powq(a,m);e=m*n;v=powq(x,n);steps=[f'內層({st(a)})的{m}次方＝{st(x)}。',f'外層是整個內層連乘{n}次，因此指數為{m}×{n}＝{e}。',f'({st(a)})的{e}次方＝{st(v)}。',f'直接驗算({st(x)})的{n}次方＝{st(v)}。']
    ans={'value':st(v),'combinedExponent':e}
 else:
  if s=='scientific-encode':
   v=num(d['value'])
   if v<=0:raise Guard('本碼科學記號只處理正數')
   # Only terminating decimal, finite magnitude/precision.
   den=v.denominator
   for p in (2,5):
    while den%p==0:den//=p
   if den!=1:raise Guard('本包只涵蓋有限小數，不處理循環小數')
   c=v;e=0
   while c>=10:c/=10;e+=1
   while c<1:c*=10;e-=1
   if not -20<=e<=20:raise Guard('本包十次方範圍為−20到20')
   ans={'coefficient':st(c),'exponent':e};steps=[f'原正數為{human(v)}。',f'以10倍位值調整，係數成{human(c)}，符合1≤係數<10。',f'保留原值所需十次方為{e}，所以寫成{human(c)}×10^({e})。',f'乘回驗算：{human(c)}×10^({e})＝{human(v)}。']
  else:
   c=num(d['coefficient']);e=integer(d['exponent'],-20,20)
   if c<=0:raise Guard('本碼只處理正係數正數')
   v=c*(F(10)**e);standard=1<=c<10
   if s=='scientific-decode':ans={'value':st(v)}
   else:
    role=d['role']
    if type(role)is not str or role not in ['value','standard']:raise Guard('需確認問等值數或標準形式')
    ans={'value':st(v),'isStandard':standard} if role=='standard' else {'value':st(v)}
   steps=[f'已知{human(c)}×10^({e})。',f'十的{e}次方＝{human(F(10)**e)}；'+('用乘法放大。' if e>0 else '乘1維持原值，不放大也不縮小。' if e==0 else '相當於除以'+str(10**(-e))+'。'),f'原數＝{human(c)}×{human(F(10)**e)}＝{human(v)}。',f'係數{human(c)}'+('符合' if standard else '不符合')+'1≤係數<10；等值不代表已是標準形式。']
 return ans,steps

def evaluate(s,d):
 try:
  if s not in SUBTYPES:raise Guard('未知子型')
  if type(d)is not dict:raise Guard('條件必須是結構資料')
  if any(k not in d or d[k] is None for k in REQ[s]+['confirmedGiven']):return {'decision':'confirm','answer':None,'reason':'請補充缺少的原題條件，不自行猜值。'}
  if set(d)-set(REQ[s]+['confirmedGiven','task','proposal']):raise Guard('含未定義條件欄位')
  if d['confirmedGiven'] is not True:
   if d['confirmedGiven'] is False:return {'decision':'confirm','answer':None,'reason':'請先確認原式、括號與所求。'}
   raise Guard('確認狀態須為真假值')
  task=d.get('task','solve')
  if type(task)is not str or task not in ['solve','verify_proposal']:raise Guard('未知任務')
  ans,steps=compute(s,d)
  if task=='verify_proposal':
   try:ok=normalize(d.get('proposal'),ans)==ans
   except Guard:ok=False
   return {'decision':'pass' if ok else 'reject','answer':ans,'accepted':ok,'steps':steps,'reason':'核對原式、值與要求的形式；錯誤提案不取代原正解。'}
  return {'decision':'pass','answer':ans,'steps':steps}
 except Guard as e:return {'decision':'reject','answer':None,'reason':str(e)}

def main():
 import pathlib
 p=pathlib.Path(__file__).with_name(pathlib.Path(__file__).name.replace('check-','').replace('.py','.json'))
 pack=json.load(open(p));n=0
 for c in pack['cases']:
  r=evaluate(c['subtypeId'],c['input']);assert r['decision']==c['expectedDecision'] and r['answer']==c['expectedAnswer'],(c['id'],r);n+=1
 print(json.dumps({'cases':n,'passed':True}))
if __name__=='__main__':main()
