import json,pathlib,sys,re,collections
from fractions import Fraction as F
PACK='grade8-equilateral-composites';SUBTYPES=['s87-equilateral', 's87-attached', 's87-cutout']
REQ={'s87-equilateral':['side','shape','unit'],'s87-attached':['side','otherBase','otherKind','configuration','unit'],'s87-cutout':['length','height','side','baseOffset','configuration','unit'],'d81-raw':['boundaries','sourceKind','endpointPolicy','coverageConfirmed','measurementUnit'],'d81-inverse':['boundaries','mode','cumulative','endpointPolicy','coverageConfirmed','measurementUnit'],'d81-line':['points','yRole','queryLower','queryUpper','endpointPolicy','coverageConfirmed','measurementUnit']}
class Bad(Exception):pass
class Need(Exception):pass
class Route(Exception):pass

def num(v,answer=False):
 b=10**256 if answer else 10**6
 if type(v)is int:
  if abs(v)>b:raise Route('超有限安全數域，保留原題轉方法，不判題目無解')
  return F(v)
 n=256 if answer else 12
 if type(v)is not str or len(v)>(520 if answer else 40)or not re.fullmatch(r'-?[0-9]{1,'+str(n)+r'}(?:/[1-9][0-9]{0,'+str(n-1)+r'}|\.[0-9]{1,'+str(n)+r'})?',v,re.ASCII):raise Bad('精確數格式不符，不收真假值、浮點、巨指數或任意算式')
 q=F(v)
 if abs(q)>b or not answer and q.denominator>10000:raise Route('原量或細分程度超此安全域，轉別法')
 return q

def en(v,choices):
 if type(v)is not str or v not in choices:raise Bad('形體、單位、構形或統計量角色不符')
 return v

def positive(v):
 q=num(v)
 if q<=0:raise Need('真實長度需正，原條件零或負先核對，不硬套形體公式')
 return q

def nonneg(v):
 q=num(v)
 if q<0:raise Need('此處原量須非負，先核對')
 return q

def integer(v):
 q=num(v)
 if q<0 or q.denominator!=1:raise Need('頻數/總人數需非負整數，不四捨五入假造人數')
 return q

def root(r=0,b=0):return {'rationalPart':str(F(r)),'sqrt3Coefficient':str(F(b))}
def length_unit(d):return en(d['unit'],['公分','公尺'])
def boundaries(v):
 if type(v)is not list or not 2<=len(v)<=9:raise Bad('本表限一至八個明定區間')
 e=[num(x)for x in v]
 if any(a>=b for a,b in zip(e,e[1:])):raise Need('組界需嚴格遞增且不重疊，先核原組界')
 return e

def stats_flags(d):
 en(d['endpointPolicy'],['left-closed-last-closed']);en(d['measurementUnit'],['分','公分','秒'])
 if type(d['coverageConfirmed'])is not bool:raise Bad('分類完整性需明確確認')
 if not d['coverageConfirmed']:raise Need('資料涵蓋與組別完整性未確認，不能自行當作全部樣本')

def table(e,counts):
 n=sum(counts,F(0));running=F(0);cum=[]
 for f in counts:running+=f;cum.append(running)
 rel=[str(f/n)if n else None for f in counts];cr=[str(c/n)if n else None for c in cum]
 points=[{'boundary':str(e[0]),'count':'0','relative':'0'if n else None,'upperInclusive':False}]+[{'boundary':str(edge),'count':str(c),'relative':r,'upperInclusive':i==len(cum)-1}for i,(edge,c,r)in enumerate(zip(e[1:],cum,cr))]
 return {'sampleSize':str(n),'frequencies':list(map(str,counts)),'relativeFrequencies':rel,'cumulativeFrequencies':list(map(str,cum)),'cumulativeRelativeFrequencies':cr,'relativeStatus':'defined'if n else'undefined-no-observations','points':points}

def observation_counts(obs,e):
 if type(obs)is not list or len(obs)>64:raise Bad('本原始資料模板限最多64筆確認觀察；更大資料轉其他批次方法')
 counts=[F(0)]*(len(e)-1)
 for v in obs:
  q=num(v)
  if q<e[0]or q>e[-1]:raise Need('觀察在已聲明完整組界外，先核資料/分類，不丟棄離群值')
  i=next(i for i in range(len(counts))if e[i]<=q and(q<e[i+1]or i==len(counts)-1 and q==e[i+1]));counts[i]+=1
 return counts

def check_declared_total(d,n):
 if d.get('sampleSize')is not None and integer(d['sampleSize'])!=n:raise Need('宣告總數與原資料/累積末值不一致，先核對，不改原總數')

def required(s,d):
 r=REQ[s][:]
 if s=='d81-raw'and d.get('sourceKind')in ['raw','frequency']:r+=['observations'if d['sourceKind']=='raw'else'frequencies']
 if s=='s87-attached'and d.get('otherKind')=='triangle':r+=['otherHeight']
 if s=='d81-inverse'and d.get('mode')in ['cumulative-relative','cumulative-percent']:r+=['sampleSize']
 if s=='d81-line'and d.get('yRole')in ['relative','percent']:r+=['sampleSize']
 return r

def compute(s,d):
 if s=='s87-equilateral':
  en(d['shape'],['equilateral']);s=positive(d['side']);u=length_unit(d)
  return {'height':root(0,s/2),'area':root(0,s*s/4),'lengthUnit':u,'areaUnit':'平方'+u}
 if s=='s87-attached':
  en(d['configuration'],['opposite-apices-over-shared-base-midpoint']);s=positive(d['side']);b=positive(d['otherBase']);kind=en(d['otherKind'],['triangle','equilateral']);u=length_unit(d)
  if b!=s:raise Need('聲明共完整底邊但兩底長不同，先核原構形，不能當作完全共底')
  if kind=='equilateral':
   if d.get('otherHeight')is not None:
    suppliedHeight=positive(d['otherHeight'])
    if 4*suppliedHeight*suppliedHeight!=3*s*s:raise Need('另附高度與正三角形邊長不一致，先核是否為近似值或抄錯，不忽略已給量')
   r=F(0);coef=s*s/2
  else:h=positive(d['otherHeight']);r=b*h/2;coef=s*s/4
  return {'equilateralArea':root(0,s*s/4),'attachedArea':root(0,s*s/4)if kind=='equilateral'else root(r,0),'totalArea':root(r,coef),'areaUnit':'平方'+u}
 if s=='s87-cutout':
  en(d['configuration'],['upright-equilateral-base-on-bottom']);l,h,s=positive(d['length']),positive(d['height']),positive(d['side']);offset=nonneg(d['baseOffset']);u=length_unit(d)
  if s>l or offset+s>l or 3*s*s>4*h*h:raise Need('此底邊位置與朝內正三角高度不能完全放進矩形，已確認旗標不覆蓋數值矛盾')
  return {'rectangleArea':root(l*h,0),'removedArea':root(0,s*s/4),'remainingArea':root(l*h,-s*s/4),'areaUnit':'平方'+u}
 stats_flags(d)
 if s=='d81-raw':
  e=boundaries(d['boundaries']);kind=en(d['sourceKind'],['raw','frequency']);rawCounts=None;givenCounts=None
  if d.get('observations')is not None:rawCounts=observation_counts(d['observations'],e)
  if d.get('frequencies')is not None:
   v=d['frequencies']
   if type(v)is not list or len(v)!=len(e)-1:raise Bad('原頻數表需逐組對應完整區間')
   givenCounts=[integer(f)for f in v]
  if rawCounts is not None and givenCounts is not None and rawCounts!=givenCounts:raise Need('原觀察與原頻數表矛盾，先核兩個來源，不挑一個蓋掉另一個')
  counts=rawCounts if kind=='raw'else givenCounts
  n=sum(counts,F(0));check_declared_total(d,n);return table(e,counts)
 if s=='d81-inverse':
  e=boundaries(d['boundaries']);mode=en(d['mode'],['cumulative-count','cumulative-relative','cumulative-percent']);vals=d['cumulative']
  if type(vals)is not list or len(vals)!=len(e)-1:raise Bad('累積列需與每個上組界一一對應')
  if mode=='cumulative-count':cum=[integer(v)for v in vals];n=cum[-1];check_declared_total(d,n)
  else:
   n=integer(d['sampleSize'])
   if n==0:
    if any(v is not None for v in vals):raise Need('零樣本沒有已定義相對次數，不能把0/0寫0或100%')
    return table(e,[F(0)]*(len(e)-1))
   ratio=[num(v)/(100 if mode=='cumulative-percent'else 1)for v in vals]
   if any(v<0 or v>1 for v in ratio)or ratio[-1]!=1:raise Need('完整累積相對資料須在0至1且末值1，先核總量/比例角色')
   cum=[v*n for v in ratio]
   if any(v.denominator!=1 for v in cum):raise Need('比例乘宣告樣本數不能得到整數人數，先核資料，不取整')
  if any(a>b for a,b in zip([F(0)]+cum,cum)):raise Need('累積次數不得下降，先核對排序或原讀值')
  counts=[b-a for a,b in zip([F(0)]+cum,cum)];return table(e,counts)
 if s=='d81-line':
  pts=d['points'];role=en(d['yRole'],['count','relative','percent'])
  if type(pts)is not list or not 2<=len(pts)<=9:raise Bad('本折線模板需完整二至九個已確認界點')
  for pt in pts:
   if type(pt)is not dict or set(pt)!={'boundary','value'}:raise Bad('原點表只收已確認組界與縱值，不能冒OCR')
  e=boundaries([p['boundary']for p in pts]);values=[p['value']for p in pts]
  if role=='count':cum=[integer(v)for v in values];n=cum[-1];check_declared_total(d,n)
  else:
   n=integer(d['sampleSize'])
   if n==0:
    if any(v is not None for v in values):raise Need('零樣本累積相對量未定義，不能畫成0%折線')
    cum=[F(0)]*len(values)
   else:
    ratio=[num(v)/(100 if role=='percent'else 1)for v in values]
    if any(v<0 or v>1 for v in ratio):raise Need('累積相對讀值超過0到1範圍，先核縱軸角色')
    cum=[v*n for v in ratio]
    if any(v.denominator!=1 for v in cum):raise Need('界點比例與總人數不一致，不取整造人數')
  if cum[0]!=0 or cum[-1]!=n or any(a>b for a,b in zip(cum,cum[1:])):raise Need('完整累積界點首0末總數且不下降，請核軸刻度/資料')
  lo,hi=num(d['queryLower']),num(d['queryUpper'])
  if lo not in e or hi not in e:raise Need('所問位置不是已確認組界，僅靠分組累積圖不能推精確組內數，不插值冒真頻數')
  il,ih=e.index(lo),e.index(hi)
  if il>=ih:raise Need('詢問區間的左界須小於右界，先核原題')
  result=table(e,[b-a for a,b in zip(cum,cum[1:])]);k=cum[ih]-cum[il]
  result.update(queryCount=str(k),queryRelative=str(k/n)if n else None,lowerInclusive=True,upperInclusive=ih==len(e)-1,queryLower=str(lo),queryUpper=str(hi));return result
 raise Bad('未知型')

NUMERIC={'rationalPart','sqrt3Coefficient','sampleSize','boundary','count','relative','queryCount','queryRelative','queryLower','queryUpper','value'}
NUMERIC_LIST={'frequencies','relativeFrequencies','cumulativeFrequencies','cumulativeRelativeFrequencies'}
def equivalent(p,a,key=''):
 try:
  if a is None:return p is None
  if type(a)is bool:return type(p)is bool and p==a
  if type(a)is dict:return type(p)is dict and set(p)==set(a)and all(equivalent(p[k],v,k)for k,v in a.items())
  if type(a)is list:return type(p)is list and len(p)==len(a)and all(equivalent(v,w,'value'if key in NUMERIC_LIST else key)for v,w in zip(p,a))
  if key in NUMERIC:return num(p,True)==num(a,True)
  return type(p)is str and p==a
 except(Bad,Route,ValueError,TypeError,OverflowError,ZeroDivisionError):return False

def evaluate(s,d):
 def out(k,a=None,why=''):return {'decision':k,'answer':a,'reason':why}
 if type(s)is not str or s not in SUBTYPES or type(d)is not dict:return out('block',why='非本有限文字方法')
 if any(d.get(k)is None for k in required(s,d)+['factsConfirmed']):return out('confirm',why='必要原量/組界/角色/原圖條件未明，先核原題')
 try:zeroRelative=num(d.get('sampleSize'))==0
 except(Bad,Route,ValueError,TypeError,OverflowError,ZeroDivisionError):zeroRelative=False
 if s=='d81-raw'and type(d.get('observations'))is list and len(d['observations'])<=64 and any(v is None for v in d['observations']):return out('confirm',why='原觀察值有缺量，先補清，不自行丟棄')
 if s=='d81-raw'and type(d.get('frequencies'))is list and len(d['frequencies'])<=8 and any(v is None for v in d['frequencies']):return out('confirm',why='原頻數表缺組數，先補完整，不假設0')
 if s in ['d81-raw','d81-inverse']and type(d['boundaries'])is list and len(d['boundaries'])<=9 and any(v is None for v in d['boundaries']):return out('confirm',why='原組界缺值，先核區間端點')
 if s=='d81-inverse'and type(d['cumulative'])is list and len(d['cumulative'])<=8 and any(v is None for v in d['cumulative'])and not(zeroRelative and d.get('mode')in ['cumulative-relative','cumulative-percent']):return out('confirm',why='必要累積值缺漏，先核原表')
 if s=='d81-line'and type(d['points'])is list and len(d['points'])<=9:
  if any(type(p)is dict and(p.get('boundary')is None or p.get('value')is None and not(zeroRelative and d.get('yRole')in ['relative','percent']))for p in d['points']):return out('confirm',why='必要界點或原縱值未明，先核圖，不猜像素')
 allowed=set(REQ[s])|{'factsConfirmed','task','proposal'}
 if s=='s87-attached':allowed.add('otherHeight')
 if s.startswith('d81-'):allowed.add('sampleSize')
 if s=='d81-raw':allowed.update(['observations','frequencies'])
 if set(d)-allowed:return out('block',why='未知額外欄不冒原條件')
 if type(d['factsConfirmed'])is not bool:return out('block',why='確認狀態需明確真假')
 if not d['factsConfirmed']:return out('confirm',why='原幾何/原圖/樣本條件尚未確認')
 if type(d.get('task'))is not str or d['task']not in ['solve','check_proposal']:return out('block',why='未知任務')
 try:a=compute(s,d)
 except Need as e:return out('confirm',why=str(e))
 except(Bad,Route,ValueError,TypeError,OverflowError,ZeroDivisionError,StopIteration)as e:return out('block',why=str(e))
 if d['task']=='check_proposal':
  if d.get('proposal')is None:return out('confirm',a,'先提供待核想法，保留原結論')
  if not equivalent(d['proposal'],a):return out('reject',a,'只拒錯提案，保留由原條件重算的精確結論')
 return out('pass',a,'精確根式/已確認原資料重算，不宣稱OCR或實測')

def check():
 p=json.load(open(pathlib.Path(__file__).with_name(PACK+'.json')))
 for s in SUBTYPES:assert collections.Counter(c['kind']for c in p['cases']if c['subtypeId']==s)==dict(normal=8,negative=6,boundary=4,ambiguous=2,holdout=4)
 for c in p['cases']:
  r=evaluate(c['subtypeId'],c['input']);assert(r['decision'],r['answer'])==(c['expectedDecision'],c['expectedAnswer']),c['id']
 print(json.dumps({'package':PACK,'cases':len(p['cases']),'passed':True}))
if __name__=='__main__':
 if len(sys.argv)>1 and sys.argv[1]=='evaluate':
  try:
   raw=sys.stdin.read(65537)
   if len(raw)>65536:raise ValueError('request too large')
   q=json.loads(raw)
   if type(q)is not dict:raise ValueError('request must be an object')
   result=evaluate(q.get('subtypeId'),q.get('input'))
  except(ValueError,TypeError,RecursionError,OverflowError):
   result=dict(decision='block',answer=None,reason='請求JSON格式、大小或巢狀深度超出此有限文字方法')
  print(json.dumps(result,ensure_ascii=False))
 else:check()
