#!/usr/bin/env python3
"""Bounded structured proofs and confirmed models; not free-text/OCR/physical assessment."""
import sys,json,math,re,pathlib,copy
from fractions import Fraction
TYPES={'s911-algebra-proof','s911-geometric-proof'}
REQ={
's911-geometric-proof':['leg','base','midpointConfirmed','collinearBetweenConfirmed','goal'],
's911-algebra-proof':['p','q'],
's912-cuboid-lines':['length','width','height','edgeA','edgeB','cuboidRolesConfirmed'],
's912-cuboid-line-plane':['length','width','height','line','face','cuboidRolesConfirmed'],
's912-tetrahedron-relations':['edgeLength','query','vertexOrder','regularModelConfirmed'],
'd93-uniform-single':['outcomes','favourable','equalLikelihoodConfirmed','completeSpaceConfirmed'],
'd93-ordered-balls':['red','blue','replacement','event','uniformIndividualDrawConfirmed'],
'd93-asymmetric-frequency':['objectKind','rounds','sameMechanismConfirmed']}
class Ask(Exception):pass
class Bound(Exception):pass
def shape(v,depth=0,budget=None):
 if budget is None:budget=[0]
 budget[0]+=1
 if budget[0]>2048 or depth>14:raise Bound('資料結構過深或過多')
 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 Bound('欄位不符')
  for x in v.values():shape(x,depth+1,budget)
 elif type(v)is list:
  if len(v)>64:raise Bound('清單過長')
  for x in v:shape(x,depth+1,budget)
 elif type(v)is str and len(v)>160:raise Bound('文字過長')
 elif type(v)is int and abs(v)>10**12:raise Bound('數量過大')
 elif type(v)not in (str,int,bool,float,type(None)):raise Bound('資料型別不符')
def need(r,k):
 if k not in r or r[k]is None:raise Ask('請先補清原題缺少的數量、指定目標或幾何／實驗條件')
 return r[k]
def exact(v):
 if type(v)is int and abs(v)<=10**12:return Fraction(v)
 if type(v)is str and len(v)<=40 and re.fullmatch(r'-?[0-9]{1,12}(?:/[0-9]{1,12}|\.[0-9]{1,8})?',v,re.ASCII):
  if '/'in v and int(v.split('/')[1])==0:raise Bound('分母不可為0')
  f=Fraction(v)
  if abs(f)<=10**12:return f
 raise Bound('須用有界整數、分數或有限小數；不讀指數或任意算式')
def nat(v,lo=0,hi=1000):
 if type(v)is not int or not lo<=v<=hi:raise Bound('原量須為範圍內整數')
 return v
def positive(v):
 q=exact(v)
 if not 0<q<=100 or q.denominator>100:raise Bound('長度須正且在本型有界範圍')
 return q
def flag(r,k):
 if type(r[k])is not bool:raise Bound('確認值須為布林')
 if not r[k]:raise Ask('此方法須先確認原題明給的條件，不從外觀或名稱猜測')
def choice(v,options):
 if type(v)is not str or v not in options:raise Bound('不在本型指定選項')
 return v
def text(f):return str(f.numerator)if f.denominator==1 else str(f.numerator)+'/'+str(f.denominator)
def bounded_missing(s,r):
 if s=='d93-uniform-single'and type(r.get('outcomes'))is list and len(r['outcomes'])<=52:
  for row in r['outcomes']:
   if type(row)is dict:
    for k in ('label','weight'):need(row,k)
 elif s=='d93-asymmetric-frequency'and type(r.get('rounds'))is list and len(r['rounds'])<=4:
  for row in r['rounds']:
   if type(row)is dict:
    for k in ('trials','successes'):need(row,k)
 elif s=='s912-tetrahedron-relations'and type(r.get('vertexOrder'))is list and len(r['vertexOrder'])<=4:
  if any(x is None for x in r['vertexOrder']):raise Ask('請補清四面體頂點角色')
# Finite geometric proof kernel: premises must precede every inference; goal is never a premise.
RULES={
 'SSS':('congruent',{'equal-legs','equal-halves','common-side'}),
 'isosceles-base-angles':('base-angles-equal',{'equal-legs','collinear-between'}),
 'SAS':('congruent',{'equal-legs','equal-halves','base-angles-equal','collinear-between'}),
 'corresponding-middle-angles':('middle-angles-equal',{'congruent'}),
 'corresponding-base-angles':('base-angles-equal',{'congruent'}),
 'linear-pair':('middle-sum-180',{'collinear-between'}),
 'equal-halves-of-flat-angle':('middle-angles-90',{'middle-angles-equal','middle-sum-180'}),
 'perpendicular-definition':('perpendicular',{'middle-angles-90'})}
GIVEN={'equal-legs','equal-halves','common-side','collinear-between'}
def geo_proof(goal,route='SSS'):
 seq=[dict(rule='given',claim=x)for x in ('equal-legs','equal-halves','common-side','collinear-between')]
 if route=='SAS':seq.append(dict(rule='isosceles-base-angles',claim='base-angles-equal'))
 seq.append(dict(rule=route,claim='congruent'))
 if goal=='base-angles-equal':seq.append(dict(rule='corresponding-base-angles',claim=goal))
 else:seq.extend([dict(rule='corresponding-middle-angles',claim='middle-angles-equal'),dict(rule='linear-pair',claim='middle-sum-180'),dict(rule='equal-halves-of-flat-angle',claim='middle-angles-90'),dict(rule='perpendicular-definition',claim='perpendicular')])
 return seq
def valid_geo(v,ans):
 if type(v)is not dict or set(v)!={'goal','conclusionEstablished','proof'}or v['goal']!=ans['goal']or v['conclusionEstablished']is not True:return False
 steps=v['proof']
 if type(steps)is not list or not 1<=len(steps)<=16:return False
 facts=set()
 for step in steps:
  if type(step)is not dict or set(step)!={'rule','claim'}:return False
  rule,claim=step['rule'],step['claim']
  if type(rule)is not str or type(claim)is not str:return False
  if rule=='given':
   if claim not in GIVEN:return False
  elif rule in RULES:
   expected,deps=RULES[rule]
   if claim!=expected or not deps<=facts:return False
  elif rule in ('AAA','assume-goal','looks-equal','numeric-example-only'):return False
  else:raise Ask('這個證明理由尚未在有限核對範圍，請老師核對，不據此判成錯誤')
  facts.add(claim)
 return ans['goal']in facts
# Degree <=2 polynomial kernel. The expression tree and justification must both match.
def padd(a,b,sgn=1):
 out=dict(a)
 for k,v in b.items():out[k]=out.get(k,Fraction(0))+sgn*v
 return {k:v for k,v in out.items()if v}
def pmul(a,b):
 out={}
 for (i,j),x in a.items():
  for (k,l),y in b.items():
   if i+j+k+l>2:raise Bound('只處理本型二次多項式')
   key=(i+k,j+l);out[key]=out.get(key,Fraction(0))+x*y
 return {k:v for k,v in out.items()if v}
def poly(e,depth=0):
 if depth>7:raise Bound('算式過深')
 if type(e)is str and e in ('x','y'):return {(1,0)if e=='x'else(0,1):Fraction(1)}
 if type(e)is not list:
  q=exact(e)
  if abs(q)>10**6:raise Bound('係數過大')
  return {(0,0):q}if q else{}
 if len(e)not in (2,3)or type(e[0])is not str:raise Bound('有限算式樹格式不符')
 op=e[0]
 if op=='sq'and len(e)==2:
  p=poly(e[1],depth+1);return pmul(p,p)
 if op not in ('add','sub','mul')or len(e)!=3:raise Bound('未知算式運算')
 a,b=poly(e[1],depth+1),poly(e[2],depth+1)
 return pmul(a,b)if op=='mul'else padd(a,b,-1 if op=='sub'else 1)
def expression_start(p,q):
 u=['add',['mul',p,'x'],['mul',q,'y']];v=['sub',['mul',p,'x'],['mul',q,'y']]
 return ['sub',['sq',u],['sq',v]]
def expression_final(p,q):return ['mul',4*p*q,['mul','x','y']]
def monomial(e):
 if type(e)is not list:
  try:poly(e);return True
  except Bound:return False
 if len(e)==2 and e[0]=='sq':return type(e[1])is str and e[1]in ('x','y')or type(e[1])is int
 return len(e)==3 and e[0]=='mul'and monomial(e[1])and monomial(e[2])
def expanded(e):
 if type(e)is list and len(e)==3 and e[0]in ('add','sub'):return expanded(e[1])and expanded(e[2])
 return monomial(e)
def has_composite_square(e):
 if type(e)is not list:return False
 return len(e)==2 and e[0]=='sq'and type(e[1])is list or any(has_composite_square(x)for x in e[1:])
def algebra_proof(p,q,route='expand'):
 start=expression_start(p,q);final=expression_final(p,q)
 if route=='factor':
  u,v=start[1][1],start[2][1];factor=['mul',['add',u,v],['sub',u,v]]
  reduced=['mul',['mul',2*p,'x'],['mul',2*q,'y']]
  return [dict(expression=start,reason='start'),dict(expression=factor,reason='difference-of-squares'),dict(expression=reduced,reason='simplify-factors'),dict(expression=final,reason='combine-like-terms')]
 a=['mul',p*p,['sq','x']];b=['mul',2*p*q,['mul','x','y']];c=['mul',q*q,['sq','y']]
 expansion=['sub',['add',['add',a,b],c],['add',['sub',copy.deepcopy(a),copy.deepcopy(b)],copy.deepcopy(c)]]
 return[dict(expression=start,reason='start'),dict(expression=expansion,reason='multiplication-formulas'),dict(expression=final,reason='combine-like-terms')]
def valid_algebra(v,ans,p,q):
 if type(v)is not dict or set(v)!={'identityCoefficient','holdsForAllRealXY','proof'}or v['holdsForAllRealXY']is not True or exact(v['identityCoefficient'])!=4*p*q:return False
 steps=v['proof']
 if type(steps)is not list or not 2<=len(steps)<=10:return False
 if type(steps[0])is not dict or set(steps[0])!={'expression','reason'}or steps[0]['reason']!='start'or steps[0]['expression']!=expression_start(p,q):return False
 prev=steps[0]['expression'];target=poly(expression_final(p,q))
 for row in steps[1:]:
  if type(row)is not dict or set(row)!={'expression','reason'}or type(row['reason'])is not str:return False
  nxt=row['expression'];rule=row['reason']
  if poly(prev)!=poly(nxt):return False
  if rule=='difference-of-squares':
   if not(type(prev)is list and prev[0]=='sub'and type(prev[1])is list and prev[1][0]=='sq'and type(prev[2])is list and prev[2][0]=='sq'and type(nxt)is list and len(nxt)==3 and nxt[0]=='mul'):return False
   u,vv=poly(prev[1][1]),poly(prev[2][1]);factors=[poly(nxt[1]),poly(nxt[2])];plus,minus=padd(u,vv),padd(u,vv,-1)
   if not(factors==[plus,minus]or factors==[minus,plus]):return False
  elif rule=='multiplication-formulas':
   if not has_composite_square(prev)or not expanded(nxt):return False
  elif rule=='simplify-factors':
   if not(type(prev)is list and prev[0]=='mul'and type(nxt)is list and nxt[0]=='mul'):return False
   pa,pb=poly(prev[1]),poly(prev[2]);na,nb=poly(nxt[1]),poly(nxt[2])
   if not([pa,pb]==[na,nb]or[pa,pb]==[nb,na]):return False
  elif rule=='distributive-law':
   if not(type(prev)is list and prev[0]=='mul'and not expanded(prev)and expanded(nxt)):return False
  elif rule=='combine-like-terms':
   if not expanded(prev)or not expanded(nxt):return False
  elif rule in ('start','AAA','numeric-example-only','assume-goal','looks-equal'):return False
  else:raise Ask('這個代數理由尚未在有限核對範圍，請老師核對，不只因說法不同判錯')
  prev=nxt
 return poly(prev)==target and expanded(prev)
VERTS={'A':(0,0,0),'B':(1,0,0),'C':(1,1,0),'D':(0,1,0),'E':(0,0,1),'F':(1,0,1),'G':(1,1,1),'H':(0,1,1)}
EDGES=['AB','BC','CD','AD','EF','FG','GH','EH','AE','BF','CG','DH']
FACES={'ABCD':(2,0),'EFGH':(2,1),'ABFE':(1,0),'DCGH':(1,1),'ADHE':(0,0),'BCGF':(0,1)}
def vertices(r):
 dims=[positive(r[k])for k in ('length','width','height')]
 return {k:tuple(Fraction(v[i])*dims[i]for i in range(3))for k,v in VERTS.items()}
def line(v,edge,edgesOnly=False):
 if type(edge)is not str or len(edge)!=2 or any(k not in v for k in edge)or edge[0]==edge[1]:raise Bound('線須由兩個不同已知頂點指定')
 if edgesOnly and ''.join(sorted(edge))not in EDGES:raise Bound('此線線型首包只評量稜所在直線')
 return v[edge[0]],tuple(v[edge[1]][i]-v[edge[0]][i]for i in range(3))
def cross(a,b):return(a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0])
def dot(a,b):return sum(x*y for x,y in zip(a,b))
def compute(s,r):
 if s=='s911-geometric-proof':
  a,b=positive(r['leg']),positive(r['base'])
  if b>=2*a:raise Ask('已知等腰邊與底邊無法成非退化三角形，先核對原條件')
  flag(r,'midpointConfirmed');flag(r,'collinearBetweenConfirmed');goal=choice(r['goal'],{'perpendicular','base-angles-equal'})
  return dict(goal=goal,conclusionEstablished=True,proof=geo_proof(goal))
 if s=='s911-algebra-proof':
  p,q=nat(r['p'],-9,9),nat(r['q'],-9,9)
  return dict(identityCoefficient=4*p*q,holdsForAllRealXY=True,proof=algebra_proof(p,q))
 if s in ('s912-cuboid-lines','s912-cuboid-line-plane'):
  flag(r,'cuboidRolesConfirmed');v=vertices(r)
  if s=='s912-cuboid-lines':
   a,u=line(v,r['edgeA'],True);b,w=line(v,r['edgeB'],True);diff=tuple(b[i]-a[i]for i in range(3));cr=cross(u,w)
   if not any(cr):relation='coincident'if not any(cross(diff,u))else'parallel';intersection='all-points'if relation=='coincident'else'none'
   elif dot(diff,cr)!=0:relation='skew';intersection='none'
   else:relation='perpendicular'if dot(u,w)==0 else'intersecting-nonright';intersection='one-point'
   return dict(relation=relation,intersection=intersection,perpendicular=relation=='perpendicular')
  a,u=line(v,r['line']);face=choice(r['face'],FACES);axis,boundary=FACES[face];plane=positive(r[['length','width','height'][axis]])*boundary
  if u[axis]==0:relation='contained'if a[axis]==plane else'parallel';intersection='all-points'if relation=='contained'else'none'
  else:relation='perpendicular'if all(u[i]==0 for i in range(3)if i!=axis)else'oblique-intersection';intersection='one-point'
  return dict(relation=relation,intersection=intersection,perpendicular=relation=='perpendicular')
 if s=='s912-tetrahedron-relations':
  positive(r['edgeLength']);flag(r,'regularModelConfirmed');order=r['vertexOrder']
  if type(order)is not list or len(order)!=4 or any(type(x)is not str or x not in 'ABCD'for x in order)or len(set(order))!=4:raise Bound('四頂點角色須完整且不重複')
  q=choice(r['query'],{'opposite-edges','adjacent-edges','face-median','altitude-base','edge-base','midline-base','base-edge-contained'})
  rel={'opposite-edges':'skew','adjacent-edges':'intersecting-nonright','face-median':'perpendicular','altitude-base':'perpendicular','edge-base':'oblique-intersection','midline-base':'parallel','base-edge-contained':'contained'}[q]
  return dict(relation=rel,intersection='none'if rel in ('skew','parallel')else'all-points'if rel=='contained'else'one-point',perpendicular=rel=='perpendicular')
 if s=='d93-uniform-single':
  flag(r,'equalLikelihoodConfirmed');flag(r,'completeSpaceConfirmed');rows=r['outcomes'];fav=r['favourable']
  if type(rows)is not list or not 1<=len(rows)<=52:raise Bound('首包需1到52個完整基本結果')
  labels=[];weights=[]
  for row in rows:
   if type(row)is not dict:raise Bound('基本結果須有名稱與題給選取權重')
   for k in ('label','weight'):need(row,k)
   if set(row)!={'label','weight'}:raise Bound('基本結果欄位不符')
   name=row['label']
   if type(name)is not str or not 1<=len(name)<=12:raise Bound('結果名稱不符')
   labels.append(name);weights.append(nat(row['weight'],1,9))
  if len(set(labels))!=len(labels):raise Bound('基本結果不可重複計數')
  if len(set(weights))!=1:raise Ask('原記錄的選取權重不同，與等可能前提不一致，不能硬用顆數比')
  if type(fav)is not list or len(fav)>52 or any(type(x)is not str for x in fav)or len(set(fav))!=len(fav)or not set(fav)<=set(labels):raise Bound('有利結果須是基本結果的無重複子集')
  return dict(total=len(labels),favourable=len(fav),probability=text(Fraction(len(fav),len(labels))),basis='classical-equiprobable',nextEventStatus='certain'if len(fav)==len(labels)else'impossible'if not fav else'random')
 if s=='d93-ordered-balls':
  a,b=nat(r['red'],0,8),nat(r['blue'],0,8);n=a+b
  if not 1<=n<=12:raise Ask('袋內總球數須先核對；首包限1到12顆')
  if type(r['replacement'])is not bool:raise Bound('放回與否須明確布林')
  if not r['replacement']and n<2:raise Ask('不放回抽兩次至少需要兩顆球')
  flag(r,'uniformIndividualDrawConfirmed');event=choice(r['event'],{'RR','RB','BR','BB','same','different','at-least-one-red'})
  rr=a*a if r['replacement']else a*(a-1);bb=b*b if r['replacement']else b*(b-1);rb=a*b;den=n*n if r['replacement']else n*(n-1)
  good={'RR':rr,'RB':rb,'BR':rb,'BB':bb,'same':rr+bb,'different':2*rb,'at-least-one-red':den-bb}[event]
  return dict(orderedTotal=den,favourable=good,probability=text(Fraction(good,den)),basis='classical-equiprobable',nextEventStatus='certain'if good==den else'impossible'if good==0 else'random')
 if s=='d93-asymmetric-frequency':
  choice(r['objectKind'],{'tack','cone','jiaobei'});flag(r,'sameMechanismConfirmed');rows=r['rounds']
  if type(rows)is not list or not 1<=len(rows)<=4:raise Bound('首包需1到4輪已確認的計數')
  total=success=0
  for row in rows:
   if type(row)is not dict:raise Bound('每輪須為物件')
   for k in ('trials','successes'):need(row,k)
   if set(row)!={'trials','successes'}:raise Bound('每輪欄位不符')
   n,k=nat(row['trials'],0,1000),nat(row['successes'],0,1000)
   if k>n:raise Ask('成功次數超過試驗次數，先核對原記錄')
   total+=n;success+=k
  return dict(trials=total,successes=success,frequency=text(Fraction(success,total))if total else None,status='observed-estimate'if total else'undefined-no-trials',trueProbabilityDetermined=False,guaranteedNextResult=False)
 raise Bound('未知子型')
def same(v,e):
 if type(e)is dict:return type(v)is dict and set(v)==set(e)and all(same(v[k],x)for k,x in e.items())
 if type(e)is list:return type(v)is list and len(v)==len(e)and all(same(x,y)for x,y in zip(v,e))
 if type(e)is bool:return type(v)is bool and v==e
 if e is None:return v is None
 if type(e)is int:return exact(v)==e
 if type(e)is str and re.fullmatch(r'-?[0-9]+(?:/[0-9]+)?',e):return exact(v)==exact(e)
 return type(v)is str and v==e
def evaluate(s,r):
 try:
  if type(s)is not str or s not in TYPES:raise Bound('未知子型')
  if type(r)is not dict:raise Bound('原題須結構化')
  shape(r)
  for k in ['task','confirmed',*REQ[s]]:need(r,k)
  bounded_missing(s,r)
  flag(r,'confirmed');choice(r['task'],{'solve','check_proposal'})
  if set(r)-set(REQ[s])-{'task','confirmed','proposal'}:raise Bound('有未定義欄位')
  if r['task']=='check_proposal':need(r,'proposal')
  ans=compute(s,r)
  if r['task']=='solve':return dict(decision='pass',answer=ans,reason='只核明列原量、已確認配置與有依據的推理，不驗實物或學生掌握')
  try:
   ok=valid_geo(r['proposal'],ans)if s=='s911-geometric-proof'else valid_algebra(r['proposal'],ans,r['p'],r['q'])if s=='s911-algebra-proof'else same(r['proposal'],ans)
  except (Bound,ValueError,ZeroDivisionError,TypeError,KeyError,RecursionError,OverflowError):ok=False
  return dict(decision='pass'if ok else'reject',answer=dict(accepted=ok,correctSolution=ans),reason='核完整原域與每步理由；容許合法不同證明／等值數值，不接受假設待證或循環論證')
 except Ask as e:return dict(decision='confirm',answer=None,reason=str(e))
 except (Bound,ValueError,ZeroDivisionError,TypeError,KeyError,RecursionError,OverflowError)as e:return dict(decision='block',answer=None,reason=str(e))
def validate_pack(d):
 errors=[]
 for c in d['cases']:
  z=evaluate(c['subtypeId'],copy.deepcopy(c['input']))
  if(z['decision'],z['answer'])!=(c['expectedDecision'],c['expectedAnswer']):errors.append(c['id'])
 return errors
def verify_package(d):return validate_pack(d)
if __name__=='__main__':
 try:
  if len(sys.argv)>1 and sys.argv[1]=='evaluate':
   if len(sys.argv)<4:raise ValueError('缺少指定子型與原題')
   if len(sys.argv[3].encode('utf-8'))>65536:raise ValueError('輸入過長')
   result=evaluate(sys.argv[2],json.loads(sys.argv[3]))
  elif len(sys.argv)>1:
   d=json.loads(pathlib.Path(sys.argv[1]).read_text());err=validate_pack(d);result=dict(ok=not err,cases=len(d['cases']),errors=err)
  else:
   blob=sys.stdin.buffer.read(65537)
   if len(blob)>65536:raise ValueError('輸入過長')
   d=json.loads(blob.decode('utf-8'));result=evaluate(d.get('subtypeId'),d.get('input'))if type(d)is dict else dict(decision='block',answer=None,reason='頂層須為物件')
 except (ValueError,RecursionError,OverflowError):result=dict(decision='block',answer=None,reason='JSON不合法或超出64KiB限制')
 print(json.dumps(result,ensure_ascii=False))
