#!/usr/bin/env python3
"""Bounded, structural arithmetic only; no raw-expression evaluation."""
import json,sys,re,copy,pathlib
from fractions import Fraction
TYPES={'r31-find-multiple','r31-find-original','r31-division-check','r32-equal-change','r32-same-factor','r32-repeat-cycle','r32-growing-change'}
class Missing(Exception):pass
class Guard(Exception):pass
class Conflict(Exception):pass
def integer(v,lo=0,hi=9999):
 if v is None:raise Missing('缺少原題數量')
 if type(v)is not int or not lo<=v<=hi:raise Guard('本包原題須是範圍內整數，不解析任意算式或指數')
 return v
def needed(d,k):
 if k not in d or d[k]is None:raise Missing('請補清原題條件')
 return d[k]
def structural(v,depth=0):
 if depth>8:raise Guard('結構太深')
 if type(v)is dict:
  if len(v)>24:raise Guard('欄位太多')
  if any(type(k)is not str or len(k)>100 for k in v):raise Guard('欄位名稱不合法')
  for x in v.values():structural(x,depth+1)
 elif type(v)is list:
  if len(v)>24:raise Guard('項目太多')
  for x in v:structural(x,depth+1)
 elif type(v)is str and len(v)>256:raise Guard('字串過長')
 elif type(v)is int and abs(v)>10**12:raise Guard('整數過大')
def preflight(s,r):
 keys=['confirmed','task']
 if s.startswith('r31-find'):keys+=['knownFactor','total']
 elif s=='r31-division-check':keys+=['dividend','divisor','claimedQuotient','claimedRemainder']
 else:
  keys+=['ruleConfirmed','rule','targetPosition','knownTerms']
  if s!='r32-repeat-cycle':keys+=['start']
 for k in keys:needed(r,k)
 if s.startswith('r32'):
  rule=r['rule']
  if type(rule)is dict:
   rk={'r32-equal-change':['step'],'r32-same-factor':['factor'],'r32-repeat-cycle':['cycle'],'r32-growing-change':['firstIncrement','incrementIncrease']}[s]
   for k in rk:needed(rule,k)
   if type(rule.get('cycle'))is list and any(x is None for x in rule['cycle']):raise Missing('循環中有一個位置尚未看清')
  if type(r['knownTerms'])is list and any(x is None for x in r['knownTerms']):raise Missing('已見項中有尚未看清的量')
 if r.get('task')=='check_proposal':needed(r,'proposal')
def sequence(s,r):
 if type(r['ruleConfirmed'])is not bool:raise Guard('規則確認值須為布林')
 if not r['ruleConfirmed']:raise Missing('只有有限幾項不能認定唯一規則，請先說明本次採用的變化')
 rule=r['rule'];pos=integer(r['targetPosition'],1,12)
 if type(rule)is not dict:raise Guard('規則須是結構化條件')
 expected={'r32-equal-change':{'step'},'r32-same-factor':{'factor'},'r32-repeat-cycle':{'cycle'},'r32-growing-change':{'firstIncrement','incrementIncrease'}}[s]
 if set(rule)!=expected:raise Guard('規則欄位不符本子型')
 terms=r['knownTerms']
 if type(terms)is not list or not 1<=len(terms)<=12:raise Guard('已見項需為1到12項')
 terms=[integer(x)for x in terms]
 if s=='r32-repeat-cycle':
  cycle=rule['cycle']
  if type(cycle)is not list or not 2<=len(cycle)<=4:raise Guard('循環需2到4個已知位置')
  cycle=[integer(x)for x in cycle];arr=[];j=0
  for _ in range(max(pos,len(terms))):
   arr.append(cycle[j]);j+=1
   if j==len(cycle):j=0
 else:
  arr=[integer(r['start'])]
  if s=='r32-equal-change':change=integer(rule['step'],-999,999)
  elif s=='r32-same-factor':factor=integer(rule['factor'],2,9)
  else:change=integer(rule['firstIncrement'],0,999);extra=integer(rule['incrementIncrease'],0,99)
  for _ in range(1,max(pos,len(terms))):
   new=arr[-1]*factor if s=='r32-same-factor'else arr[-1]+change
   if not 0<=new<=9999:raise Guard('延伸超出本包自然數範圍，原題需轉交其他方法，不猜值')
   arr.append(new)
   if s=='r32-growing-change':change+=extra
 if arr[:len(terms)]!=terms:raise Conflict('已見項與明給規則不一致，請核對題面')
 return {'value':arr[pos-1],'terms':arr[:pos]}
def compute(s,r):
 if s in {'r31-find-multiple','r31-find-original'}:
  k=integer(r['knownFactor'],0,9);total=integer(r['total'])
  if k==0:return {'status':'multiple'if total==0 else'impossible','value':None}
  q,rem=divmod(total,k)
  return {'status':'unique','value':q}if rem==0 else{'status':'not-whole','value':None}
 if s=='r31-division-check':
  a=integer(r['dividend']);d=integer(r['divisor'],0,9);q=integer(r['claimedQuotient']);rem=integer(r['claimedRemainder'])
  if d==0:return {'status':'undefined','valid':False,'quotient':None,'remainder':None,'reconstructed':None}
  correctq,correctr=divmod(a,d);back=d*q+rem
  return {'status':'defined','valid':back==a and rem<d,'quotient':correctq,'remainder':correctr,'reconstructed':back}
 return sequence(s,r)
def exact(v):
 if type(v)is int:
  if abs(v)>10**12:raise Guard('答案整數過大')
  return Fraction(v)
 if type(v)is not str or len(v)>40 or not re.fullmatch(r'-?\d{1,16}(?:/\d{1,16}|\.\d{1,12})?',v):raise Guard('答案數量須為有界精確數值')
 try:f=Fraction(v)
 except (ValueError,ZeroDivisionError):raise Guard('答案數值不合法')
 if abs(f)>10**12:raise Guard('答案數量過大')
 return f
def normalize(v,expected):
 if type(expected)is dict:
  if type(v)is not dict or len(v)!=len(expected)or set(v)!=set(expected):raise Guard('提案欄位須完整且不可加分數等欄')
  return {k:normalize(v[k],x)for k,x in expected.items()}
 if type(expected)is list:
  if type(v)is not list or len(v)!=len(expected):raise Guard('提案逐項數量不符')
  return [normalize(a,b)for a,b in zip(v,expected)]
 if type(expected)is bool:
  if type(v)is not bool:raise Guard('是非判斷不可用0或1代替')
  return v
 if type(expected)is int:return exact(v)
 if expected is None:
  if v is not None:raise Guard('無唯一量時不可自填一個數')
  return None
 if type(v)is not str:raise Guard('狀態文字不符')
 return v
def evaluate(subtype_id,r):
 try:
  if type(subtype_id)is not str or subtype_id not in TYPES:raise Guard('未知子型')
  if type(r)is not dict:raise Guard('原題條件須為物件')
  structural({k:v for k,v in r.items()if k!='proposal'});preflight(subtype_id,r)
  if type(r['confirmed'])is not bool:raise Guard('確認值須是布林')
  if not r['confirmed']:raise Missing('先核對原題已知量')
  if type(r['task'])is not str or r['task']not in {'solve','check_proposal'}:raise Guard('未知工作種類')
  answer=compute(subtype_id,r)
  if r['task']=='check_proposal':
   try:accepted=normalize(r['proposal'],answer)==normalize(answer,answer)
   except Guard as e:return {'decision':'reject','answer':{'accepted':False,'correctSolution':answer},'reason':str(e)}
   return {'decision':'pass'if accepted else'reject','answer':{'accepted':accepted,'correctSolution':answer},'reason':'逐一核對狀態、數量與每一步；錯提案仍保留原題正解'}
  return {'decision':'pass','answer':answer,'reason':'依已確認條件逐步核對，不從有限項猜唯一規則'}
 except (Missing,Conflict) as e:return {'decision':'confirm','answer':None,'reason':str(e)}
 except Guard as e:return {'decision':'block','answer':None,'reason':str(e)}
def verify_package(package):
 errors=[];counts={}
 for c in package['cases']:
  actual=evaluate(c['subtypeId'],copy.deepcopy(c['input']));counts[actual['decision']]=counts.get(actual['decision'],0)+1
  if actual['decision']!=c['expectedDecision']or actual['answer']!=c['expectedAnswer']:errors.append({'id':c['id'],'actual':actual})
 return errors,counts
def validate_pack(package):return verify_package(package)[0]
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));sys.exit(0)
 path=pathlib.Path(sys.argv[1])if len(sys.argv)>1 else pathlib.Path(__file__).with_name(pathlib.Path(__file__).stem.removeprefix('check-')+'.json')
 errors,counts=verify_package(json.loads(path.read_text()));print(json.dumps({'ok':not errors,'cases':sum(counts.values()),'decisions':counts,'errors':errors},ensure_ascii=False));sys.exit(bool(errors))
