import pathlib,json,sys,re,copy
from fractions import Fraction
PACK='grade6-prism-methods'
SUBTYPES=['s64-prism-volume', 's64-prism-surface', 's64-two-prism-volume']
REQ={'s62-numeric-scale':['target','scaleDenominator','givenLength','givenUnit','outputUnit','scaleAppliesToMeasuredMap'],'s62-graphic-scale':['barPrintedCm','barRealLength','barRealUnit','routePrintedCm','outputUnit','sameVersionConfirmed','sameScalingConfirmed','physicalMeasurementConfirmed'],'s62-two-maps':['scaleA','scaleB','lengthACm','sameRouteConfirmed','scalesApplyConfirmed'],'s64-prism-volume':['prism'],'s64-prism-surface':['prism','closedConfirmed','baseEdgeCorrespondenceConfirmed'],'s64-two-prism-volume':['operation','prisms','placementRelation']}
UNITS={'cm':1,'m':100,'km':100000};ZH={'cm':'公分','m':'公尺','km':'公里'}
class Ask(Exception):pass
class Guard(Exception):pass
def out(d,a=None,r=''):return dict(decision=d,answer=a,reason=r)
def bounded(v,depth=0):
 if depth>8:raise Guard('結構過深')
 if type(v)is dict:
  if len(v)>24 or any(type(k)is not str or len(k)>64 for k in v):raise Guard('欄位過多')
  for x in v.values():bounded(x,depth+1)
 elif type(v)is list:
  if len(v)>12:raise Guard('列表過長')
  for x in v:bounded(x,depth+1)
 elif type(v)is str and len(v)>256:raise Guard('字串過長')
 elif type(v)is int and abs(v)>10**18:raise Guard('原量字面過大')
def need(r,k):
 if k not in r or r[k]is None:raise Ask('先補必要原量、單位或外部已確認關係，不猜照片')
 return r[k]
def keys(r,req,optional=()):
 if type(r)is not dict:raise Guard('需結構化原量')
 for k in req:need(r,k)
 if set(r)-set(req)-set(optional):raise Guard('未知欄位')
def flag(v):
 if type(v)is not bool:raise Guard('確認欄需布林')
 return v
def known(v):
 if not flag(v):raise Ask('先取得完整外部觀察確認，不從外觀補值')
def integer(v,lo=1,hi=10**8):
 if type(v)is not int or not lo<=v<=hi:raise Guard('整數超有限域或型別錯誤')
 return v
def number(v,original=False):
 limit=64 if original else 256
 if type(v)is int:
  if abs(v)>(10**6 if original else 10**30):raise Guard('數字過大')
  f=Fraction(v)
 elif type(v)is str and 1<=len(v)<=limit and re.fullmatch(r'[+-]?(?:[0-9]+(?:/[0-9]+|\.[0-9]{1,64})?|\.[0-9]{1,64})',v,re.ASCII):
  if '/'in v and not any(c!='0'for c in v.split('/')[1]):raise Guard('分母0')
  f=Fraction(v)
 else:raise Guard('只讀有限整數/分數/有限小數，不讀布林浮點指數')
 if original and(not 0<=f<=10**6 or f.denominator>1000):raise Guard('原量0..100萬且最簡分母至1000')
 if abs(f)>10**30:raise Guard('衍生數量過大')
 return f
def txt(f):return str(f)
def positive(v):
 f=number(v,True)
 if f<=0:raise Guard('實體長度或底面積須正')
 return f
def enum(v,vs):
 if type(v)is not str or v not in vs:raise Guard('枚舉值不合')
 return v
def unit(v):return enum(v,UNITS)
def areaunit(u):return '平方'+ZH[u]
def volunit(u):return '立方'+ZH[u]
def nested_preflight(s,r):
 # Small schema-defined containers only; resource envelope has already been bounded.
 if s=='s62-numeric-scale'and r.get('target')=='compare-two-lengths'and type(r.get('givenLength'))is list and len(r['givenLength'])==2 and any(v is None for v in r['givenLength']):raise Ask('兩段圖距有缺量，先確認')
 def base(b):
  if type(b)is not dict:return
  kind=need(b,'kind');fields={'triangle':['baseLength','baseAltitude','altitudeRole','shapeConfirmed'],'rectangle':['length','width','shapeConfirmed'],'parallelogram':['sideA','sideB','baseAltitude','altitudeRole','shapeConfirmed'],'trapezoid':['top','bottom','baseAltitude','altitudeRole','shapeConfirmed'],'verified-quadrilateral':['area','areaVerified','shapeConfirmed'],'right-triangle':['legA','legB','hypotenuse','rightAngleConfirmed','shapeConfirmed'],'circle':['measure','measureRole','centerConfirmed','shapeConfirmed']}
  if type(kind)is str and kind in fields:
   for k in fields[kind]:need(b,k)
 def prism(p):
  if type(p)is not dict:return
  for k in ['base','height','heightRole','unit','parallelCongruentBasesConfirmed','constantSectionConfirmed','rightPrismConfirmed']:need(p,k)
  base(p['base'])
 if s in ('s64-prism-volume','s64-prism-surface'):
  if 'prism'in r:prism(r['prism'])
  p=r.get('prism')
  if type(p)is dict and type(p.get('base'))is dict and p['base'].get('kind')=='circle':need(r,'piRule')
 elif s=='s64-two-prism-volume'and type(r.get('prisms'))is list and len(r['prisms'])==2:
  for p in r['prisms']:
   if p is None:raise Ask('先補兩柱的原資料')
   prism(p)
  if any(type(p)is dict and type(p.get('base'))is dict and p['base'].get('kind')=='circle'for p in r['prisms']):need(r,'piRule')
def base_values(b,surface=False):
 kind=enum(need(b,'kind'),['triangle','rectangle','parallelogram','trapezoid','verified-quadrilateral','right-triangle','circle']);common=['kind','shapeConfirmed'];known(need(b,'shapeConfirmed'))
 if surface and kind not in ['rectangle','parallelogram','right-triangle','circle']:raise Guard('表面積本型只四種已核底形，不擴到任意底形')
 if kind=='circle':
  keys(b,common+['measure','measureRole','centerConfirmed']);known(b['centerConfirmed']);v=positive(b['measure']);role=enum(b['measureRole'],['radius','diameter']);rad=v if role=='radius'else v/2
  return dict(kind=kind,areaConstant=Fraction(0),areaPi=rad*rad,perimeterConstant=Fraction(0),perimeterPi=2*rad,radius=rad)
 if kind=='rectangle':
  keys(b,common+['length','width']);a=positive(b['length']);c=positive(b['width']);ar=a*c;per=2*(a+c);dims=[a,c]
 elif kind=='triangle':
  keys(b,common+['baseLength','baseAltitude','altitudeRole']);a=positive(b['baseLength']);h=positive(b['baseAltitude']);enum(b['altitudeRole'],['perpendicular-to-base']);ar=a*h/2;per=None;dims=[a,h]
 elif kind=='parallelogram':
  keys(b,common+['sideA','sideB','baseAltitude','altitudeRole']);a=positive(b['sideA']);c=positive(b['sideB']);h=positive(b['baseAltitude']);enum(b['altitudeRole'],['perpendicular-to-sideA'])
  if h>c:raise Guard('底高比相鄰邊長還長，已確認資料矛盾')
  ar=a*h;per=2*(a+c);dims=[a,c,h]
 elif kind=='trapezoid':
  keys(b,common+['top','bottom','baseAltitude','altitudeRole']);a=positive(b['top']);c=positive(b['bottom']);h=positive(b['baseAltitude']);enum(b['altitudeRole'],['perpendicular-between-parallel-bases']);ar=(a+c)*h/2;per=None;dims=[a,c,h]
 elif kind=='verified-quadrilateral':
  keys(b,common+['area','areaVerified']);known(b['areaVerified']);ar=positive(b['area']);per=None;dims=[]
 else:
  keys(b,common+['legA','legB','hypotenuse','rightAngleConfirmed']);known(b['rightAngleConfirmed']);a=positive(b['legA']);c=positive(b['legB']);z=positive(b['hypotenuse'])
  # Engineering consistency only. No Pythagorean algorithm taught to grade6 students.
  if a*a+c*c!=z*z:raise Guard('外部已確認的直角底三邊矛盾，請重新量測')
  ar=a*c/2;per=a+c+z;dims=[a,c,z]
 return dict(kind=kind,areaConstant=ar,areaPi=Fraction(0),perimeterConstant=per,perimeterPi=Fraction(0),dims=dims)
def prism_values(p,surface=False):
 req=['base','height','heightRole','unit','parallelCongruentBasesConfirmed','constantSectionConfirmed','rightPrismConfirmed'];keys(p,req)
 known(p['parallelCongruentBasesConfirmed']);known(p['constantSectionConfirmed']);known(p['rightPrismConfirmed']);enum(p['heightRole'],['perpendicular-between-bases']);u=enum(p['unit'],['cm','m']);h=positive(p['height']);b=base_values(p['base'],surface);return b,h,u

def exact_output(c,k,pi):
 if k==0:return txt(c)
 return txt(c+k*Fraction(314,100))if pi=='3.14'else None

def compute(s,r):
 if s.startswith('s62-'):
  if s=='s62-numeric-scale':
   target=enum(r['target'],['real-distance','map-distance','compare-two-lengths']);n=integer(r['scaleDenominator']);gu=unit(r['givenUnit']);ou=unit(r['outputUnit']);known(r['scaleAppliesToMeasuredMap'])
   if target=='compare-two-lengths':
    if gu!='cm'or type(r['givenLength'])is not list or len(r['givenLength'])!=2:raise Guard('兩段圖距須同版實測公分兩值')
    x=number(r['givenLength'][0],True);y=positive(r['givenLength'][1]);a=x*n/UNITS[ou];b=y*n/UNITS[ou]
    return dict(firstReal=txt(a),secondReal=txt(b),mapRatio=txt(x/y),realRatio=txt(a/b),unit=ZH[ou],sameRatio=True)
   v=number(r['givenLength'],True)
   if target=='real-distance':
    if gu!='cm':raise Guard('本型圖上原量以實測公分給定，不用像素')
    mc=v;rc=mc*n;value=rc/UNITS[ou]
   else:
    if ou!='cm':raise Guard('圖上結果本型固定公分')
    rc=v*UNITS[gu];mc=rc/n;value=mc
   return dict(value=txt(value),unit=ZH[ou],mapCm=txt(mc),realCm=txt(rc),scaleDenominator=n)
  if s=='s62-graphic-scale':
   bp=positive(r['barPrintedCm']);real=positive(r['barRealLength']);ru=unit(r['barRealUnit']);route=number(r['routePrintedCm'],True);ou=unit(r['outputUnit'])
   for k in ['sameVersionConfirmed','sameScalingConfirmed','physicalMeasurementConfirmed']:known(r[k])
   segments=route/bp;rc=real*UNITS[ru]*segments;return dict(segments=txt(segments),realCm=txt(rc),value=txt(rc/UNITS[ou]),unit=ZH[ou])
  a=integer(r['scaleA']);b=integer(r['scaleB']);length=number(r['lengthACm'],True);known(r['sameRouteConfirmed']);known(r['scalesApplyConfirmed']);rc=length*a;other=rc/b;return dict(lengthBCm=txt(other),realCm=txt(rc),conversionFactor=txt(Fraction(a,b)),mapBComparedToA='較長'if other>length else'較短'if other<length else'相同',unit='公分')
 if s in ('s64-prism-volume','s64-prism-surface'):
  surface=s=='s64-prism-surface'
  if surface:
   if not flag(r['closedConfirmed']):raise Guard('已知有開口，不套封閉完整表面積')
   known(r['baseEdgeCorrespondenceConfirmed'])
  b,h,u=prism_values(r['prism'],surface);c,k=b['areaConstant'],b['areaPi'];pi=enum(need(r,'piRule'),['symbolic','3.14'])if k else'not-applicable'
  if not surface:return dict(baseArea=exact_output(c,k,pi),baseAreaPiCoefficient=txt(k)if k else None,volume=exact_output(c*h,k*h,pi),volumePiCoefficient=txt(k*h)if k else None,piRule=pi,approximate=bool(k and pi=='3.14'),areaUnit=areaunit(u),volumeUnit=volunit(u))
  sidec=b['perimeterConstant']*h;sidek=b['perimeterPi']*h;return dict(baseArea=exact_output(c,k,pi),baseAreaPiCoefficient=txt(k)if k else None,sideArea=exact_output(sidec,sidek,pi),sideAreaPiCoefficient=txt(sidek)if sidek else None,surface=exact_output(2*c+sidec,2*k+sidek,pi),surfacePiCoefficient=txt(2*k+sidek)if 2*k+sidek else None,piRule=pi,approximate=bool(k and pi=='3.14'),areaUnit=areaunit(u))
 op=enum(r['operation'],['combine','remove']);ps=r['prisms']
 if type(ps)is not list or len(ps)!=2:raise Guard('僅兩柱簡單組合，不擴多形體')
 vals=[prism_values(p)for p in ps];knownrelation=enum(r['placementRelation'],['non-overlapping-connected','aligned-contained','coaxial-contained','unconfirmed'])
 if knownrelation=='unconfirmed':raise Ask('先外部確認不重疊接合或完全包含移除，不從輪廓猜')
 u=vals[0][2]
 if any(v[2]!=u for v in vals):raise Guard('兩柱需同單位，本型不猜單位換算')
 terms=[(b['areaConstant']*h,b['areaPi']*h)for b,h,_ in vals];haspi=any(k for c,k in terms);pi=enum(need(r,'piRule'),['symbolic','3.14'])if haspi else'not-applicable'
 if op=='combine':
  if knownrelation!='non-overlapping-connected':raise Ask('相加需已確認只接面且體積不重疊')
  c,k=map(sum,zip(*terms))
 else:
  if knownrelation=='aligned-contained':
   if any(b['kind']!='rectangle'for b,h,u in vals):raise Guard('本有限矩形挖空需兩長方直柱、對應方向一致')
   outer,inner=vals
   if any(a<b for a,b in zip(outer[0]['dims']+[outer[1]],inner[0]['dims']+[inner[1]])):raise Guard('長寬高對應不容納，不能用確認旗標覆蓋')
  elif knownrelation=='coaxial-contained':
   if any(b['kind']!='circle'for b,h,u in vals):raise Guard('同軸圓柱挖空需兩圓柱')
   if vals[1][0]['radius']>vals[0][0]['radius']or vals[1][1]>vals[0][1]:raise Guard('半徑或高不容納，不能假稱完全包含')
  else:raise Ask('移除須已確認兩柱完全包含及本型明列對齊關係')
  c=terms[0][0]-terms[1][0];k=terms[0][1]-terms[1][1]
  if c<0 or k<0:raise Guard('移除量超過原量')
 return dict(partVolumes=[dict(constant=txt(c),piCoefficient=txt(k))for c,k in terms],resultConstant=txt(c),resultPiCoefficient=txt(k),value=exact_output(c,k,pi),piRule=pi,approximate=bool(k and pi=='3.14'),volumeUnit=volunit(u))

def equivalent(p,a,key=''):
 if type(a)is bool:return type(p)is bool and p==a
 if a is None:return p is None
 if type(a)is int or type(a)is str and re.fullmatch(r'[+-]?[0-9]+(?:/[0-9]+)?',a):
  try:return number(p)==number(a)
  except Guard:return False
 if type(a)is str:return type(p)is str 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(x,y)for x,y in zip(p,a))
 return False

def evaluate(s,r):
 try:
  if type(s)is not str or s not in SUBTYPES or type(r)is not dict:raise Guard('不屬本有限題型')
  bounded({k:v for k,v in r.items()if k!='proposal'})
  for k in ['confirmed','task',*REQ[s]]:need(r,k)
  nested_preflight(s,r)
  known(r['confirmed']);enum(r['task'],['solve','check_proposal'])
  if set(r)-set(REQ[s])-{'confirmed','task','proposal'}-({'piRule'}if s.startswith('s64-')else set()):raise Guard('未知原欄位')
  if 'piRule'in r:enum(r['piRule'],['symbolic','3.14'])
  ans=compute(s,r)
  if r['task']=='solve':return out('pass',ans,'只核外部已確認原量，未識圖/實物驗證')
  if r.get('proposal')is None:raise Ask('先補待核提案')
  ok=equivalent(r['proposal'],ans);return out('pass'if ok else'reject',ans,'保留可算正解並核數值、單位、π與量角色')
 except Ask as e:return out('confirm',r=str(e))
 except(Guard,ValueError,TypeError,KeyError,ZeroDivisionError,OverflowError)as e:return out('block',r=str(e))
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()
 p=pathlib.Path(__file__).with_name(PACK+'.json');d=json.load(open(p));bad=[]
 for c in d['cases']:
  x=evaluate(c['subtypeId'],c['input'])
  if (x['decision'],x['answer'])!=(c['expectedDecision'],c['expectedAnswer']):bad.append(c['id'])
 print(json.dumps(dict(ok=not bad,cases=len(d['cases']),errors=bad),ensure_ascii=False));sys.exit(bool(bad))
