PACK='grade8-sequence-rules'
SUBTYPES={'g8-sequence-pattern': 'pattern', 'g8-sequence-cycle': 'cycle'}
import json,pathlib,re,sys,collections
from fractions import Fraction as F
REQ={'pattern':['rule','n','ruleConfirmed'],'cycle':['cycle','n','ruleConfirmed'],'ad-term':['first','difference','n','arithmeticConfirmed'],'ad-table':['first','difference','values','arithmeticConfirmed'],'sum-d':['first','difference','n','arithmeticConfirmed'],'sum-end':['first','last','n','arithmeticConfirmed'],'gp-term':['first','ratio','n','geometricConfirmed'],'gp-table':['first','ratio','values','geometricConfirmed']}
BOOL={'ruleConfirmed','arithmeticConfirmed','geometricConfirmed'}
class Invalid(Exception):pass
class Need(Exception):pass
def out(d,a=None,reason=''):return dict(decision=d,answer=a,reason=reason)
def rational(x,bound=1000):
 if type(x)is int and abs(x)<=bound:return F(x)
 if type(x)is str and len(x)<=80 and re.fullmatch(r'-?[0-9]{1,32}(?:/[1-9][0-9]{0,31}|\.[0-9]{1,10})?',x,re.ASCII):
  v=F(x)
  if abs(v)<=bound and v.denominator<=1000:return v
 raise Invalid('原量限明列有理數（約分後分母至多1000），不收浮點、真假值或科學記號')
def integer(x,lo,hi):
 if type(x)is not int or not lo<=x<=hi:raise Invalid('項次/項數只支援明列正整數域；空和或另定第0項需轉相符方法')
 return x
def derived(x):
 if type(x)is int and abs(x)<10**256:return F(x)
 if type(x)is str and len(x)<=520 and re.fullmatch(r'-?[0-9]{1,256}(?:/[1-9][0-9]{0,255}|\.[0-9]{1,256})?',x,re.ASCII):return F(x)
 raise Invalid('衍生答案須為有界精確值，不接浮點或真假值')
def normalize(p,a):
 if type(p)is not dict or set(p)!=set(a):raise Invalid('答案欄位需完全對應')
 z={}
 for k,v in a.items():
  if type(v)is bool:
   if type(p[k])is not bool:raise Invalid('符合與否需明確真假值')
   z[k]=p[k]
  else:z[k]=derived(p[k])
 return z

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',reason='不屬本有限文字方法')
 mode=SUBTYPES[subtype_id];required=REQ[mode]
 if r.get('confirmed')is not True or any(r.get(k)is None for k in required):return out('confirm',reason='先補原題規則/項次/項值，不由有限前項猜唯一規則')
 for k in('cycle','values'):
  if k in required and type(r[k])is list and any(x is None for x in r[k]):return out('confirm',reason='原有序項表含未確認項，先補清，不用另一題代入')
 if type(r.get('task'))is not str or r['task']not in('solve','check_proposal')or set(r)-set(required)-{'task','confirmed','proposal'}:return out('block',reason='未知任務/欄位不可套入本方法')
 try:
  for k in required:
   if k in BOOL:
    if type(r[k])is not bool:raise Invalid('規則確認需真偽值')
    if not r[k]:raise Need('題目尚未明訂生成規則或等差/等比關係；先確認，不能只看前幾項猜')
  if mode=='pattern':
   n=integer(r['n'],1,100)
   if type(r['rule'])is not str or r['rule']not in('square','consecutive-product','triangular'):raise Invalid('只支援已明訂n²、n(n+1)、n(n+1)/2的項次規則')
   a={'value':str(F(n*n if r['rule']=='square'else n*(n+1),2 if r['rule']=='triangular'else 1))}
  elif mode=='cycle':
   n=integer(r['n'],1,1000);xs=r['cycle']
   if type(xs)is not list or not 1<=len(xs)<=8:raise Invalid('週期需1至8個已確認有序項')
   xs=[rational(x)for x in xs];a={'value':str(xs[(n-1)%len(xs)])}
  elif mode in('ad-term','sum-d','gp-term','sum-end'):
   n=integer(r['n'],1,30);first=rational(r['first'])
   if mode=='sum-end':
    last=rational(r['last'])
    if n==1 and first!=last:raise Need('只有1項時首項和末項是同一項，兩值矛盾先確認')
    a={'value':str(n*(first+last)/2)}
   elif mode=='gp-term':
    ratio=rational(r['ratio'],5)
    # n=1 returns the original first term without evaluating0**0.
    a={'value':str(first if n==1 else first*ratio**(n-1))}
   else:
    difference=rational(r['difference'],100);last=first+(n-1)*difference;a={'value':str(last if mode=='ad-term'else n*(first+last)/2)}
  else:
   first=rational(r['first']);xs=r['values']
   if type(xs)is not list or not 1<=len(xs)<=30:raise Invalid('核對有限項表只收1至30項，不由此證明無限延伸唯一')
   xs=[rational(x,10**30)for x in xs]
   # Table literals share finite denominator1000; terms needing finer denominators route to scalar-term method.
   delta=rational(r['difference'],100)if mode=='ad-table'else rational(r['ratio'],5);value=first;bad=0
   for i,x in enumerate(xs,1):
    if x!=value and bad==0:bad=i
    value=value+delta if mode=='ad-table'else value*delta
   a={'matches':bad==0,'firstMismatch':bad}
 except Need as e:return out('confirm',reason=str(e))
 except(Invalid,ValueError,ZeroDivisionError,OverflowError,TypeError)as e:return out('block',reason=str(e))
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',a,'請提供想核對的答案；原規則正解仍保留')
  try:ok=normalize(r['proposal'],a)==normalize(a,a)
  except(Invalid,ValueError,ZeroDivisionError,TypeError):ok=False
  if not ok:return out('reject',a,'錯提案不能改原規則；回到具體項次/間隔或符號檢查')
 return out('pass',a,'只對已明訂規則作有限精確核對，不猜唯一延伸')
def validate_pack(p):
 errs=[]
 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):errs.append(sid+':distribution')
 for c in p['cases']:
  g=evaluate(c['subtypeId'],c['input'])
  if(g['decision'],g['answer'])!=(c['expectedDecision'],c['expectedAnswer']):errs.append(c['id'])
  if c['teacherReviewed']is not False or c['appConnected']is not False:errs.append(c['id']+':flags')
 return errs
def check():
 p=json.loads(pathlib.Path(__file__).with_name(PACK+'.json').read_text());errs=validate_pack(p);assert not errs,errs;print(json.dumps(dict(pack=PACK,cases=len(p['cases']),passed=True)))
if __name__=='__main__':
 if len(sys.argv)>1 and sys.argv[1]=='evaluate':
  q=json.load(sys.stdin);print(json.dumps(evaluate(q.get('subtypeId'),q.get('input')),ensure_ascii=False))
 else:check()
