#!/usr/bin/env python3
"""Finite elementary method oracle. Standard library; no fixture-derived answers."""
import json,pathlib,sys,re,copy,collections
PACK='grade2-two-step-stories'
REQUIRED={'g2-two-step-add-subtract': ('start', 'first', 'second', 'firstAction'), 'g2-two-step-multiply-add': ('each', 'groups', 'extra'), 'g2-two-step-multiply-subtract': ('each', 'groups', 'taken')}
MODE='two-step'
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整數')
 if subtype_id=='g2-two-step-add-subtract':
  start,first,second=r['start'],r['first'],r['second'];action=r['firstAction']
  if action not in('add','subtract'):return out('block',reason='兩次事件的第一操作未明確')
  if any(not 0<=v<=1000 for v in(start,first,second)):return out('block',reason='本包每個量限0到1000')
  mid=start+first if action=='add'else start-first;v=mid-second if action=='add'else mid+second
  if not 0<=mid<=1000 or not 0<=v<=1000:return out('block',reason='兩步都須保持非負且不超1000，否則轉適合數域')
 else:
  each,groups=r['each'],r['groups'];key='extra'if subtype_id.endswith('add')else'taken';other=r[key]
  if not 0<=each<=10 or not 0<=groups<=10 or not 0<=other<=1000:return out('block',reason='本包相同組限十十乘法，第二步數量1000內')
  mid=0
  for _ in range(groups):mid+=each
  v=mid+other if key=='extra'else mid-other
  if not 0<=v<=1000:return out('block',reason='實物剩量不可負，總量不超1000')
 answer={'value':v}
 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)
