PACK='grade3-one-decimal-methods'
SUBTYPES=('g3-tenths-compose', 'g3-tenths-compare', 'g3-tenths-add-subtract')
import json,pathlib,re,sys,copy,collections
from fractions import Fraction as F
REQ={
 'g3-two-level-products':['each','inner','outer'],
 'g3-change-then-share':['start','change','action','people'],
 'g3-share-then-change':['total','people','change','action'],
 'g3-estimate-product':['original','replacement','groups'],
 'g3-estimate-quotient':['original','replacement','people'],
 'g3-tenths-compose':['whole','tenths','unit'],
 'g3-tenths-compare':['first','second','unit'],
 'g3-tenths-add-subtract':['first','second','operation','unit'],
 'g3-numberline-read':['step','index'],
 'g3-numberline-compare':['step','firstIndex','secondIndex'],
 'g3-numberline-move':['step','startIndex','hops','direction']}
def out(d,a=None,reason=''):return dict(decision=d,answer=a,reason=reason)
def ni(x,lo,hi):
 if type(x)is not int or not lo<=x<=hi:raise ValueError('原數量須為本方法範圍內整數，布林不是數量')
 return x
def decimal(x):
 if type(x)is not str or not re.fullmatch(r'(?:0|[1-9][0-9]?)\.[0-9]',x):raise ValueError('原題只收0.0至99.9的一位小數文字')
 return int(x.split('.')[0])*10+int(x[-1])
def fmt(t):return str(t//10)+'.'+str(t%10)
def derived(x):
 if type(x)is int and abs(x)<10**100:return F(x)
 if type(x)is not str or len(x)>260 or not re.fullmatch(r'-?[0-9]{1,128}(?:/[0-9]{1,128}|\.[0-9]{1,128})?',x):raise ValueError('答案需精確有限數字')
 return F(x)
def norm(p,a):
 if type(p)is not dict or set(p)!=set(a):raise ValueError('答案欄位不符')
 z={}
 for k,v in a.items():
  if k in('unit','relation'):
   if type(p[k])is not str:raise ValueError('保留單位或比較方向')
   z[k]={'＞':'>','＜':'<','＝':'='}.get(p[k],p[k]) if k=='relation'else p[k]
  else:z[k]=derived(p[k])
 return z
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',reason='此有限方法不適用')
 fs=REQ[subtype_id]
 if r.get('confirmed')is not True or any(r.get(k)is None for k in fs):return out('confirm',reason='先確認缺少的原題條件，不擅自補0')
 if r.get('task')not in('solve','check_proposal')or set(r)-set(fs)-{'confirmed','task','proposal'}:return out('block',reason='任務或欄位不符')
 s=subtype_id
 try:
  if s=='g3-two-level-products':
   e=ni(r['each'],0,10);i=ni(r['inner'],0,10);o=ni(r['outer'],0,10);a={'value':e*i*o}
  elif s=='g3-change-then-share':
   n=ni(r['start'],0,1000);v=ni(r['change'],0,1000);b=ni(r['people'],1,10)
   if r['action']not in('add','subtract'):raise ValueError('先確認收到或拿走')
   mid=n+v if r['action']=='add'else n-v
   if not 0<=mid<=1000 or mid%b:raise ValueError('本型只示範1000內非負整分；其他數域或餘量需轉方法')
   a={'value':mid//b}
  elif s=='g3-share-then-change':
   n=ni(r['total'],0,1000);b=ni(r['people'],1,10);v=ni(r['change'],0,1000)
   if r['action']not in('add','subtract'):raise ValueError('每人的後續變動方向未明')
   if n%b:raise ValueError('本型先限整分，不把餘量抹去')
   ans=n//b+v if r['action']=='add'else n//b-v
   if not 0<=ans<=1000:raise ValueError('每人量須非負且1000內')
   a={'value':ans}
  elif s in('g3-estimate-product','g3-estimate-quotient'):
   n=ni(r['original'],0,999);v=ni(r['replacement'],0,1000)
   if s.endswith('product'):
    b=ni(r['groups'],1,9)
    if v%10 or abs(v-n)>5:raise ValueError('本示範用相差不超5的鄰近整十卡，不宣稱唯一估法')
    a={'estimate':v*b}
   else:
    b=ni(r['people'],1,9)
    if v%b or abs(v-n)*2>b:raise ValueError('本示範用鄰近可整分量，須相差不超半個分組單位')
    a={'estimate':v//b}
  elif s.startswith('g3-tenths-'):
   if type(r['unit'])is not str or r['unit']not in('公尺','公升','公斤'):raise ValueError('同一連續量單位須先確認；換算另路由')
   if s.endswith('compose'):a={'value':fmt(ni(r['whole'],0,99)*10+ni(r['tenths'],0,9)),'unit':r['unit']}
   else:
    x,y=decimal(r['first']),decimal(r['second'])
    if s.endswith('compare'):a={'relation':'>'if x>y else'<'if x<y else'='}
    else:
     if r['operation']not in('add','subtract'):raise ValueError('本方法只收加減')
     v=x+y if r['operation']=='add'else x-y
     if not 0<=v<=999:raise ValueError('本型結果限0.0至99.9；不抹負數或進到百位')
     a={'value':fmt(v),'unit':r['unit']}
  elif s.startswith('g3-numberline-'):
   step=ni(r['step'],1,10)
   if s.endswith('read'):a={'value':step*ni(r['index'],0,100)}
   elif s.endswith('compare'):
    x,y=ni(r['firstIndex'],0,100),ni(r['secondIndex'],0,100);a={'first':step*x,'second':step*y,'relation':'>'if x>y else'<'if x<y else'='}
   else:
    n,h=ni(r['startIndex'],0,100),ni(r['hops'],0,100)
    if r['direction']not in('right','left'):raise ValueError('向右或向左未確認')
    end=n+h if r['direction']=='right'else n-h
    if not 0<=end<=100:raise ValueError('本型數線從0起，不跨負數或本圖右端')
    a={'value':step*end}
  else:return out('block',reason='此型未實作')
 except(ValueError,TypeError,KeyError,ZeroDivisionError,OverflowError)as e:return out('block',reason=str(e))
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',a,'先提供要核對的想法')
  try:good=norm(r['proposal'],a)==norm(a,a)
  except(ValueError,TypeError,OverflowError,ZeroDivisionError):good=False
  if not good:return out('reject',a,'保留原題正解；回到具體錯誤步驟')
 return out('pass',a,'以原條件與單位逐步核對')
def verify_package(p):
 errors=[];counts=collections.Counter()
 for s in SUBTYPES:
  if collections.Counter(c['kind']for c in p['cases']if c['subtypeId']==s)!=dict(normal=8,negative=6,boundary=4,ambiguous=2,holdout=4):errors.append(s+':count')
 for c in p['cases']:
  g=evaluate(c['subtypeId'],c['input']);counts[g['decision']]+=1
  if(g['decision'],g['answer'])!=(c['expectedDecision'],c['expectedAnswer']):errors.append(c['id'])
  if c['studentFacing']!=(c['casePurpose']!='validator-guard')or c['teacherReviewed']is not False or c['appConnected']is not False:errors.append(c['id']+':flags')
 return errors,dict(counts)
def validate_pack(p):return verify_package(p)[0]
def check(path=None):
 p=json.loads(pathlib.Path(path or pathlib.Path(__file__).with_name(PACK+'.json')).read_text());errs,counts=verify_package(p);assert not errs,errs;n=0
 for c in p['cases']:
  if c['expectedAnswer']is None:continue
  r=dict(c['input'],task='check_proposal',proposal=c['expectedAnswer']);assert evaluate(c['subtypeId'],r)['decision']=='pass';n+=1
 print(json.dumps(dict(pack=PACK,cases=len(p['cases']),roundtrips=n,decisions=counts),ensure_ascii=False))
if __name__=='__main__':check(sys.argv[1]if len(sys.argv)>1 else None)
