PACK='grade6-pattern-count-assumption'
SUBTYPES=('g6-linked-tables', 'g6-exclusive-outfits', 'g6-chicken-rabbit')
import json,pathlib,re,sys,collections
from fractions import Fraction as F
REQ={'g6-remaining-juice-share':['total','drunk','cups'],'g6-fraction-mass-pack':['mass','portion','perBag'],'g6-budget-three-step':['budget','price','count','shares','estimatePrice'],'g6-linked-tables':['tables'],'g6-exclusive-outfits':['topsA','bottomsA','topsB','bottomsB'],'g6-chicken-rabbit':['animals','feet'],'g6-sum-difference-length':['sum','difference'],'g6-future-age-backtrack':['futureSum','years','difference'],'g6-water-speed-relations':['down','up','sameConditions']}
def out(decision,answer=None,reason=''):return dict(decision=decision,answer=answer,reason=reason)
def q(v):
 if type(v)is int:r=F(v)
 elif type(v)is str and len(v)<=24 and re.fullmatch(r'(?:0|[1-9][0-9]*)(?:/[1-9][0-9]*|\.[0-9]{1,3})?',v):r=F(v)
 else:raise ValueError('原數量須是已確認整數或精確分小數，不收布林及浮點近似')
 if not 0<=r<=1000 or r.denominator>1000:raise ValueError('超出本有限數域，保留原題轉方法')
 return r
def integer(v,lo,hi):
 if type(v)is not int or not lo<=v<=hi:raise ValueError('整數量或個數超出本型範圍')
 return v
def norm(p,a):
 if type(p)is not dict or set(p)!=set(a):raise ValueError('答案欄位')
 z={}
 for k,v in a.items():
  x=p[k]
  if k=='unit':
   if type(x)is not str or x!=v:raise ValueError('答案單位')
   z[k]=x;continue
  if type(x)is int and abs(x)<10**100:z[k]=F(x)
  elif type(x)is str and len(x)<=260 and re.fullmatch(r'-?[0-9]{1,128}(?:/[1-9][0-9]{0,127}|\.[0-9]{1,128})?',x):z[k]=F(x)
  else:raise ValueError('答案需精確數值')
 return z
def evaluate(s,r):
 if type(s)is not str or s not in SUBTYPES or type(r)is not dict:return out('block',reason='有限子型不適用')
 if r.get('confirmed')is not True or any(r.get(k)is None for k in REQ[s]):return out('confirm',reason='補清同一題原條件，不猜數或單位')
 if r.get('task')not in('solve','check_proposal')or set(r)-set(REQ[s])-{'confirmed','task','proposal'}:return out('block',reason='任務或欄位不符')
 try:
  if s=='g6-remaining-juice-share':
   t,d=q(r['total']),q(r['drunk']);n=integer(r['cups'],1,20)
   if d>t:raise ValueError('喝掉量大於原量，先核對條件，不能造負剩量')
   a={'perCup':str((t-d)/n),'unit':'公升'}
  elif s=='g6-fraction-mass-pack':
   m,f,p=q(r['mass']),q(r['portion']),q(r['perBag'])
   if f>1 or not p:raise ValueError('所取部分需0至1且每包量正')
   bags=m*f/p
   if bags.denominator!=1:raise ValueError('本型只完整分裝，不默丟剩料；有餘量轉另一教法')
   a={'bags':int(bags),'unit':'包'}
  elif s=='g6-budget-three-step':
   b,p=q(r['budget']),q(r['price']);n=integer(r['count'],1,20);h=integer(r['shares'],1,20);e=integer(r['estimatePrice'],0,1000)
   if abs(p-e)>1:raise ValueError('指定粗估卡須與原價相差不超1元')
   cost=p*n
   if cost>b or e*n>b:raise ValueError('支出或估計支出超預算，核對或轉其他教法')
   a={'perShare':str((b-cost)/h),'estimate':str((b-e*n)/h),'unit':'元'}
  elif s=='g6-linked-tables':a={'seats':2*integer(r['tables'],1,50)+2,'unit':'個'}
  elif s=='g6-exclusive-outfits':
   ta,ba,tb,bb=(integer(r[k],0,12)for k in REQ[s]);a={'ways':ta*ba+tb*bb,'unit':'套'}
  elif s=='g6-chicken-rabbit':
   n=integer(r['animals'],0,100);feet=integer(r['feet'],0,400);extra=feet-2*n
   if extra<0 or extra>2*n or extra%2:raise ValueError('已確認雞兔條件無整隻相容解，核對原題而非硬湊或怪學生')
   rabbits=extra//2;a={'chickens':n-rabbits,'rabbits':rabbits,'unit':'隻'}
  elif s=='g6-sum-difference-length':
   t,d=q(r['sum']),q(r['difference'])
   if d>t:raise ValueError('差大於和，條件不相容，先核對')
   a={'longer':str((t+d)/2),'shorter':str((t-d)/2),'unit':'公尺'}
  elif s=='g6-future-age-backtrack':
   t=integer(r['futureSum'],0,240);y=integer(r['years'],0,30);d=integer(r['difference'],0,100);current=t-2*y
   if current<d or(current-d)%2:raise ValueError('本型整歲/現在非負，條件不合先核對，不造負年齡')
   a={'older':(current+d)//2,'younger':(current-d)//2,'unit':'歲'}
  else:
   if r['sameConditions']is not True:return out('confirm',reason='先確認同船、相同靜水速度及同一水流速度，不能直接套和差')
   down,up=q(r['down']),q(r['up'])
   if down<up:raise ValueError('同條件順流不應比逆流慢，核對已確認條件，不造負流速')
   a={'still':str((down+up)/2),'current':str((down-up)/2),'unit':'公里/小時'}
 except(ValueError,TypeError,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,ZeroDivisionError,OverflowError):good=False
  if not good:return out('reject',a,'保留原題正解，定位量角色或具體計算步')
 return out('pass',a,'沿量關係計算並代回所有原條件')
def validate_pack(p):
 errors=[]
 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'])
  if(g['decision'],g['answer'])!=(c['expectedDecision'],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
def main():
 path=pathlib.Path(sys.argv[1])if len(sys.argv)>1 else pathlib.Path(__file__).with_name(PACK+'.json');p=json.loads(path.read_text());errors=validate_pack(p);print(json.dumps({'pack':PACK,'cases':len(p['cases']),'errors':errors,'teacherReviewed':False,'appConnected':False},ensure_ascii=False));return bool(errors)
if __name__=='__main__':sys.exit(main())
