import pathlib,json,re,sys,collections,math,copy
from fractions import Fraction as F
CFG={'code': 'A-8-4', 'title': '國二一次因式與因式分解的意義', 'modes': ['linear-factor-test', 'factorization-role'], 'page': 43, 'lines': [3336, 3342]}
PACK='grade8-polynomial-factor-meaning'
SUBTYPES={'g8-poly-linear-factor-test': 'linear-factor-test', 'g8-poly-factorization-role': 'factorization-role'}
REQ={'binomial-square':['p','q'],'difference-squares':['p','q'],'binomial-product':['a','b','c','d'],'polynomial-definition':['terms'],'canonical-meaning':['terms'],'add-subtract':['left','right','operation'],'multiply-cubic':['left','right'],'quadratic-division':['dividend','divisor'],'linear-factor-test':['polynomial','candidate'],'factorization-role':['polynomial','presentation'],'common-factor':['polynomial'],'formula-factor':['polynomial'],'cross-factor':['polynomial']}
def out(d,a=None,r=''):return dict(decision=d,answer=a,reason=r)
def integer(v,lo=-50,hi=50):
 if type(v)is not int or not lo<=v<=hi:raise ValueError('原係數需有限整數，不接布林/巨大整數')
 return v
def enum(v,seq):
 if type(v)is not str or v not in seq:raise ValueError('選項不在此有限結構契約')
 return v
def derived(v):
 if type(v)is int and abs(v)<=10**64:return F(v)
 if type(v)is str and len(v)<=132 and re.fullmatch(r'-?[0-9]{1,64}(?:/[0-9]{1,64}|\.[0-9]{1,64})?',v,re.ASCII):return F(v)
 raise ValueError('衍生答案限有界精確數，不接浮點布林')
def exponent(v):
 if type(v)is int and -3<=v<=6:return F(v)
 if type(v)is str and re.fullmatch(r'-?[0-9](?:/[12])?',v,re.ASCII):
  e=F(v)
  if -3<=e<=6:return e
 raise ValueError('指數限-3..6的整數/半整數觀察標記')
def trim(p):
 p=list(p)
 while len(p)>1 and p[-1]==0:p.pop()
 return p or[F(0)]
def degree(p):return None if trim(p)==[0]else len(trim(p))-1
def poly(v,limit=7,raw=True):
 if type(v)is not list or not 1<=len(v)<=limit:raise ValueError('需有限升冪係數陣列')
 return trim([F(integer(x))if raw else derived(x)for x in v])
def add(a,b,sign=1):return trim([(a[i]if i<len(a)else 0)+sign*(b[i]if i<len(b)else 0)for i in range(max(len(a),len(b)))])
def mul(a,b):
 z=[F(0)]*(len(a)+len(b)-1)
 for i,x in enumerate(a):
  for j,y in enumerate(b):z[i+j]+=x*y
 return trim(z)
def divide(a,b):
 if b==[0]:raise ZeroDivisionError('不能除零多項式')
 q=[F(0)]*max(1,len(a)-len(b)+1);r=trim(a);steps=[]
 while r!=[0]and len(r)>=len(b):
  k=len(r)-len(b);v=r[-1]/b[-1];term=[F(0)]*k+[v];q[k]+=v;sub=mul(term,b);new=add(r,sub,-1);steps.append((r[:],v,k,sub[:],new[:]));r=new
 return trim(q),r,steps
def pack(p):return [str(x)for x in trim(p)]
def analysis(p):
 p=trim(p);terms=[{'coefficient':str(v),'power':i}for i,v in enumerate(p)if v]
 return {'coefficients':pack(p),'termCount':len(terms),'degree':'零多項式次數不定'if degree(p)is None else degree(p),'leadingCoefficient':'無最高次項'if degree(p)is None else str(p[-1]),'constant':str(p[0]),'ascending':terms,'descending':list(reversed(terms))}
def normalize_terms(ts,classification=False):
 if type(ts)is not list or not 1<=len(ts)<=8:raise ValueError('需1..8個已確認項')
 terms=[]
 for t in ts:
  if type(t)is not dict or set(t)!= {'coefficient','exponent','variable'}:raise ValueError('單項式結構鍵不符')
  a=integer(t['coefficient']);e=exponent(t['exponent'])if classification else F(integer(t['exponent'],0,6));v=enum(t['variable'],('x','y')if classification else('x',));terms.append((F(a),e,v))
 return terms
def content(p):
 g=0
 for c in p:g=math.gcd(g,abs(int(c)))
 if not g:return F(0),0,[F(0)]
 m=next(i for i,c in enumerate(p)if c);return F(g),m,trim([c/g for c in p[m:]])
def divisors(n):return [i for i in range(1,abs(n)+1)if n%i==0]
def factor(p,formula=False):
 c,b,a=p;g=math.gcd(math.gcd(abs(int(a)),abs(int(b))),abs(int(c)));g=g if a>0 else-g;aa,bb,cc=(int(x/g)for x in(a,b,c))
 if formula:
  u=math.isqrt(aa);v=math.isqrt(abs(cc))
  if u*u==aa and cc>=0 and v*v==cc and bb in(2*u*v,-2*u*v):
   v=v if bb>=0 else-v;fs=[[F(v),F(u)],[F(v),F(u)]]
  elif bb==0 and cc<0 and u*u==aa and v*v==-cc:fs=[[-F(v),F(u)],[F(v),F(u)]]
  else:return {'status':'公式未匹配','scalar':'1','factors':[]}
 else:
  if cc==0:fs=[[F(0),F(1)],[F(bb),F(aa)]]
  else:
   fs=None
   for u in divisors(aa):
    for v0 in divisors(cc):
     for v in(v0,-v0):
      w=aa//u;z=cc//v
      if u*z+v*w==bb:fs=[[F(v),F(u)],[F(z),F(w)]];break
     if fs:break
    if fs:break
   if not fs:return {'status':'整係數一次因式未找到','scalar':'1','factors':[]}
 fs=sorted(fs,key=lambda p:(p[1],p[0]));return {'status':'已分成一次因式','scalar':str(g),'factors':[pack(x)for x in fs]}
def factor_product(p,raw=False):
 if type(p)is not dict or set(p)!= {'scalar','factors'}:raise ValueError('乘積結構需scalar與factors')
 scalar=F(integer(p['scalar']))if raw else derived(p['scalar']);fs=p['factors']
 if type(fs)is not list or len(fs)!=2:raise ValueError('此包兩個一次因式')
 factors=[poly(x,2,raw)for x in fs]
 if any(degree(x)!=1 for x in factors):raise ValueError('一次因式首項不可0')
 return [v*scalar for v in mul(*factors)]
def equal_answer(proposal,answer,mode):
 if type(proposal)is not dict or set(proposal)!=set(answer):return False
 try:
  if mode in('formula-factor','cross-factor')and answer['status']=='已分成一次因式':
   if proposal['status']!=answer['status']:return False
   actual=trim(factor_product({'scalar':proposal['scalar'],'factors':proposal['factors']}));wanted=trim(factor_product({'scalar':answer['scalar'],'factors':answer['factors']}));return actual==wanted
  numeric={'value','coefficient','leadingCoefficient','constant'}
  def eq(x,y,k=''):
   if k=='leadingCoefficient'and y=='無最高次項':return x==y and type(x)is str
   if k in numeric:return derived(x)==derived(y)
   if k in('coefficients','quotient','remainder','remaining'):
    if type(x)is not list:return False
    return poly(x,12,False)==poly(y,12,False)
   if k=='scalar':return derived(x)==derived(y)
   if type(y)is bool:return type(x)is bool and x==y
   if type(y)is int:return type(x)is int and x==y
   if type(y)is list:
    if type(x)is not list or len(x)!=len(y):return False
    return all(eq(a,b)for a,b in zip(x,y))
   if type(y)is dict:return type(x)is dict and set(x)==set(y)and all(eq(x[z],y[z],z)for z in y)
   return type(x)is type(y)and x==y
  return all(eq(proposal[k],v,k)for k,v in answer.items())
 except(ValueError,TypeError,KeyError,OverflowError,ZeroDivisionError):return False
def nested_missing(x,depth=0):
 if x is None:return True
 if depth>12:return False
 if type(x)is list:return len(x)<=20 and any(nested_missing(v,depth+1)for v in x)
 if type(x)is dict:return len(x)<=20 and any(nested_missing(v,depth+1)for v in x.values())
 return False
def evaluate(subtype_id,r):
 if type(subtype_id)is not str or subtype_id not in SUBTYPES or type(r)is not dict:return out('block',r='非本有限多項式模板')
 mode=SUBTYPES[subtype_id];fs=REQ[mode]
 if r.get('confirmed')is not True or any(k not in r or nested_missing(r[k])for k in fs):return out('confirm',r='原係數、次方或式子角色缺少，先核對，不eval原字串')
 if mode in('polynomial-definition','canonical-meaning')and type(r['terms'])is list and len(r['terms'])<=8:
  if any(type(t)is dict and any(k not in t or t[k]is None for k in('coefficient','exponent','variable'))for t in r['terms']):return out('confirm',r='原項的係數/次方/變數缺少，先核對')
 if mode=='factorization-role'and type(r['presentation'])is dict:
  p=r['presentation'];kind=p.get('kind')
  needed=('kind','coefficients')if kind=='expanded'else('kind','scalar','factors')if kind=='product'else('kind',)
  if any(k not in p or p[k]is None for k in needed):return out('confirm',r='待判的呈現角色或乘積條件缺少，先核對')
 if type(r.get('task'))is not str or r['task']not in('solve','check_proposal')or set(r)-set(fs)-{'confirmed','task','proposal'}:return out('block',r='結構或任務鍵不符')
 try:
  if mode in('binomial-square','difference-squares'):
   p,q=F(integer(r['p'])),F(integer(r['q']));v=mul([q,p],[q,p])if mode=='binomial-square'else mul([q,p],[-q,p]);ans={'coefficients':pack(v)}
  elif mode=='binomial-product':
   a,b,c,d=(F(integer(r[k]))for k in('a','b','c','d'));ans={'coefficients':pack(mul([b,a],[d,c]))}
  elif mode=='polynomial-definition':
   ts=normalize_terms(r['terms'],True)
   grouped={};restrictions={}
   for c,e,v in ts:
    key=('constant'if e==0 else v,e);grouped[key]=grouped.get(key,F(0))+c
    needs=restrictions.setdefault(v,set())
    if e.denominator==2:needs.add('nonnegative')
    if e<0:needs.add('nonzero')
   domains=[]
   for var,needs in sorted(restrictions.items()):
    if needs=={'nonnegative','nonzero'}:domains.append(var+'>0')
    elif 'nonnegative'in needs:domains.append(var+'≥0')
    elif 'nonzero'in needs:domains.append(var+'≠0')
   bad=any(c and(e.denominator!=1 or e<0)for(v,e),c in grouped.items())
   foreign=any(c and v=='y'for(v,e),c in grouped.items());ok=not bad and not foreign
   de=max((int(e)for(v,e),c in grouped.items()if c),default=None)if ok else None
   ans={'isPolynomial':ok,'degree':'零多項式次數不定'if ok and de is None else de if ok else'不適用','reasonCode':'合併後仍有負或非整指數'if bad else'合併後仍含第二變數'if foreign else'化簡後為一元多項式','domainRestrictions':domains}
  elif mode=='canonical-meaning':
   ts=normalize_terms(r['terms']);v=[F(0)]*7
   for a,e,_ in ts:v[int(e)]+=a
   ans=analysis(v)
  elif mode in('add-subtract','multiply-cubic'):
   a=poly(r['left'],4);b=poly(r['right'],4)
   if mode=='multiply-cubic':
    v=mul(a,b)
    if degree(v)is not None and degree(v)>3:return out('block',r='原題可乘，但乘積超三次，轉後續模板')
   else:op=enum(r['operation'],('add','subtract'));v=add(a,b,1 if op=='add'else-1)
   ans={'coefficients':pack(v)}
  elif mode=='quadratic-division':
   a=poly(r['dividend'],3);b=poly(r['divisor'],3)
   if b==[0]:return out('confirm',r='零多項式不能作除式，先確認原式')
   if degree(a)!=2:return out('block',r='原題可另處理，本型只驗二次被除式')
   if degree(b)not in(1,2):return out('block',r='本有限長除型只一次或二次除式，常數除式另配對')
   q,rem,_=divide(a,b);ans={'quotient':pack(q),'remainder':pack(rem)}
  elif mode in('linear-factor-test','factorization-role'):
   a=poly(r['polynomial'],3)
   if degree(a)!=2:return out('block',r='本型因式意義限定二次式的一次因式')
   if mode=='linear-factor-test':
    b=poly(r['candidate'],2)
    if degree(b)!=1:return out('block',r='候選需真正一次式，零/常數候選另確認定義')
    q,rem,_=divide(a,b);ans={'isFactor':rem==[0],'quotient':pack(q),'remainder':pack(rem)}
   else:
    p=r['presentation']
    if type(p)is not dict or type(p.get('kind'))is not str:raise ValueError('呈現結構缺角色')
    if p['kind']=='expanded':
     if set(p)!= {'kind','coefficients'}:raise ValueError('展開式結構不符')
     v=poly(p['coefficients'],3);equivalent=v==a;isfact=False
    elif p['kind']=='product':
     if set(p)!= {'kind','scalar','factors'}:raise ValueError('乘積結構不符')
     v=trim(factor_product({'scalar':p['scalar'],'factors':p['factors']},True));equivalent=v==a;isfact=equivalent
    else:raise ValueError('只辨識展開和與兩一次因式乘積')
    ans={'equivalent':equivalent,'isFactorization':isfact}
  elif mode=='common-factor':
   p=poly(r['polynomial'],3);g,power,remain=content(p);ans={'status':'零式不指定唯一公因式'if g==0 else'沒有非平凡公因式'if g==1 and power==0 else'已提出正最大公因式','coefficient':str(g),'power':power,'remaining':pack(remain)}
  elif mode in('formula-factor','cross-factor'):
   p=poly(r['polynomial'],3)
   if degree(p)!=2:return out('block',r='此型只整係數二次式，低次/零式另配對')
   ans=factor(p,mode=='formula-factor')
  else:return out('block',r='非本有限模板')
 except(ValueError,TypeError,KeyError,OverflowError,ZeroDivisionError):return out('block',r='原係數/次方/項數或結構超出契約，不作任意字串運算')
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',ans,'請提供待核對想法')
  if not equal_answer(r['proposal'],ans,mode):return out('reject',ans,'不改原式，保留係數/商餘/因式角色的正解')
 return out('pass',ans,'結構化已確認係數運算；非拍照/OCR驗證')
def verify_package(p):
 errs=[];counts=collections.Counter()
 for sid in SUBTYPES:
  if collections.Counter(c['kind']for c in p['cases']if c['subtypeId']==sid)!=dict(normal=8,negative=6,boundary=4,ambiguous=2,holdout=4):errs.append(sid+':數量')
 for c in p['cases']:
  g=evaluate(c['subtypeId'],c['input']);counts[g['decision']]+=1
  if(g['decision'],g['answer'])!=(c['expectedDecision'],c['expectedAnswer']):errs.append(c['id']+':結果')
  if c['teacherReviewed']is not False or c['appConnected']is not False or c['studentFacing']!=(c['casePurpose']!='validator-guard'):errs.append(c['id']+':flags')
 return errs,dict(counts)
def validate_pack(p):return verify_package(p)[0]
def check(path=None):
 p=json.loads(pathlib.Path(path or pathlib.Path(__file__).with_name(PACK+'.json')).read_text());es,cs=verify_package(p);assert not es,es;rt=0
 for c in p['cases']:
  if c['expectedAnswer']is None:continue
  assert evaluate(c['subtypeId'],dict(c['input'],task='check_proposal',proposal=c['expectedAnswer']))['decision']=='pass',c['id'];rt+=1
 print(json.dumps({'package':PACK,'cases':len(p['cases']),'roundtrips':rt,'decisions':cs},ensure_ascii=False))
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))
 else:check(sys.argv[1]if len(sys.argv)>1 else None)
