#!/usr/bin/env python3
"""Finite elementary method oracle. Standard library; no fixture-derived answers."""
import json,pathlib,sys,re,copy,collections
PACK='grade2-grouping-sharing'
REQUIRED={'g2-exact-grouping': ('total', 'each'), 'g2-exact-sharing': ('total', 'groups')}
MODE='grouping-sharing'
def out(d,a=None,reason=''):return {'decision':d,'answer':a,'reason':reason}
def evaluate(subtype_id,r):
 if type(subtype_id)is not str or subtype_id not in REQUIRED or type(r)is not dict:return out('block',reason='未知子型或入參格式')
 if r.get('confirmed')is not True:return out('confirm',reason='先確認原題')
 fields=REQUIRED[subtype_id]
 if any(r.get(k)is None for k in fields):return out('confirm',reason='原題缺少必備量，不自行補0')
 if 'coins'in fields and type(r['coins'])is dict and any(v is None for v in r['coins'].values()):return out('confirm',reason='先確認每種錢幣枚數')
 if r.get('task')not in('solve','check_proposal'):return out('block',reason='未知任務')
 if set(r)-set(fields)-{'task','confirmed','proposal'}:return out('block',reason='未知欄位')
 for k in fields:
  if k not in('coins','unknownPosition','firstAction','enoughConfirmed')and type(r[k])is not int:return out('block',reason='本包原數量只收JSON整數')
 n=r['total'];size=r['each']if subtype_id.endswith('grouping')else r['groups']
 if not 0<=n<=100 or not 1<=size<=10:return out('block',reason='本活動總量100內，每包量或人數1到10')
 remaining=n;q=0
 while remaining>=size:remaining-=size;q+=1
 if remaining or q>10:return out('block',reason='此活動只練十十乘法內剛好分完，其他題轉後續方法')
 answer={'groups':q}if subtype_id.endswith('grouping')else{'each':q}
 if r['task']=='check_proposal':
  proposal=r.get('proposal')
  if proposal is None:return out('confirm',answer,'先提供要檢查的提案')
  if type(proposal)is not dict or set(proposal)!=set(answer):return out('reject',answer,'提案鍵不符；仍提供正解')
  normalized={}
  for k,v in proposal.items():
   if type(answer[k])is str:
    if type(v)is not str or v!=answer[k]:return out('reject',answer,'分類錯誤；保留原題正解')
    normalized[k]=v;continue
   if type(v)is int and 0<=v<=1000:pass
   elif type(v)is str and re.fullmatch(r'[0-9]{1,4}',v) and int(v)<=1000:pass
   else:return out('reject',answer,'提案不是契約中的非負整數')
   normalized[k]=int(v)
  if normalized!=answer:return out('reject',answer,'具體錯誤定位見案例教學；保留原題正解')
 return out('pass',answer,'依原條件操作並以反向關係核對')
def verify_package(p):
 errors=[];counts=collections.Counter()
 for sid in REQUIRED:
  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+':counts')
 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']+':'+str(g))
  if c['studentFacing']!=(c['casePurpose']!='validator-guard')or c['teacherReviewed']is not False or c['appConnected']is not False:errors.append(c['id']+':flags')
  if len(c['solutionSteps'])<3 or not c['ifNotUnderstood']:errors.append(c['id']+':method')
 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());errors,counts=verify_package(p);assert not errors,errors
 n=0
 for c in p['cases']:
  if c['expectedAnswer']is None:continue
  r=copy.deepcopy(c['input']);r.update(task='check_proposal',proposal=c['expectedAnswer']);assert evaluate(c['subtypeId'],r)['decision']=='pass';n+=1
  r['proposal']={k:str(v)for k,v in c['expectedAnswer'].items()};assert evaluate(c['subtypeId'],r)['decision']=='pass'
  k=next(k for k,v in c['expectedAnswer'].items()if type(v)is int);r['proposal'][k]=str(int(r['proposal'][k])+1);g=evaluate(c['subtypeId'],r);assert g['decision']=='reject'and g['answer']==c['expectedAnswer']
 mut=copy.deepcopy(p);c=next(c for c in mut['cases']if c['expectedAnswer']is not None);c['expectedAnswer'][next(k for k,v in c['expectedAnswer'].items()if type(v)is int)]+=1;assert validate_pack(mut)
 result={'pack':PACK,'cases':len(p['cases']),'decisions':counts,'roundtripCases':n,'answerMutationDetected':True};print(json.dumps(result,ensure_ascii=False));return result
if __name__=='__main__':check(sys.argv[1]if len(sys.argv)>1 else None)
