import pathlib,json,sys,re,collections
from fractions import Fraction as F
CFG={'code': 'S-6-1', 'title': '六年級放大縮小的邊角與類別', 'modes': ['corresponding-length', 'angle-shape-invariant'], 'page': 36, 'lines': [2754, 2766]}
PACK='grade6-scale-relations'
SUBTYPES={'g6-scale-corresponding-length': 'corresponding-length', 'g6-scale-angle-shape-invariant': 'angle-shape-invariant'}
UNITS={'公尺':('length',1),'公分':('length',F(1,100)),'公里':('length',1000),'公斤':('mass',1),'公克':('mass',F(1,1000)),'公升':('capacity',1),'毫升':('capacity',F(1,1000)),'時':('time',1),'分':('time',F(1,60)),'秒':('time',F(1,3600)),'元':('money',1),'份':('count',1)}
REQ={'ratio-value':['a','b','unitA','unitB'],'equal-ratios':['a','b','c'],'ratio-partition':['total','firstParts','secondParts','unit'],'uniform-motion':['target','distanceUnit','timeUnit','uniformConfirmed'],'speed-unit-convert':['speed','lengthPair','timePair'],'weighted-speed':['distances','times','distanceUnit','timeUnit','allSegmentsConfirmed'],'find-comparison':['base','ratio','unit'],'recover-base':['comparison','ratio','unit'],'exchange-base':['oldRatio','oldDirectionConfirmed'],'corresponding-length':['originalLength','factor','unit','correspondenceConfirmed'],'angle-shape-invariant':['shape','originalAngle','factor','correspondenceConfirmed','uniformScaleConfirmed']}
MOTION={'distance':('speed','time'),'speed':('distance','time'),'time':('distance','speed')}
LPAIR={'公里-公尺':1000,'公里-公分':100000,'公尺-公分':100};TPAIR={'時-分':60,'時-秒':3600,'分-秒':60}
def out(d,a=None,r=''):return {'decision':d,'answer':a,'reason':r}
def original(v):
 if type(v)is int and 0<=v<=1000000:return F(v)
 if type(v)is str and len(v)<=20 and re.fullmatch(r'[0-9]{1,7}(?:/[0-9]{1,4}|\.[0-9]{1,3})?',v,re.ASCII):
  n=F(v)
  if 0<=n<=1000000 and n.denominator<=1000:return n
 raise ValueError('原量限0..100萬、分母至1000的簡單精確數；不接浮點布林')
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 enum(v,seq):
 if type(v)is not str or v not in seq:raise ValueError('單位/選項不在本模板')
 return v
def integer(v,lo,hi):
 if type(v)is not int or not lo<=v<=hi:raise ValueError('整數欄位不符')
 return v
def equivalent(p,a):
 if type(p)is not dict or set(p)!=set(a):return False
 numeric={'value','first','second','ratio','angle'}
 try:return all(derived(p[k])==derived(v)if k in numeric and v!='無頂角'else type(p[k])is type(v)and p[k]==v for k,v in a.items())
 except(ValueError,TypeError,ZeroDivisionError):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 mode=='angle-shape-invariant'and r.get('originalAngle')is None and type(r.get('shape'))is str:
  if r['shape']in('長方形','正方形'):r=dict(r,originalAngle=90)
  elif r['shape']=='圓':r=dict(r,originalAngle='無頂角')
 if r.get('confirmed')is not True or any(r.get(k)is None for k in fs):return out('confirm',r='原題量、單位或對應關係缺少，先確認不猜圖')
 if mode=='uniform-motion':
  if any(k in r and r[k]is None for k in('distance','time','speed')):return out('confirm',r='已提供的原量欄缺數，先確認')
  if type(r['target'])is not str or r['target']not in MOTION:return out('block',r='只求距離/速度/時間其中一量')
  fs+=list(MOTION[r['target']])
  if any(r.get(k)is None for k in fs):return out('confirm',r='先補齊另兩個原量')
 if mode=='weighted-speed':
  for k in('distances','times'):
   if type(r[k])is list and any(x is None for x in r[k]):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=='ratio-value':
   a,b=original(r['a']),original(r['b']);ua=enum(r['unitA'],UNITS);ub=enum(r['unitB'],UNITS)
   if not b:return out('confirm',r='後項為0無法定比值，先確認比的順序與原量')
   same=UNITS[ua][0]==UNITS[ub][0];z=a*UNITS[ua][1]/(b*UNITS[ub][1])if same else a/b
   ans={'value':str(z),'unit':'無單位'if same else ua+'/'+ub}
  elif mode=='equal-ratios':
   a,b,c=(original(r[k])for k in('a','b','c'))
   if not a or not b or not c:return out('confirm',r='相等比兩項需正；新前項為0會得0:0而無定比值，先核對題意')
   ans={'value':str(b*(c/a))}
  elif mode=='ratio-partition':
   total=original(r['total']);a=original(r['firstParts']);b=original(r['secondParts']);unit=enum(r['unit'],('公斤','公升','公尺'))
   if not a or not b:return out('confirm',r='本型兩部分均正份數；0份的分配語意先確認')
   one=total/(a+b);ans={'first':str(one*a),'second':str(one*b),'unit':unit}
  elif mode=='uniform-motion':
   du=enum(r['distanceUnit'],('公里','公尺','公分'));tu=enum(r['timeUnit'],('時','分','秒'));target=r['target'];a,b=(original(r[k])for k in MOTION[target])
   if target=='distance':z=a*b;unit=du
   else:
    if not b:return out('confirm',r='除數速度/時間是0，先確認情境；不能直接相除')
    z=a/b;unit=du+'/'+tu if target=='speed'else tu
   ans={'value':str(z),'unit':unit}
  elif mode=='speed-unit-convert':
   v=original(r['speed']);lp=enum(r['lengthPair'],LPAIR);tp=enum(r['timePair'],TPAIR);ans={'value':str(v*LPAIR[lp]/TPAIR[tp]),'unit':lp.split('-')[1]+'/'+tp.split('-')[1]}
  elif mode=='weighted-speed':
   ds,ts=r['distances'],r['times'];du=enum(r['distanceUnit'],('公里','公尺','公分'));tu=enum(r['timeUnit'],('時','分','秒'))
   if type(ds)is not list or type(ts)is not list or len(ds)!=len(ts)or not 2<=len(ds)<=4:return out('block',r='需2到4段、距離時間一一對應清單')
   ds=[original(v)for v in ds];ts=[original(v)for v in ts]
   if any(v<=0 for v in ts):return out('confirm',r='每段時間需正；0時間段的情境先核對')
   ans={'value':str(sum(ds)/sum(ts)),'unit':du+'/'+tu}
  elif mode in('find-comparison','recover-base'):
   unit=enum(r['unit'],('公斤','公升','公尺','元'));ratio=original(r['ratio']);v=original(r['base'if mode=='find-comparison'else'comparison'])
   if v==0 and mode=='find-comparison':return out('confirm',r='基準量為0不能定為1，先確認基準意義')
   if mode=='recover-base'and(not ratio or not v):return out('confirm',r='比率或比較量為0無法回推正基準，先核對條件')
   z=v*ratio if mode=='find-comparison'else v/ratio;ans={'value':str(z),'unit':unit}
  elif mode=='exchange-base':
   ratio=original(r['oldRatio'])
   if not ratio:return out('confirm',r='比較量為0不能改作非零基準，不能直接取倒數')
   ans={'ratio':str(1/ratio)}
  elif mode=='corresponding-length':
   v=original(r['originalLength']);factor=original(r['factor']);unit=enum(r['unit'],('公尺','公分'))
   if not v or not factor:return out('confirm',r='圖形邊長/半徑及縮放倍率需正，0會退化，先核對')
   ans={'value':str(v*factor),'unit':unit}
  elif mode=='angle-shape-invariant':
   factor=original(r['factor']);shape=enum(r['shape'],('三角形','長方形','正方形','圓'))
   if not factor:return out('confirm',r='0倍率會退化，不能套圖形類別不變')
   if shape=='圓':
    if r['originalAngle']!='無頂角':return out('confirm',r='圓與頂角標示矛盾，先核對是不是圓心角或其他線段夾角')
    angle='無頂角'
   else:
    angle=integer(r['originalAngle'],1,179)
    if shape in('長方形','正方形')and angle!=90:return out('confirm',r='原圖形類別與角度矛盾，先確認原標示')
   ans={'angle':str(angle)if type(angle)is int else angle,'shape':shape}
  else:return out('block',r='非本有限模板')
 except(ValueError,TypeError,OverflowError,ZeroDivisionError):return out('block',r='原量型別/單位/範圍不符契約')
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',ans,'先提供待核對想法')
  if not equivalent(r['proposal'],ans):return out('reject',ans,'保留原量正解，定位錯的對應關係或運算')
 return out('pass',ans,'依已確認結構算，不宣稱照片/實測理解')
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']:
  a=evaluate(c['subtypeId'],c['input']);counts[a['decision']]+=1
  if(a['decision'],a['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());e,counts=verify_package(p);assert not e,e;rt=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'];rt+=1
 print(json.dumps({'package':PACK,'cases':len(p['cases']),'roundtrips':rt,'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)
