#!/usr/bin/env python3
"""Offline finite textual methods; exact rational arithmetic; no eval/OCR/network."""
import copy,json,re,sys
from fractions import Fraction as F
SLUG='grade8-quadratic-meaning'
GROUPS={'grade8-quadratic-meaning':['a86-equation-classify','a86-candidate-root','a86-rectangle-model'],'grade8-affine-function-meaning':['f81-finite-correspondence','f81-affine-rule','f81-confirmed-rule-table'],'grade8-affine-function-graphs':['f82-affine-graph-domain','f82-two-points-affine']}
REQUIRED={'a86-equation-classify':['left','right','domain'],'a86-candidate-root':['left','right','domain','candidate'],'a86-rectangle-model':['widthSymbol','lengthExtra','area','lengthUnit','domainConfirmed'],'f81-finite-correspondence':['domainValues','pairs','allPairsConfirmed'],'f81-affine-rule':['a','b','domain','x','ruleConfirmed'],'f81-confirmed-rule-table':['a','b','domain','rows','ruleConfirmed','allRowsConfirmed'],'f82-affine-graph-domain':['a','b','domain','ruleConfirmed'],'f82-two-points-affine':['points','domain','affineConfirmed']}
class Guard(Exception):pass
class Missing(Exception):pass
def bounded(x,depth=0,counter=None):
 if counter is None:counter=[0]
 counter[0]+=1
 if counter[0]>3000 or depth>12:raise Guard('資料超出安全大小')
 if isinstance(x,str) and len(x)>4096:raise Guard('字串過長')
 if isinstance(x,(dict,list)):
  if len(x)>160:raise Guard('集合過大')
  for k,v in (x.items() if isinstance(x,dict) else enumerate(x)):
   if isinstance(x,dict) and (not isinstance(k,str) or len(k)>80):raise Guard('鍵型別')
   bounded(v,depth+1,counter)
def need(x):
 if x is None:raise Missing('缺少必要原條件')
def num(x,answer=False):
 need(x)
 if type(x) is int:
  if x.bit_length()>(1800 if answer else 80):raise Guard('整數過大')
  s=str(x)
 elif type(x) is str:s=x
 else:raise Guard('數值只收整數、有限小數、整數分數字串，不收bool或float')
 limit=512 if answer else 64
 if len(s)>limit or not re.fullmatch(r'[+-]?\d+(?:\.\d+|/[+-]?\d+)?',s):raise Guard('非有限十進位/分數字面')
 # Bounded grammar and lengths are checked BEFORE Fraction. No scientific notation.
 try:q=F(s)
 except (ValueError,ZeroDivisionError):raise Guard('分母不可0')
 if not answer and (abs(q)>10**6 or q.denominator>10000):raise Guard('超出原量有限域')
 return q
def s(q):return str(q)
def keys(x,allowed):
 if not isinstance(x,dict) or set(x)-set(allowed):raise Guard('欄位不符')
def exactbool(x):
 if type(x) is not bool:raise Guard('須明確布林')
 return x
def preflight(sid,d):
 # Only original required condition fields; unknown None must not trigger confirmation.
 for k in REQUIRED[sid]:need(d.get(k))
 if sid.startswith('a86-') and sid!='a86-rectangle-model':
  for k in ('left','right'):
   if isinstance(d[k],list):
    for v in d[k]:need(v)
 if sid in ('f81-affine-rule','f81-confirmed-rule-table','f82-affine-graph-domain','f82-two-points-affine','a86-equation-classify','a86-candidate-root'):
  dom=d['domain']
  if isinstance(dom,dict):
   need(dom.get('kind'))
   if dom.get('kind')=='interval':
    for k in ('lo','hi','loClosed','hiClosed'):need(dom.get(k))
   if dom.get('kind')=='finite':
    need(dom.get('values'))
    if isinstance(dom.get('values'),list):
     for v in dom['values']:need(v)
 if sid=='f81-finite-correspondence':
  if isinstance(d['domainValues'],list):
   for v in d['domainValues']:need(v)
  if isinstance(d['pairs'],list):
   for row in d['pairs']:
    if isinstance(row,dict):
     need(row.get('x'));need(row.get('y'))
 if sid in ('f81-confirmed-rule-table','f82-two-points-affine'):
  for row in d['rows' if sid.startswith('f81') else 'points'] if isinstance(d['rows' if sid.startswith('f81') else 'points'],list) else []:
   if isinstance(row,dict):need(row.get('x'));need(row.get('y'))
def domain(d):
 keys(d,['kind','lo','hi','loClosed','hiClosed','values'])
 k=d['kind']
 if k in ('real','nonnegative','positive','integers','positive-integers'):
  keys(d,['kind']);return {'kind':k}
 if k=='finite':
  keys(d,['kind','values'])
  if not isinstance(d['values'],list) or len(d['values'])>30:raise Guard('有限原域至多30個值')
  vv=[num(v) for v in d['values']]
  if len(vv)!=len(set(vv)):raise Guard('原域集合不可重複')
  return {'kind':k,'values':vv}
 if k=='interval':
  keys(d,['kind','lo','hi','loClosed','hiClosed'])
  lo,hi=num(d['lo']),num(d['hi']);lc,hc=exactbool(d['loClosed']),exactbool(d['hiClosed'])
  if lo>hi:raise Guard('上下界倒置不是本方法原域')
  return {'kind':k,'lo':lo,'hi':hi,'loClosed':lc,'hiClosed':hc}
 raise Guard('原域種類不支援')
def inside(x,d):
 k=d['kind']
 if k=='real':return True
 if k=='positive':return x>0
 if k=='nonnegative':return x>=0
 if k=='integers':return x.denominator==1
 if k=='positive-integers':return x.denominator==1 and x>0
 if k=='finite':return x in d['values']
 return (x>d['lo'] or (d['loClosed'] and x==d['lo'])) and (x<d['hi'] or (d['hiClosed'] and x==d['hi']))
def empty(d):return (d['kind']=='finite' and not d['values']) or (d['kind']=='interval' and d['lo']==d['hi'] and not(d['loClosed'] and d['hiClosed']))
def singleton(d):
 if d['kind']=='finite' and len(d['values'])==1:return d['values'][0]
 if d['kind']=='interval' and d['lo']==d['hi'] and d['loClosed'] and d['hiClosed']:return d['lo']
 return None
def poly(v):
 if not isinstance(v,list) or not 1<=len(v)<=4:raise Guard('一元多項式最高三次，係數依常數到三次')
 return [num(a) for a in v]+[F(0)]*(4-len(v))
def pv(p,x):return sum(c*x**i for i,c in enumerate(p))
def classification(p):
 nz=[i for i,c in enumerate(p) if c]
 degree=max(nz) if nz else None
 kind='identity' if degree is None else ('contradiction' if degree==0 else ('linear' if degree==1 else ('quadratic' if degree==2 else 'other-degree')))
 return {'classification':kind,'degree':degree,'coefficients':[s(c) for c in p]}
def pointrows(rows,maxn=30):
 if not isinstance(rows,list) or len(rows)>maxn:raise Guard('表列太多或型別錯')
 ret=[]
 for row in rows:
  keys(row,['x','y']);ret.append((num(row['x']),num(row['y'])))
 return ret
def graph(a,b,d):
 k=d['kind'];one=singleton(d)
 if empty(d):shape='empty'
 elif one is not None:shape='single-point'
 elif k=='finite':shape='discrete-points'
 elif k in ('integers','positive-integers'):shape='discrete-integer-domain'
 elif k=='interval':shape='segment-with-stated-endpoints'
 elif k in ('nonnegative','positive'):shape='ray-with-stated-endpoint'
 else:shape='horizontal-line' if a==0 else 'line'
 trend='constant' if a==0 else ('increasing' if a>0 else 'decreasing')
 if empty(d) or one is not None:trend='not-comparable'
 if a:
  r=-b/a;xint=[s(r)] if inside(r,d) else []
 else:xint='all-domain' if b==0 and not empty(d) else []
 return {'a':s(a),'b':s(b),'shape':shape,'trend':trend,'yIntercept':s(b) if inside(F(0),d) else None,'xIntercepts':xint,'domain':serialize_domain(d)}
def serialize_domain(d):return {k:([s(v) for v in v0] if isinstance(v0,list) else s(v0) if isinstance(v0,F) else v0) for k,v0 in d.items()}
def solve(sid,d):
 if sid in ('a86-equation-classify','a86-candidate-root'):
  l,r=poly(d['left']),poly(d['right']);dom=domain(d['domain'])
  p=[a-b for a,b in zip(l,r)]
  if sid.endswith('classify'):return classification(p)
  x=num(d['candidate']);lv,rv=pv(l,x),pv(r,x);ok=inside(x,dom)
  return {'candidate':s(x),'leftValue':s(lv),'rightValue':s(rv),'inDomain':ok,'satisfiesEquation':lv==rv,'validRoot':ok and lv==rv}
 if sid=='a86-rectangle-model':
  if d['widthSymbol']!='x':raise Guard('本有限文字模板以x表示寬')
  if not exactbool(d['domainConfirmed']):raise Missing('需確認x為正寬且兩邊長單位相同')
  extra,area=num(d['lengthExtra']),num(d['area'])
  if extra<0 or area<=0:raise Guard('本型長x+d且d>=0、面積正')
  if d['lengthUnit'] not in ('公分','公尺'):raise Guard('長度單位須公分或公尺')
  return {'coefficients':[s(-area),s(extra),'1','0'],'domain':'x>0','width':'x','lengthExtra':s(extra),'area':s(area),'lengthUnit':d['lengthUnit'],'areaUnit':'平方'+d['lengthUnit']}
 if sid=='f81-finite-correspondence':
  if not exactbool(d['allPairsConfirmed']):raise Missing('需確認全部對應是否列齊')
  if not isinstance(d['domainValues'],list) or len(d['domainValues'])>30:raise Guard('原域最多30值')
  xx=[num(x) for x in d['domainValues']]
  if len(set(xx))!=len(xx):raise Guard('原域集合不可重複')
  rows=pointrows(d['pairs']);outs={x:set() for x in xx}
  for x,y in rows:
   if x not in outs:raise Guard('對應含原域以外的x')
   outs[x].add(y)
  missing=[s(x) for x in xx if not outs[x]];multiple=[s(x) for x in xx if len(outs[x])>1]
  return {'isFunction':not missing and not multiple,'missingInputs':missing,'multipleOutputInputs':multiple,'image':[s(v) for v in sorted(set().union(*outs.values()) if outs else set())]}
 if sid=='f81-affine-rule' or sid=='f81-confirmed-rule-table' or sid=='f82-affine-graph-domain':
  if not exactbool(d['ruleConfirmed']):raise Missing('需確認完整規則，不能由有限表猜整個函數')
  a,b=num(d['a']),num(d['b']);dom=domain(d['domain'])
  if sid=='f82-affine-graph-domain':return graph(a,b,dom)
  cls='constant' if a==0 else 'first-degree'
  if sid=='f81-affine-rule':
   x=num(d['x']);ok=inside(x,dom)
   return {'functionType':cls,'inputInDomain':ok,'value':s(a*x+b) if ok else None}
  if not exactbool(d['allRowsConfirmed']):raise Missing('需確認表格原數')
  rows=pointrows(d['rows'])
  checks=[{'x':s(x),'givenY':s(y),'inDomain':inside(x,dom),'ruleY':s(a*x+b),'matches':inside(x,dom) and y==a*x+b} for x,y in rows]
  return {'functionType':cls,'allRowsMatch':all(r['matches'] for r in checks),'rows':checks}
 if sid=='f82-two-points-affine':
  if not exactbool(d['affineConfirmed']):raise Missing('兩點不能保證原關係為一次或常數函數')
  rows=pointrows(d['points'],2)
  if len(rows)!=2:raise Guard('須恰好兩個已確認點')
  dom=domain(d['domain'])
  if any(not inside(x,dom) for x,y in rows):raise Guard('給定點不在原域')
  (x1,y1),(x2,y2)=rows
  if x1==x2:
   if y1==y2:raise Missing('同一點重複不能唯一決定一次或常數規則')
   return {'relation':'not-a-function','reason':'same-input-different-outputs','a':None,'b':None}
  a=(y2-y1)/(x2-x1);b=y1-a*x1
  return {'relation':'affine-function','graph':graph(a,b,dom),'checkValues':[s(a*x1+b),s(a*x2+b)]}
 raise Guard('未知子型')
def normalized(x):
 if isinstance(x,dict):return {k:normalized(v) for k,v in x.items()}
 if isinstance(x,list):return [normalized(v) for v in x]
 if type(x) is bool or x is None:return x
 if type(x) in (int,str):
  if type(x) is int or re.fullmatch(r'[+-]?\d+(?:\.\d+|/[+-]?\d+)?',x or ''):return ('Q',num(x,True))
  return x
 raise Guard('答案不收float或非支援型別')
def equal(sid,p,a):
 if not isinstance(p,dict):raise Guard('答案必須具名物件')
 if sid=='a86-rectangle-model' and p.get('equationForm')=='product':
  keys(p,['equationForm','factor1','factor2','rhs','domain','width','lengthExtra','area','lengthUnit','areaUnit'])
  if not all(isinstance(p.get(k),list) and len(p[k])==2 for k in ('factor1','factor2')):raise Guard('乘積式須兩個一次因式')
  f,g=([num(v,True) for v in p[k]] for k in ('factor1','factor2'))
  rhs=num(p['rhs'],True)
  p={k:v for k,v in p.items() if k not in ('equationForm','factor1','factor2','rhs')}
  p['coefficients']=[s(f[0]*g[0]-rhs),s(f[0]*g[1]+f[1]*g[0]),s(f[1]*g[1]),'0']
 # Required explicit type semantics; bool never equals a numeric value.
 def check_types(ref,v,path=()):
  if path and path[-1]=='xIntercepts':
   if v=='all-domain':return
   if not isinstance(v,list) or len(v)>30:raise Guard('x軸交點答案型別')
   for x in v:
    if type(x)is not str:raise Guard('x軸交點須數值字串')
    num(x,True)
   return
  if isinstance(ref,dict):
   if not isinstance(v,dict) or set(v)!=set(ref):raise Guard('答案鍵不符')
   for k in ref:check_types(ref[k],v[k],path+(k,))
  elif isinstance(ref,list):
   if not isinstance(v,list):raise Guard('答案清單形狀不符')
   for i,(x,y) in enumerate(zip(ref,v)):check_types(x,y,path+(i,))
  elif type(ref) is bool:
   if type(v) is not bool:raise Guard('答案真假須bool')
  elif ref is None:
   if v is not None and not (type(v) is int or (type(v) is str and len(v)<=512)):raise Guard('可空答案欄位型別')
  elif type(ref) is int:
   if v is not None and type(v) is not int:raise Guard('次數須整數非bool')
  elif type(ref) is str:
   if v is not None and not isinstance(v,str):raise Guard('答案字串型別')
 check_types(a,p)
 if sid in ('a86-equation-classify','a86-rectangle-model'):
  if len(p['coefficients'])!=4:raise Guard('係數答案需4欄')
  pp=[num(x,True) for x in p['coefficients']];aa=[num(x,True) for x in a['coefficients']]
  nz=next((i for i,x in enumerate(aa) if x),None)
  coeffok=all(x==0 for x in pp) if nz is None else pp[nz]!=0 and all(pp[i]*aa[nz]==aa[i]*pp[nz] for i in range(4))
  p=copy.deepcopy(p);a=copy.deepcopy(a);p.pop('coefficients');a.pop('coefficients')
  return coeffok and normalized(p)==normalized(a)
 # Function images/missing/multiple are sets, same values in another order acceptable.
 if sid=='f81-finite-correspondence':
  for key in ('missingInputs','multipleOutputInputs','image'):
   vals=[num(x,True) for x in p[key]]
   if len(vals)!=len(set(vals)):return False
   if set(vals)!={num(x,True) for x in a[key]}:return False
  return p['isFunction']==a['isFunction']
 return normalized(p)==normalized(a)
def evaluate(subtype_id,input_data):
 try:
  bounded(input_data)
  if subtype_id not in GROUPS[SLUG]:raise Guard('子型不屬於本包')
  if not isinstance(input_data,dict):raise Guard('原資料須物件')
  d=input_data
  preflight(subtype_id,d)
  need(d.get('task'))
  if d['task']=='check_proposal':need(d.get('proposal'))
  keys(d,REQUIRED[subtype_id]+['task','proposal'])
  if d['task'] not in ('solve','check_proposal'):raise Guard('task錯誤')
  a=solve(subtype_id,d)
  if d['task']=='solve':
   if 'proposal' in d:raise Guard('solve不可混入提案')
   return {'decision':'pass','answer':a}
  return {'decision':'pass' if equal(subtype_id,d['proposal'],a) else 'reject','answer':a}
 except Missing as e:return {'decision':'confirm','answer':None,'reason':str(e)}
 except (Guard,KeyError,TypeError,ValueError,ZeroDivisionError,OverflowError) as e:return {'decision':'block','answer':None,'reason':str(e)}
def main():
 from pathlib import Path
 p=Path(__file__).with_name(SLUG+'.json')
 if len(sys.argv)>1 and sys.argv[1] in ('--evaluate','evaluate'):
  try:
   raw=sys.stdin.read(65537)
   if len(raw)>65536:raise ValueError('request too large')
   data=json.loads(raw)
   if type(data)is not dict or set(data)!={'subtypeId','input'} or type(data['subtypeId'])is not str:raise ValueError('request object requires subtypeId/input')
   result=evaluate(data['subtypeId'],data['input'])
  except (ValueError,TypeError,RecursionError,OverflowError,UnicodeError):
   result={'decision':'block','answer':None,'reason':'請求JSON格式、必要欄位、大小或巢狀深度超出此有限文字方法'}
  print(json.dumps(result,ensure_ascii=False));return
 j=json.loads(p.read_text());fail=[]
 for c in j['cases']:
  r=evaluate(c['subtypeId'],c['input'])
  if r['decision']!=c['expectedDecision'] or r['answer']!=c['expectedAnswer']:fail.append({'id':c['id'],'actual':r})
 print(json.dumps({'slug':SLUG,'cases':len(j['cases']),'failures':fail},ensure_ascii=False));sys.exit(bool(fail))
if __name__=='__main__':main()
