PACK='grade3-confirmed-tables'
SUBTYPES={'g3-one-way-table': 'tally', 'g3-two-way-table': 'cross'}
import json,pathlib,re,sys,collections
from fractions import Fraction as F
REQ={
 'tally':['labels','observations','unit','completeConfirmed','exclusiveConfirmed'],
 'cross':['rows','columns','cells','queryRow','queryColumn','unit','completeConfirmed','exclusiveConfirmed'],
 'bar-read':['labels','offsets','step','maximum','query','unit','scaleConfirmed','completeConfirmed','exclusiveConfirmed'],
 'line-read':['times','offsets','baseline','step','queryTime','timeUnit','unit','orderedConfirmed','scaleConfirmed'],
 'bar-plan':['labels','counts','step','maximum','unit','exclusiveConfirmed','completeConfirmed'],
 'line-plan':['times','values','xOrigin','xStep','yStep','timeUnit','unit','timeSeriesConfirmed'],
 'line-check':['times','values','positions','xOrigin','xStep','yStep','timeUnit','unit','timeSeriesConfirmed'],
 'pie-plan':['labels','counts','total','unit','wholeConfirmed','exclusiveConfirmed','completeConfirmed'],
 'pie-read':['labels','percentages','total','unit','wholeConfirmed','exclusiveConfirmed','completeConfirmed','exactPercentConfirmed'],
 'likely-compare':['labels','counts','queryA','queryB','mechanismConfirmed','sameContextConfirmed','clearDifferenceConfirmed','completeConfirmed','exclusiveConfirmed'],
 'likely-profile':['labels','counts','query','mechanismConfirmed','sameContextConfirmed','clearDifferenceConfirmed','completeConfirmed','exclusiveConfirmed']}
UNITS=('人','次','個','株','冊','公分');TIMEUNITS=('天','週','月','年','分鐘')
class Bad(Exception):pass
class Need(Exception):pass
class Outside(Exception):pass
def out(d,a=None,reason=''):return dict(decision=d,answer=a,reason=reason)
def ni(v,lo,hi):
 if type(v)is not int or not lo<=v<=hi:raise Bad('原數需在本有限範圍的JSON整數，不收布林/浮點/數字字串')
 return v
def enum(v,values):
 if type(v)is not str or v not in values:raise Bad('單位或資料角色不符')
 return v
def labels(v):
 if type(v)is not list or not 1<=len(v)<=6 or any(type(x)is not str or not re.fullmatch(r'[\u4e00-\u9fffA-Za-z0-9]{1,10}',x)for x in v)or len(set(v))!=len(v):raise Bad('類別/列欄名稱需清楚、互異、有序，最多6個')
 return v
def counts(v,n):
 if type(v)is not list or len(v)!=n:raise Need('資料筆數與標頭不相符，先補完整對應，不自行移位')
 return [ni(x,0,1000)for x in v]
def series(r):
 ts=r['times'];vs=r['values']
 if type(ts)is not list or not 2<=len(ts)<=6:raise Bad('本有限時間資料2至6個已確認觀察點')
 ts=[ni(x,0,100)for x in ts]
 if any(a>=b for a,b in zip(ts,ts[1:])):raise Need('觀察時間需嚴格遞增且無重複，先確認原順序，不自動改資料')
 vs=counts(vs,len(ts));enum(r['timeUnit'],TIMEUNITS);enum(r['unit'],UNITS);origin=ni(r['xOrigin'],0,100);xs=ni(r['xStep'],1,20);ys=ni(r['yStep'],1,100)
 if origin>ts[0]:raise Need('時間軸起點大於第一觀察時間，先核對原製圖設定')
 return ts,vs,[(F(t-origin,xs),F(v,ys))for t,v in zip(ts,vs)]
def derived(x):
 if type(x)is int and abs(x)<10**128:return F(x)
 if type(x)is str and len(x)<=260 and re.fullmatch(r'-?[0-9]{1,128}(?:/[1-9][0-9]{0,127}|\.[0-9]{1,128})?',x,re.ASCII):return F(x)
 raise Bad('答案須有界精確值，不接受浮點/布林當數量')
def same(p,a):
 if type(a)is dict:return type(p)is dict and set(p)==set(a)and all(same(p[k],v)for k,v in a.items())
 if type(a)is list:return type(p)is list and len(p)==len(a)and all(same(x,y)for x,y in zip(p,a))
 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:
  try:v=F(a)
  except ValueError:return type(p)is str and p==a
  return derived(p)==v
 raise Bad('未定義答案欄位')
def missing_nested(x):
 if type(x)is list:return any(v is None or (type(v)is list and missing_nested(v))for v in x)
 return False

def evaluate(s,r):
 if type(s)is not str or s not in SUBTYPES or type(r)is not dict:return out('block',reason='非本有限文字統計方法')
 mode=SUBTYPES[s];fs=REQ[mode]
 if r.get('confirmed')is not True or any(r.get(k)is None for k in fs):return out('confirm',reason='先確認同一份資料/標頭/總體/刻度，不能猜照片像素')
 if any(missing_nested(r[k])for k in fs if k in('labels','rows','columns','cells','counts','times','values','offsets','observations','percentages','positions')):return out('confirm',reason='已知資料表仍有空白未確認項，先補原資料')
 if type(r.get('task'))is not str or r['task']not in('solve','check_proposal')or set(r)-set(fs)-{'task','confirmed','proposal'}:return out('block',reason='任務或未知欄位不屬本有限方法')
 try:
  for k in fs:
   if k.endswith('Confirmed'):
    if type(r[k])is not bool:raise Bad('觀察確認需真偽值')
    if not r[k]:raise Need('總體、分類、刻度或比較機制尚未核實，先問，不覆蓋不明條件')
  if mode=='tally':
   ls=labels(r['labels']);obs=r['observations'];unit=enum(r['unit'],UNITS)
   if type(obs)is not list or len(obs)>50 or any(type(x)is not str or x not in ls for x in obs):raise Need('觀察清單含未歸類項，先確認每筆屬哪類及是否漏類')
   cs=[obs.count(x)for x in ls];a=dict(counts=cs,total=len(obs),unit=unit)
  elif mode=='cross':
   rows=labels(r['rows']);cols=labels(r['columns']);xs=r['cells'];unit=enum(r['unit'],UNITS)
   if type(xs)is not list or len(xs)!=len(rows):raise Need('列標頭與列數不符')
   cells=[counts(x,len(cols))for x in xs];qi=ni(r['queryRow'],0,len(rows)-1);qj=ni(r['queryColumn'],0,len(cols)-1);rs=[sum(x)for x in cells];cs=[sum(x[j]for x in cells)for j in range(len(cols))]
   if sum(rs)>1000:raise Outside('三年級首包合計只到1000，較大表轉後續方法')
   a=dict(rowTotals=rs,columnTotals=cs,total=sum(rs),selected=cells[qi][qj],unit=unit)
  elif mode=='bar-read':
   ls=labels(r['labels']);offsets=counts(r['offsets'],len(ls));step=ni(r['step'],1,100);maximum=ni(r['maximum'],1,10000);query=ni(r['query'],0,len(ls)-1);unit=enum(r['unit'],UNITS)
   if maximum%step or any(x*step>maximum for x in offsets):raise Need('長條已知刻度上限/間隔/頂端位置不相符，先核原圖')
   vs=[x*step for x in offsets];a=dict(values=vs,total=sum(vs),selected=vs[query],unit=unit)
  elif mode=='line-read':
   ts=r['times']
   if type(ts)is not list or not 2<=len(ts)<=6:raise Bad('折線已確認觀察點2至6筆')
   ts=[ni(x,0,100)for x in ts]
   if any(a>=b for a,b in zip(ts,ts[1:])):raise Need('時間順序或重複時間需先核實')
   os=counts(r['offsets'],len(ts));base=ni(r['baseline'],0,1000);step=ni(r['step'],1,100);query=ni(r['queryTime'],0,100);unit=enum(r['unit'],UNITS);enum(r['timeUnit'],TIMEUNITS)
   if query not in ts:raise Need('所問時間未量測，不從兩點連線猜精確值')
   a=dict(value=base+os[ts.index(query)]*step,unit=unit)
  elif mode=='bar-plan':
   ls=labels(r['labels']);cs=counts(r['counts'],len(ls));step=ni(r['step'],1,100);maximum=ni(r['maximum'],1,10000);enum(r['unit'],UNITS)
   if maximum%step or max(cs)>maximum:raise Need('縱軸上限/間隔無法包含原數據，先調整製圖設定')
   a=dict(heights=[str(F(x,step))for x in cs],total=sum(cs))
  elif mode in('line-plan','line-check'):
   ts,vs,positions=series(r)
   if mode=='line-plan':a=dict(x=[str(x)for x,y in positions],y=[str(y)for x,y in positions])
   else:
    ps=r['positions']
    if type(ps)is not list or len(ps)!=len(ts)or any(type(v)is not list or len(v)!=2 for v in ps):raise Need('待核對座標表缺點或未對應同一觀察時間')
    # Supplied chart positions are exact rational grid coordinates, not OCR pixels.
    supplied=[tuple(derived(v)for v in pair)for pair in ps]
    if any(v<0 or v>10000 or v.denominator>1000 for pair in supplied for v in pair):raise Outside('本五年級座標核對只支援非負格數至10000、約分分母<=1000，其他另轉方法')
    bad=next((i for i,(got,want)in enumerate(zip(supplied,positions),1)if got!=want),0);a=dict(matches=bad==0,firstMismatch=bad)
  elif mode in('pie-plan','pie-read'):
   ls=labels(r['labels'])
   if type(r['total'])is int and r['total']==0:raise Need('全體為0不能直接分配圓圖比例，先核對總體與題意')
   total=ni(r['total'],1,10000);unit=enum(r['unit'],('人','個','次'))
   if mode=='pie-plan':
    cs=counts(r['counts'],len(ls))
    if sum(cs)!=total:raise Need('分類合計不等於同一完整總體，先查漏類/重複/總數')
    ps=[F(100*x,total)for x in cs]
    if any(p.denominator!=1 for p in ps):raise Outside('本首包只整百分率百格配置；分格或四捨五入另教，不能硬湊100格')
    a=dict(percentages=[int(p)for p in ps],cells=[int(p)for p in ps])
   else:
    ps=counts(r['percentages'],len(ls))
    if any(x>100 for x in ps)or sum(ps)!=100:raise Need('完整圓圖精確百分率未合100%，先查是否局部圖、約數或漏類')
    cs=[F(p*total,100)for p in ps]
    if any(c.denominator!=1 for c in cs):raise Need('精確百分率與整體人/個/次數不相容，先確認是否概數或總數有誤')
    a=dict(counts=[int(x)for x in cs],total=total,unit=unit)
  else:
   ls=labels(r['labels']);cs=counts(r['counts'],len(ls))
   if len(cs)<2 or sum(cs)==0:raise Need('至少兩類且有實際觀察紀錄，沒有資料不能推可能性')
   if mode=='likely-compare':
    i=ni(r['queryA'],0,len(ls)-1);j=ni(r['queryB'],0,len(ls)-1)
    if i==j or cs[i]==cs[j]:raise Need('類別相同或次數相同，資料不能支持誰較可能；請確認比較問題')
    high,low=max(cs[i],cs[j]),min(cs[i],cs[j])
    if high<3*low or high-low<5:raise Outside('差異未落入本首包保守明顯對比案例，交老師依資料說明；非官方機率門檻')
    a=dict(comparison='甲類較可能'if cs[i]>cs[j]else'乙類較可能')
   else:
    i=ni(r['query'],0,len(ls)-1);selected=cs[i];other=sum(cs)-selected
    if selected>=3*other and selected-other>=5:a=dict(description='資料支持很有可能')
    elif other>=3*selected and other-selected>=5:a=dict(description='資料支持很不可能')
    else:raise Outside('中間或差異小的分布不屬本有限強對比示例；請老師說明，不套通用機率數值門檻')
 except Need as e:return out('confirm',reason=str(e))
 except(Outside,Bad,ValueError,TypeError,ZeroDivisionError,OverflowError)as e:return out('block',reason=str(e))
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',a,'先提供想核對的想法，保留原資料答案')
  try:good=same(r['proposal'],a)
  except(Bad,ValueError,TypeError,ZeroDivisionError):good=False
  if not good:return out('reject',a,'保留原資料結論；先對齊原標頭/時刻/單位/總體再修正錯步')
 return out('pass',a,'由已確認完整資料推理；不從像素補數，不保證未來必然發生')
def validate_pack(p):
 errors=[]
 for s in SUBTYPES:
  if collections.Counter(c['kind']for c in p['cases']if c['subtypeId']==s)!=dict(normal=8,negative=6,boundary=4,ambiguous=2,holdout=4):errors.append(s+':distribution')
 for c in p['cases']:
  g=evaluate(c['subtypeId'],c['input'])
  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:errors.append(c['id']+':flags')
 return errors
def check():
 p=json.loads(pathlib.Path(__file__).with_name(PACK+'.json').read_text());errors=validate_pack(p);assert not errors,errors;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()
