import json,pathlib,re,sys,collections
from fractions import Fraction as F
CFG={'code': 'N-5-13', 'title': '五年級公噸與重量概數', 'modes': ['unit-convert', 'quantity-arithmetic', 'quantity-round'], 'units': {'公斤': 1, '公噸': 1000}, 'page': 33, 'lines': [2413, 2421]}
PACK='grade5-weight-measurement'
SUBTYPES={'g5-weight-unit-convert': 'unit-convert', 'g5-weight-quantity-arithmetic': 'quantity-arithmetic', 'g5-weight-quantity-round': 'quantity-round'}
REQ={'part-percent':['part','whole'],'discount':['price','tenths'],'portion-tenths':['total','tenths','unit'],'unit-convert':['amount','fromUnit','toUnit'],'quantity-arithmetic':['a','aUnit','b','bUnit','targetUnit','operation'],'quantity-round':['amount','fromUnit','toUnit','places','roundingConfirmed'],'unit-cube-layers':['perLayer','layers','completeConfirmed','unitCubeConfirmed'],'cuboid-volume':['length','width','height','shapeConfirmed','unit']}
def out(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 number(v):
 if type(v)is int and 0<=v<=1000000:return F(v)
 if type(v)is str and len(v)<=11 and re.fullmatch(r'[0-9]{1,7}(?:\.[0-9]{1,3})?',v,re.ASCII):
  n=F(v)
  if n<=1000000:return n
 raise ValueError('原量限非負整數或至多三位有限小數，最大100萬')
def derived(v):
 if type(v)is int and abs(v)<=10**64:return F(v)
 if type(v)is str and len(v)<=132 and re.fullmatch(r'-?[0-9]{1,64}(?:/[0-9]{1,64}|\.[0-9]{1,64})?',v,re.ASCII):return F(v)
 raise ValueError('衍生答案限有界精確數，不接浮點布林')
def text(v):
 v=F(v);d=v.denominator;k=0
 while d%2==0:d//=2
 while d%5==0:d//=5
 if d!=1:return str(v)
 den=v.denominator
 while den>1:den=den//2 if den%2==0 else den//5;k+=1
 # decimal scale based on both factors, not sum of exponents.
 k=0;scale=1
 while scale%v.denominator:scale*=10;k+=1
 n=v.numerator*scale//v.denominator;s=str(abs(n)).zfill(k+1)
 if k:s=s[:-k]+'.'+s[-k:];s=s.rstrip('0').rstrip('.')
 return ('-'if n<0 else'')+s
def fixed(v,places):
 n=(F(v)*10**places).numerator;s=str(n).zfill(places+1)
 return s if places==0 else s[:-places]+'.'+s[-places:]
def finite3(v):return (F(v)*1000).denominator==1
def rounded(v,places):
 factor=10**places;x=F(v)*factor;q=x.numerator//x.denominator
 if x-q>=F(1,2):q+=1
 return F(q,factor)
def equivalent(p,a):
 if type(p)is not dict or set(p)!=set(a):return False
 numeric={'ratio','percent','value'}
 try:
  return all(derived(p[k])==derived(v)if k in numeric else type(p[k])is type(v)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 out('block',r='非本有限文字解法模板')
 mode=SUBTYPES[subtype_id];fs=REQ[mode]
 if r.get('confirmed')is not True or any(r.get(k)is None for k in fs):return out('confirm',r='先確認原題缺少的量、單位或關係，不從照片自行補')
 for k in fs:
  if k.endswith('Confirmed'):
   if type(r[k])is not bool:return out('block',r='關係確認需真偽值')
   if not r[k]:return out('confirm',r='原題幾何/單位或四捨五入約定未確認，不套固定法')
 if type(r.get('task'))is not str or r['task']not in('solve','check_proposal')or set(r)-set(fs)-{'task','confirmed','proposal'}:return out('block',r='任務或欄位不符')
 try:
  if mode=='part-percent':
   part=integer(r['part'],0,10000);whole=integer(r['whole'],0,10000)
   if whole==0:return out('confirm',r='整體為0沒有可比較的比率，先核對整體定義')
   if part>whole:return out('block',r='原題比率大於1，轉N-6-8，不把合法較大比率判錯')
   f=F(part,whole);a={'ratio':str(f),'percent':fixed(rounded(100*f,1),1),'percentUnit':'%（四捨五入到小數第一位）'}
  elif mode in('discount','portion-tenths'):
   v=number(r['price'if mode=='discount'else'total']);t=integer(r['tenths'],0,10);z=v*t/10
   if not finite3(z):return out('block',r='金額/部分量需超過三位小數，轉更細精度教學')
   unit='元'if mode=='discount'else enum(r['unit'],('公斤','公升'))
   a={'ratio':str(F(t,10)),'value':text(z),'unit':unit}
  elif mode in('unit-convert','quantity-round'):
   v=number(r['amount']);u=enum(r['fromUnit'],CFG['units']);target=enum(r['toUnit'],CFG['units']);z=v*CFG['units'][u]/CFG['units'][target]
   if not finite3(z):return out('block',r='原題可換算，但本包只示範換後三位以內小數，轉更細位值模板')
   if mode=='quantity-round':z=rounded(z,integer(r['places'],0,3))
   a={'value':fixed(z,r['places'])if mode=='quantity-round'else text(z),'unit':target}
  elif mode=='quantity-arithmetic':
   aa=number(r['a']);bb=number(r['b']);u=enum(r['aUnit'],CFG['units']);v=enum(r['bUnit'],CFG['units']);target=enum(r['targetUnit'],CFG['units']);op=enum(r['operation'],('add','subtract'));z=(aa*CFG['units'][u]+(bb*CFG['units'][v]if op=='add'else-bb*CFG['units'][v]))/CFG['units'][target]
   if z<0:return out('confirm',r='減去的量比原量大，先確認敘述與比較方向')
   if not finite3(z):return out('block',r='本包結果限三位以內小數，轉更細位值模板')
   a={'value':text(z),'unit':target}
  elif mode=='unit-cube-layers':
   per=integer(r['perLayer'],0,1000);layers=integer(r['layers'],0,100);a={'value':str(per*layers),'unit':'立方公尺'}
  elif mode=='cuboid-volume':
   l=number(r['length']);w=number(r['width']);h=number(r['height']);enum(r['unit'],('公尺',))
   if min(l,w,h)<=0:return out('confirm',r='實體長方體邊長須正量，先核對標示，不把缺邊當0')
   z=l*w*h
   if not finite3(z):return out('block',r='體積結果需更細小數，轉合適精度模板')
   a={'value':text(z),'unit':'立方公尺'}
  else:return out('block',r='非本有限模板')
 except(ValueError,ZeroDivisionError,TypeError,OverflowError):return out('block',r='原量、單位或型別不在本契約')
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',a,'請提供要核對的想法')
  if not equivalent(r['proposal'],a):return out('reject',a,'錯提案不改原量；保留原題正解並核對具體錯因')
 return out('pass',a,'依已確認原量運算，不代表實測/OCR驗收')
def verify_package(p):
 errors=[];counts=collections.Counter()
 for sid in SUBTYPES:
  if collections.Counter(c['kind']for c in p['cases']if c['subtypeId']==sid)!=dict(normal=8,negative=6,boundary=4,ambiguous=2,holdout=4):errors.append(sid+':數量')
 for c in p['cases']:
  z=evaluate(c['subtypeId'],c['input']);counts[z['decision']]+=1
  if (z['decision'],z['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());es,counts=verify_package(p);assert not es,es;n=0
 for c in p['cases']:
  if c['expectedAnswer']is None:continue
  assert evaluate(c['subtypeId'],dict(c['input'],task='check_proposal',proposal=c['expectedAnswer']))['decision']=='pass',c['id'];n+=1
 print(json.dumps({'package':PACK,'cases':len(p['cases']),'roundtrips':n,'counts':counts},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)
