#!/usr/bin/env python3
"""Finite structured methods, not a raw-expression or handwriting parser."""
import json,sys,re,pathlib,copy
from fractions import Fraction
TYPES={'r61-safe-mul-div','r61-shared-factor','r62-cost-table','r62-fixed-total-table','r63-part-whole-symbol','r63-groups-loose-symbol'}
REQ={'r61-safe-mul-div':['a','b','c'],'r61-shared-factor':['a','b','c'],'r62-cost-table':['unitPrice','fixedFee','knownRows','requestedCount','ruleConfirmed'],'r62-fixed-total-table':['total','knownRows','requestedFirst','ruleConfirmed'],'r63-part-whole-symbol':['unknownRole','quantities'],'r63-groups-loose-symbol':['unknownRole','quantities']}
ROLES={'r63-part-whole-symbol':{'partA':'甲部分顆數','partB':'乙部分顆數','total':'全部顆數'},'r63-groups-loose-symbol':{'perGroup':'每盒顆數','groups':'盒數','loose':'散放顆數','total':'全部顆數'}}
class Ask(Exception):pass
class Bound(Exception):pass
def need(r,k):
 if k not in r or r[k]is None:raise Ask('請補清原題缺少的數量、指定規則或符號所代表的量')
 return r[k]
def nat(v,lo=0,hi=9999):
 if type(v)is not int or not lo<=v<=hi:raise Bound('原量須為本型範圍內非負整數')
 return v
def enum(v,choices):
 if type(v)is not str or v not in choices:raise Bound('不在本型明列的量名或任務')
 return v
def shape(v,depth=0):
 if depth>8:raise Bound('結構過深')
 if type(v)is dict:
  if len(v)>24 or any(type(k)is not str or len(k)>80 for k in v):raise Bound('欄位結構不符')
  for x in v.values():shape(x,depth+1)
 elif type(v)is list:
  if len(v)>24:raise Bound('清單過長')
  for x in v:shape(x,depth+1)
 elif type(v)is str and len(v)>128:raise Bound('文字過長')
 elif type(v)is int and abs(v)>10**12:raise Bound('整數過大')
def exact(v,raw=False):
 if type(v)is int:
  if abs(v)>10**12:raise Bound('數量過大')
  f=Fraction(v)
 elif type(v)is str and 1<=len(v)<=40 and re.fullmatch(r'-?[0-9]{1,16}(?:/[0-9]{1,16}|\.[0-9]{1,12})?',v,re.ASCII):
  if '/'in v and not any(x!='0'for x in v.split('/')[1]):raise Bound('分母不能是0')
  try:f=Fraction(v)
  except(ValueError,ZeroDivisionError):raise Bound('數值不合法')
 else:raise Bound('須是有限精確整數、分數或小數；不讀指數或算式')
 if abs(f)>10**12:raise Bound('數量過大')
 if raw:
  if not 0<=f<=9999:raise Bound('本型原量須在0到9999')
  if type(v)is str and '/'in v and int(v.split('/')[1])>100:raise Bound('原題分母限100以內')
  if type(v)is str and'.'in v and len(v.split('.')[1])>2:raise Bound('原題小數至多兩位')
 return f
def text(f):return str(f.numerator)if f.denominator==1 else str(f.numerator)+'/'+str(f.denominator)
def compute(s,r):
 if s.startswith('r61-'):
  a,b,c=[exact(r[k],True)for k in'abc']
  if s=='r61-safe-mul-div':
   if c==0:return dict(status='undefined',originalFirst=None,regroupedFirst=None,value=None,regroupedValue=None,sameValue=False)
   left=a*b;right=a/c;v=left/c;other=right*b
   if max(left,right,v,other)>10**8:raise Bound('計算量超過本包範圍')
   return dict(status='defined',originalFirst=text(left),regroupedFirst=text(right),value=text(v),regroupedValue=text(other),sameValue=v==other)
  ab=a*b;ac=a*c;v=ab+ac;other=a*(b+c)
  if max(ab,ac,v,other)>10**8:raise Bound('計算量超過本包範圍')
  return dict(leftPart=text(ab),rightPart=text(ac),sumValue=text(v),factoredValue=text(other),sameValue=v==other)
 if s.startswith('r62-'):
  if type(r['ruleConfirmed'])is not bool:raise Bound('規則確認須是布林')
  if not r['ruleConfirmed']:raise Ask('有限幾筆不能決定唯一規則，先確認題目指定的數量關係')
  rows=r['knownRows']
  if type(rows)is not list or not 1<=len(rows)<=4:raise Bound('本型需1到4筆已知資料')
  if s=='r62-cost-table':
   price=nat(r['unitPrice'],1,50);fee=nat(r['fixedFee'],0,100);n=nat(r['requestedCount'],0,100)
   for row in rows:
    if type(row)is not dict:raise Bound('資料列須是物件')
    for k in ['count','amount']:need(row,k)
    if set(row)!={'count','amount'}:raise Bound('資料列欄位不符')
    q=nat(row['count'],0,100);v=nat(row['amount'],0,5100)
    if v!=fee+price*q:raise Ask('已知各列與題目指定單價及固定費不一致，先核對原表')
   return dict(requestedCount=n,amount=fee+price*n,isProportional=fee==0)
  total=nat(r['total'],0,100);x=nat(r['requestedFirst'],0,100)
  for row in rows:
   if type(row)is not dict:raise Bound('資料列須是物件')
   for k in ['first','second']:need(row,k)
   if set(row)!={'first','second'}:raise Bound('資料列欄位不符')
   a=nat(row['first'],0,100);b=nat(row['second'],0,100)
   if a+b!=total:raise Ask('已知各列與固定總量不一致，先核對原表')
  if x>total:return dict(status='not-natural',requestedFirst=x,second=None,isInverseProportion=False)
  return dict(status='defined',requestedFirst=x,second=total-x,isInverseProportion=False)
 if s.startswith('r63-'):
  roles=ROLES[s];u=enum(r['unknownRole'],roles);q=r['quantities']
  if type(q)is not dict:raise Bound('各量需按量名完整記錄')
  for k in roles:
   if k not in q:raise Ask('請保留各量的位置，未知的指定量用空格表示')
   if k!=u:need(q,k)
  if set(q)!=set(roles):raise Bound('量名欄位不符')
  if q[u]is not None:raise Bound('本型指定的未知量須留空，不以算出數字取代關係表示')
  vals={k:nat(v,0,999)for k,v in q.items()if k!=u}
  if s=='r63-part-whole-symbol':
   if u!='total'and vals['total']<vals['partB'if u=='partA'else'partA']:raise Ask('已知部分超過全部，先核對題面')
   terms={k:'□'if k==u else vals[k]for k in roles}
   return dict(unknownMeaning=roles[u],partA=terms['partA'],partB=terms['partB'],total=terms['total'],model='甲部分＋乙部分＝全部')
  if u=='perGroup'and(vals['total']<vals['loose']or vals['groups']==0 and vals['total']!=vals['loose']):raise Ask('已知盒數或散量與全部矛盾，先確認')
  if u=='groups'and(vals['total']<vals['loose']or vals['perGroup']==0 and vals['total']!=vals['loose']):raise Ask('已知每盒或散量與全部矛盾，先確認')
  if u=='loose'and vals['perGroup']*vals['groups']>vals['total']:raise Ask('盒內總量超過全部，先核對題面')
  if u in {'groups','perGroup'}:
   factor=vals['perGroup'if u=='groups'else'groups'];remaining=vals['total']-vals['loose']
   if factor and remaining%factor:raise Ask('剩下顆數無法分成題目指定的整盒/整顆，先核對原條件')
  terms={k:'□'if k==u else vals[k]for k in roles}
  return dict(unknownMeaning=roles[u],perGroup=terms['perGroup'],groups=terms['groups'],loose=terms['loose'],total=terms['total'],model='每盒顆數×盒數＋散放顆數＝全部顆數')
 raise Bound('未知子型')
def normalize(v,e):
 if type(e)is dict:
  if type(v)is not dict or set(v)!=set(e):raise Bound('關係/提案欄位須完整，不能只交最後數字')
  return {k:normalize(v[k],x)for k,x in e.items()}
 if type(e)is bool:
  if type(v)is not bool:raise Bound('布林不可用0或1代替')
  return v
 if e is None:
  if v is not None:raise Bound('不可硬填不適用量')
  return None
 if type(e)is int:return exact(v)
 if type(e)is str and re.fullmatch(r'[0-9]+(?:/[0-9]+)?',e):return exact(v)
 if type(v)is not str:raise Bound('量名或符號須是文字')
 return v
def nested_missing(s,r):
 # shape() already enforces resource limits; inspect only small schema-defined containers.
 if s.startswith('r62-'):
  rows=r.get('knownRows')
  if type(rows)is list and 1<=len(rows)<=4:
   fields=('count','amount')if s=='r62-cost-table'else('first','second')
   for row in rows:
    if type(row)is dict:
     for k in fields:need(row,k)
 elif s.startswith('r63-'):
  u=r.get('unknownRole');q=r.get('quantities')
  if type(u)is str and u in ROLES[s] and type(q)is dict:
   for k in ROLES[s]:
    if k not in q:raise Ask('請保留各量的位置，未知的指定量用空格表示')
    if k!=u:need(q,k)
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({k:v for k,v in r.items()if k!='proposal'})
  for k in ['confirmed','task',*REQ[s]]:need(r,k)
  nested_missing(s,r)
  if type(r['confirmed'])is not bool:raise Bound('確認值型別不符')
  if not r['confirmed']:raise Ask('先確認原題條件')
  enum(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=normalize(r['proposal'],ans)==normalize(ans,ans)
  except Bound as e:return dict(decision='reject',answer=dict(accepted=False,correctSolution=ans),reason=str(e))
  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 as e:return dict(decision='block',answer=None,reason=str(e))
def verify_package(d):
 errors=[];counts={}
 for c in d['cases']:
  z=evaluate(c['subtypeId'],copy.deepcopy(c['input']));counts[z['decision']]=counts.get(z['decision'],0)+1
  if(z['decision'],z['answer'])!=(c['expectedDecision'],c['expectedAnswer']):errors.append(dict(id=c['id'],actual=z))
 return errors,counts
def validate_pack(d):return verify_package(d)[0]
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(0)
 p=pathlib.Path(sys.argv[1])if len(sys.argv)>1 else pathlib.Path(__file__).with_name(pathlib.Path(__file__).stem.removeprefix('check-')+'.json');errors,counts=verify_package(json.loads(p.read_text()));print(json.dumps(dict(ok=not errors,cases=sum(counts.values()),decisions=counts,errors=errors),ensure_ascii=False));sys.exit(bool(errors))
