import json,pathlib,sys,re,collections
from fractions import Fraction as F
CFG={'code': 'D-1-1', 'title': '一年級日常物件簡單分類', 'modes': ['one-rule', 'reclassify'], 'page': 22, 'lines': [1272, 1285]}
PACK='grade1-simple-classification'
SUBTYPES={'primary-one-rule': 'one-rule', 'primary-reclassify': 'reclassify'}
AXES={'顏色':('紅色','藍色','黃色'),'形狀':('圓形','正方形','三角形'),'材料':('木製','塑膠')}
REQ={'one-rule':['objects','criterion','observedTotal'],'reclassify':['objects','firstCriterion','secondCriterion','observedTotal'],'nested-groups':['objects','parentCriterion','childCriterion','observedTotal'],'multiple-marks':['objects','selectedLabels','selectionMode','observedTotal'],'record-audit':['objects','criterion','records','observedTotal'],'capacity-compare':['method'],'weight-compare':['method'],'area-compare':['method']}
MODE_REQ={'capacity-compare':{'cups':['aCount','bCount','unitRelation','fillA','fillB','spillA','spillB'],'reference':['aLevel','bLevel','topLevel','fillA','fillB','sameReferenceConfirmed','spillA','spillB','overflowA','overflowB']},'weight-compare':{'balance':['leftLabel','rightLabel','emptyPosition','loadedPosition'],'units':['aCount','bCount','unitRelation','balancedA','balancedB']},'area-compare':{'cover':['aCount','bCount','tileRelation','coverA','coverB','overlapA','overlapB'],'overlay':['observation','operationConfirmed']}}
def out(d,a=None,r=''):return dict(decision=d,answer=a,reason=r)
def integer(v,lo=0,hi=20):
 if type(v)is not int or not lo<=v<=hi:raise ValueError('原點數需範圍內整數，布林不是1')
 return v
def enum(v,values):
 if type(v)is not str or v not in values:raise ValueError('原標記不在已列有限選項')
 return v
def boolean(v):
 if type(v)is not bool:raise ValueError('操作紀錄需明確真偽')
 return v
def missing(v,depth=0):
 if v is None:return True
 if depth>10:return False
 if type(v)is list:return len(v)<=100 and any(missing(x,depth+1)for x in v)
 if type(v)is dict:return len(v)<=20 and any(missing(x,depth+1)for x in v.values())
 return False
def objects(v,limit):
 if type(v)is not list or len(v)>limit:raise ValueError('物件清單超本有限觀察範圍')
 out=[];ids=[]
 for o in v:
  if type(o)is not dict or len(o)!=4 or set(o)!= {'id','顏色','形狀','材料'}:raise ValueError('每件需同一身分與三個已確認特徵')
  label=o['id']
  if type(label)is not str or not re.fullmatch(r'[0-9]{2}號',label,re.ASCII):raise ValueError('物件用兩位數號碼識別，不把相同樣子當同一件')
  for axis,values in AXES.items():enum(o[axis],values)
  ids.append(label);out.append(o)
 if len(set(ids))!=len(ids):raise ValueError('原物件身分重複，需要先確認是否同一件記兩次')
 return out
def grouped(obs,axis):return {label:[o['id']for o in obs if o[axis]==label]for label in AXES[axis]}
def counts(obs,axis):return {k:len(v)for k,v in grouped(obs,axis).items()}
def cmp(a,b,kind):
 if a==b:return '一樣重'if kind=='weight'else'一樣大'
 return('甲'if a>b else'乙')+('較重'if kind=='weight'else'較大')
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 equal(p,a):
 try:
  if type(a)is bool:return type(p)is bool and p==a
  if type(a)is int:return derived(p)==a
  if type(a)is str:return type(p)is str and p==a
  if type(a)is list:return type(p)is list and len(p)==len(a)and all(type(x)is str for x in p)and len(p)==len(set(p))and sorted(p)==sorted(a)
  if type(a)is dict:return type(p)is dict and len(p)==len(a)and set(p)==set(a)and all(equal(p[k],v)for k,v in a.items())
 except(ValueError,TypeError,ZeroDivisionError):return False
 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 or len(r)>32:return out('block',r='非本有限操作觀察模板')
 mode=SUBTYPES[subtype_id];fs=REQ[mode][:]
 if r.get('confirmed')is not True or any(k not in r or missing(r[k])for k in fs):return out('confirm',r='先確認缺少的分類準則、觀察值或操作條件，不猜實物圖')
 if mode in MODE_REQ:
  if any(v is None for k,v in r.items()if k not in('proposal','task')):return out('confirm',r='已提供的原觀察缺值，先確認')
  if type(r['method'])is not str or r['method']not in MODE_REQ[mode]:return out('block',r='本包方法不符')
  fs+=MODE_REQ[mode][r['method']]
  if any(k not in r or missing(r[k])for k in fs):return out('confirm',r='先確認此比較方法需要的原觀察與條件')
 if 'objects'in r and type(r['objects'])is list and len(r['objects'])<=30:
  if any(type(o)is dict and any(k not in o or o[k]is None for k in('id',*AXES))for o in r['objects']):return out('confirm',r='某物件身分或特徵缺少，先核對')
 if 'objects'in r and type(r['objects'])is list and len(r['objects'])<=30:
  ids=[o.get('id')for o in r['objects']if type(o)is dict]
  if all(type(v)is str for v in ids)and len(ids)!=len(set(ids)):return out('confirm',r='原批同號出現多次，先確認是同件重記還是身分標錯')
  for o in r['objects']:
   if type(o)is dict:
    for axis,values in AXES.items():
     v=o.get(axis)
     if type(v)is list and len(v)>1 and all(type(x)is str and x in values for x in v):return out('confirm',r='同件在同特徵有多個標記，先約定本次分籃或複選記法，不能任選一群')
 if mode=='record-audit'and type(r['records'])is list and len(r['records'])<=60:
  if any(type(v)is dict and any(k not in v or v[k]is None for k in('id','group'))for v in r['records']):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)-{'confirmed','task','proposal'}:return out('block',r='結構或任務欄不符')
 try:
  if mode not in MODE_REQ:
   obs=objects(r['objects'],20 if CFG['code']=='D-1-1'else 30);known=integer(r['observedTotal'],0,20 if CFG['code']=='D-1-1'else 30)
   if known!=len(obs):return out('confirm',r='已數總件數與原清單矛盾，先查漏拍/重複，不讓確認條件掩蓋矛盾')
   if mode=='one-rule':
    axis=enum(r['criterion'],AXES);groups=grouped(obs,axis);ans={'groups':groups,'counts':{k:len(v)for k,v in groups.items()},'total':len(obs)}
   elif mode=='reclassify':
    a=enum(r['firstCriterion'],AXES);b=enum(r['secondCriterion'],AXES)
    if a==b:return out('block',r='本型是換另一準則；同準則重分轉原分類型')
    ans={'first':counts(obs,a),'second':counts(obs,b),'total':len(obs)}
   elif mode=='nested-groups':
    a=enum(r['parentCriterion'],AXES);b=enum(r['childCriterion'],AXES)
    if a==b:return out('block',r='本型用另一特徵再分；同特徵不增加分群資訊')
    ans={'parents':{key:{'count':len(xs),'children':counts([o for o in obs if o['id']in xs],b)}for key,xs in grouped(obs,a).items()},'total':len(obs)}
   elif mode=='multiple-marks':
    enum(r['selectionMode'],('可複選貼記號',));labels=r['selectedLabels'];allLabels={v:axis for axis,values in AXES.items()for v in values}
    if type(labels)is not list or not 2<=len(labels)<=3 or any(type(x)is not str or x not in allLabels for x in labels)or len(set(labels))!=len(labels):raise ValueError('需2..3個不重複且已明定的貼記號標準')
    hit={label:[o['id']for o in obs if o[allLabels[label]]==label]for label in labels};selected=set(x for xs in hit.values()for x in xs)
    ans={'labelCounts':{k:len(v)for k,v in hit.items()},'marks':sum(len(v)for v in hit.values()),'uniqueSelected':len(selected),'originalTotal':len(obs),'unselected':len(obs)-len(selected)}
   else:
    axis=enum(r['criterion'],AXES);records=r['records']
    if type(records)is not list or len(records)>60:raise ValueError('需有限記錄清單')
    byid={o['id']:o for o in obs};seen=collections.Counter();wrong=set();unexpected=set()
    allLabels={v for vs in AXES.values()for v in vs}
    for row in records:
     if type(row)is not dict or len(row)!=2 or set(row)!= {'id','group'}:raise ValueError('每個記號需物件號碼與群名')
     label=row['id'];group=enum(row['group'],allLabels)
     if type(label)is not str or not re.fullmatch(r'[0-9]{2}號',label,re.ASCII):raise ValueError('記錄身分格式不符')
     seen[label]+=1
     if label not in byid:unexpected.add(label);continue
     if byid[label][axis]!=group:wrong.add(label)
    absent=set(byid)-set(seen);dup={k for k,v in seen.items()if v>1};ans={'valid':not(absent or dup or wrong or unexpected),'missingIds':sorted(absent),'duplicateIds':sorted(dup),'wrongGroupIds':sorted(wrong),'unexpectedIds':sorted(unexpected),'originalTotal':len(obs),'recordMarks':len(records)}
  elif mode=='capacity-compare':
   method=r['method'];fillA=enum(r['fillA'],('裝滿','未裝滿'));fillB=enum(r['fillB'],('裝滿','未裝滿'));spillA=boolean(r['spillA']);spillB=boolean(r['spillB'])
   if fillA!='裝滿'or fillB!='裝滿'or spillA or spillB:return out('confirm',r='原容器未滿或灑漏，觀察不能直接代表容量，先重做操作')
   if method=='cups':
    a=integer(r['aCount'],1,20);b=integer(r['bCount'],1,20);unit=enum(r['unitRelation'],('同容量','容量不同'));ans={'relation':cmp(a,b,'capacity')if unit=='同容量'else'不能只比杯數'}
   else:
    a=integer(r['aLevel'],1,20);b=integer(r['bLevel'],1,20);top=integer(r['topLevel'],1,20);same=boolean(r['sameReferenceConfirmed']);ovA=boolean(r['overflowA']);ovB=boolean(r['overflowB'])
    if not same or ovA or ovB or a>top or b>top:return out('confirm',r='不是同參照/有溢出/液面超容器上界，先核對實際操作')
    ans={'relation':cmp(a,b,'capacity')}
  elif mode=='weight-compare':
   if r['method']=='balance':
    a=enum(r['leftLabel'],('甲','乙'));b=enum(r['rightLabel'],('甲','乙'));empty=enum(r['emptyPosition'],('平衡','左低','右低'));loaded=enum(r['loadedPosition'],('平衡','左低','右低'))
    if a==b or empty!='平衡':return out('confirm',r='左右身分矛盾或空天平未平衡，不能直接判重量')
    ans={'relation':'一樣重'if loaded=='平衡'else(a if loaded=='左低'else b)+'較重'}
   else:
    a=integer(r['aCount']);b=integer(r['bCount']);same=enum(r['unitRelation'],('同重量','重量不同'));matchA=boolean(r['balancedA']);matchB=boolean(r['balancedB'])
    if not matchA or not matchB:return out('confirm',r='物品尚未與個別單位秤平，份數不能代表重量')
    ans={'relation':cmp(a,b,'weight')if same=='同重量'or not a or not b else'不能只比個數'}
  else:
   if r['method']=='cover':
    a=integer(r['aCount']);b=integer(r['bCount']);same=enum(r['tileRelation'],('同面積','面積不同'));ca=enum(r['coverA'],('完整覆滿','未覆滿'));cb=enum(r['coverB'],('完整覆滿','未覆滿'));oa=boolean(r['overlapA']);ob=boolean(r['overlapB'])
    if ca!='完整覆滿'or cb!='完整覆滿'or oa or ob:return out('confirm',r='未完整覆蓋或小片重疊，塊數不能直接代表面積')
    ans={'relation':cmp(a,b,'area')if same=='同面積'or not a or not b else'不能只比塊數'}
   else:
    o=enum(r['observation'],('甲嚴格包含乙','乙嚴格包含甲','完全重合','互不包含'));confirmed=boolean(r['operationConfirmed'])
    if not confirmed:return out('confirm',r='平放重疊及邊界對應未核實，不從示意猜面積')
    ans={'relation':{'甲嚴格包含乙':'甲較大','乙嚴格包含甲':'乙較大','完全重合':'一樣大','互不包含':'不能只憑這次重疊判大小'}[o]}
 except(ValueError,TypeError,KeyError,OverflowError,ZeroDivisionError):return out('block',r='原點數/觀察標記/結構不在有限契約；不代表原題必錯')
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',ans,'先說出想核對的答案')
  if not equal(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']:
  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['teacherReviewed']is not False or c['appConnected']is not False or c['studentFacing']!=(c['casePurpose']!='validator-guard'):errors.append(c['id']+':flags')
  if c['kind']=='ambiguous':
   ws=c.get('ambiguityWitnesses',[])
   if len(ws)!=2:errors.append(c['id']+':見證數')
   else:
    z=[evaluate(c['subtypeId'],w['completeInput'])for w in ws]
    if any(a['decision']!='pass'or a['answer']!=w['expectedAnswer']for a,w in zip(z,ws))or z[0]['answer']==z[1]['answer']:errors.append(c['id']+':見證不合法或同答')
 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,cs=verify_package(p);assert not es,es;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,'decisions':cs},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)
