import json,pathlib,sys,re,collections
from fractions import Fraction
CFG={'code': 'N-3-16', 'title': '三年級重量與公克', 'large': '公斤', 'small': '公克', 'units': {'公斤': 1000, '公克': 1}, 'page': [27]}
PACK='grade3-mass-measurement'
SUBTYPES={'g3-mass-convert': 'convert', 'g3-mass-compound': 'compound', 'g3-mass-read': 'read'}
REQ={'convert':['amount','fromUnit','toUnit'],'compound':['aMajor','aMinor','bMajor','bMinor','operation'],'read':['lower','step','offset','upper','scaleConfirmed'],'duration-convert':['amount','pair','direction'],'duration-same':['a','b','unit','operation'],'duration-compound':['aMajor','aMinor','bMajor','bMinor','operation']}
def result(d,a=None,r=''):return {'decision':d,'answer':a,'reason':r}
def integer(v,lo,hi):
 if type(v)is not int or not lo<=v<=hi:raise ValueError('需本範圍內整數；布林與字串不是原量')
 return v
def enum(v,seq):
 if type(v)is not str or v not in seq:raise ValueError('未支持的單位或操作；原題應轉合適模板')
 return v
def derived(v):
 if type(v)is int and abs(v)<=10**64:return Fraction(v)
 if type(v)is str and len(v)<=132 and re.fullmatch(r'-?\d{1,64}(?:/\d{1,64}|\.\d{1,64})?',v,re.ASCII):return Fraction(v)
 raise ValueError('答案需有限精確數，非浮點/布林')
def equal(p,a):
 if type(p)is not dict or set(p)!=set(a):return False
 try:return all(derived(p[k])==derived(v)if type(v)is int else type(p[k])is str and p[k]==v for k,v in a.items())
 except(ValueError,ZeroDivisionError,TypeError):return False
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 result('block',r='非本有限模板')
 mode=SUBTYPES[subtype_id];req=REQ[mode]
 if r.get('confirmed')is not True or any(r.get(k)is None for k in req):return result('confirm',r='先確認缺少的原量、單位或刻度條件，不猜原圖')
 if mode=='read':
  if type(r['scaleConfirmed'])is not bool:return result('block',r='刻度確認需布林')
  if not r['scaleConfirmed']:return result('confirm',r='先核對等距刻度、單位及指示位置')
 if type(r.get('task'))is not str or r['task']not in('solve','check_proposal')or set(r)-set(req)-{'confirmed','task','proposal'}:return result('block',r='任務或欄位不符')
 try:
  if mode=='convert':
   u=enum(r['fromUnit'],CFG['units']);v=enum(r['toUnit'],CFG['units']);n=integer(r['amount'],0,9999)
   total=n*CFG['units'][u]
   if total>9999:return result('block',r='本包限不足10個大單位；原題可另轉更高量級模板')
   q,rem=divmod(total,CFG['units'][v]);a={'whole':q,'remainder':rem}
  elif mode in('compound','duration-compound'):
   base=60 if mode.startswith('duration')else 1000;hi=99 if base==60 else 9
   am=integer(r['aMajor'],0,hi);an=integer(r['aMinor'],0,base-1);bm=integer(r['bMajor'],0,hi);bn=integer(r['bMinor'],0,base-1);op=enum(r['operation'],('add','subtract'))
   if base==60 and ((op=='add'and an+bn>=60)or(op=='subtract'and an<bn)):return result('block',r='此題需時分進退位，轉四年級時間模板；不拒絕原問題')
   total=am*base+an+(1 if op=='add'else-1)*(bm*base+bn)
   if total<0:return result('confirm',r='原敘述會得負的量；先確認比較方向或減去的量')
   if total>(5999 if base==60 else 9999):return result('block',r='超出本有限量級，轉合適模板')
   q,rem=divmod(total,base);a={'major':q,'minor':rem}
  elif mode=='read':
   lo=integer(r['lower'],0,9999);step=integer(r['step'],1,1000);idx=integer(r['offset'],0,20);up=integer(r['upper'],0,9999)
   if up<lo or(up-lo)%step or lo+idx*step>up:return result('confirm',r='標數、格距與指示位置不相容，先核對原圖')
   a={'value':lo+idx*step,'unit':CFG['small']}
  elif mode=='duration-convert':
   n=integer(r['amount'],0,9999);pair=enum(r['pair'],('日-時','時-分','分-秒'));direction=enum(r['direction'],('large-to-small','small-to-large'));b=24 if pair=='日-時'else 60
   if direction=='large-to-small':
    if n*b>9999:return result('block',r='超出一萬以內量級，轉合適模板')
    a={'whole':n*b,'remainder':0}
   else:q,rem=divmod(n,b);a={'whole':q,'remainder':rem}
  elif mode=='duration-same':
   aa=integer(r['a'],0,9999);bb=integer(r['b'],0,9999);u=enum(r['unit'],('日','時','分','秒'));op=enum(r['operation'],('add','subtract'));n=aa+(bb if op=='add'else-bb)
   if n<0:return result('confirm',r='時間量不能負；先核對已過/剩下的敘述方向')
   if n>9999:return result('block',r='超出本包一萬以內量級')
   a={'value':n,'unit':u}
  else:return result('block',r='非本有限模板')
 except(ValueError,TypeError,OverflowError,ZeroDivisionError):return result('block',r='數值、單位或型別不在已明定契約')
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return result('confirm',a,'請提供想核對的答案')
  if not equal(r['proposal'],a):return result('reject',a,'保留原題正解，依原單位及已知量逐步檢查錯提案')
 return result('pass',a,'只依已確認數值條件；非實測/OCR驗證')
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+':種類數')
 for c in p['cases']:
  g=evaluate(c['subtypeId'],c['input']);counts[g['decision']]+=1
  if g['decision']!=c['expectedDecision']or g['answer']!=c['expectedAnswer']:errors.append(c['id']+':結果')
  if c['teacherReviewed']is not False or c['appConnected']is not False or c['studentFacing']!=(c['casePurpose']!='validator-guard'):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());err,counts=verify_package(p);assert not err,err;rt=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',(c['id'],r);rt+=1
 print(json.dumps({'package':PACK,'cases':len(p['cases']),'decisions':counts,'roundtrips':rt},ensure_ascii=False))
if __name__=='__main__':
 if len(sys.argv)>1 and sys.argv[1]=='evaluate':print(json.dumps(evaluate(sys.argv[2],json.loads(sys.argv[3])),ensure_ascii=False))
 else:check(sys.argv[1]if len(sys.argv)>1 else None)
