PACK='grade1-indirect-length'
SUBTYPES=('g1-length-string-transfer', 'g1-length-common-reference')
import json,pathlib,re,sys,copy,collections
from fractions import Fraction as F
REQ={'g1-length-cover': ['aCount', 'bCount', 'sameUnitsConfirmed', 'coveredConfirmed'], 'g1-length-direct': ['aEnd', 'bEnd', 'alignedConfirmed', 'orderConfirmed'], 'g1-length-string-transfer': ['curvedCount', 'straightCount', 'sameUnitsConfirmed', 'noStretchConfirmed', 'pathTransferConfirmed'], 'g1-length-common-reference': ['aRelation', 'bRelation', 'sameReferenceConfirmed', 'aReference', 'bReference'], 'g1-calendar-neighbor': ['month', 'day', 'when', 'sameMonthConfirmed'], 'g1-clock-whole-half': ['hourStart', 'longAt', 'shortAt', 'handRolesConfirmed'], 'g1-day-period-order': ['first', 'second', 'cardOrderConfirmed'], 'g1-original-cut-restore': ['recipe', 'pieces', 'joins', 'matchedConfirmed'], 'g1-face-imprint': ['solid', 'quarterTurns', 'flatContactConfirmed', 'noSmearConfirmed']}
RECIPES={'square-diagonal': ('正方形', '從一個角連到對面角切成2片', ['A', 'B'], [['A斜切邊', 'B斜切邊']]), 'square-midline': ('正方形', '從上邊中間連到下邊中間直切成2片', ['A', 'B'], [['A內切邊', 'B內切邊']]), 'rectangle-diagonal': ('長方形', '從一角到對面角切成2片', ['A', 'B'], [['A斜切邊', 'B斜切邊']]), 'rectangle-midline': ('長方形', '從上邊中間連到下邊中間直切成2片', ['A', 'B'], [['A內切邊', 'B內切邊']]), 'triangle-fan2': ('三角形', '從頂端連到下面邊的中間切成2片', ['A', 'B'], [['A內切邊', 'B內切邊']]), 'circle-half': ('圓形', '從紙片正中直切成2片', ['A', 'B'], [['A直切邊', 'B直切邊']]), 'square-grid4': ('正方形', '中央一橫一豎切成4片', ['A', 'B', 'C', 'D'], [['A右切邊', 'B左切邊'], ['A下切邊', 'C上切邊'], ['B下切邊', 'D上切邊'], ['C右切邊', 'D左切邊']]), 'rectangle-strips3': ('長方形', '用兩條平行切線分成左中右3片', ['A', 'B', 'C'], [['A右切邊', 'B左切邊'], ['B右切邊', 'C左切邊']]), 'rectangle-grid4': ('長方形', '一橫一豎分成左上右上左下右下4片', ['A', 'B', 'C', 'D'], [['A右切邊', 'B左切邊'], ['A下切邊', 'C上切邊'], ['B下切邊', 'D上切邊'], ['C右切邊', 'D左切邊']]), 'triangle-fan3': ('三角形', '從頂端連兩條線到下面邊，分成左中右3片', ['A', 'B', 'C'], [['A右切邊', 'B左切邊'], ['B右切邊', 'C左切邊']]), 'square-corner-strip': ('正方形', '沿靠右一條直線切成寬窄2片', ['A', 'B'], [['A右切邊', 'B左切邊']]), 'circle-strips3': ('圓形', '用兩條互不交叉的平行直線分成左中右3片', ['A', 'B', 'C'], [['A右切邊', 'B左切邊'], ['B右切邊', 'C左切邊']])}
IMPRINTS={'cube-flat': ('方塊積木', '已確認的一個平正方形面', '正方形'), 'cuboid-wide': ('長盒積木', '已確認的一個長方形面，長邊比短邊長', '長方形'), 'cylinder-end': ('圓柱積木', '一端的平圓面', '圓形'), 'triangle-prism-end': ('三角柱積木', '一端的平三角形面', '三角形')}
PERIODS=('上午','中午','下午','晚上')
def out(d,a=None,r=''):return dict(decision=d,answer=a,reason=r)
def integer(v,lo,hi):
 if type(v)is not int or not lo<=v<=hi:raise ValueError('原觀察數量需契約範圍內整數，布林不是數量')
 return v
def enum(v,values):
 if type(v)is not str or v not in values:raise ValueError('觀察標記不在已確認的有限資料中')
 return v
def rel(a,b):return '甲較短'if a<b else'甲較長'if a>b else'一樣長'
def joins_norm(xs):
 if type(xs)is not list or len(xs)>8:raise ValueError('切邊配對需有限清單')
 out=[]
 for pair in xs:
  if type(pair)is not list or len(pair)!=2 or any(type(v)is not str or len(v)>20 for v in pair):raise ValueError('每次配對恰兩條已知切邊')
  out.append(tuple(sorted(pair)))
 if len(set(out))!=len(out):raise ValueError('切邊不可重複接合')
 return sorted(out)
def derived(v):
 if type(v)is int and abs(v)<10**100:return F(v)
 if type(v)is not str or len(v)>260 or not re.fullmatch(r'-?[0-9]{1,128}(?:/[0-9]{1,128}|\.[0-9]{1,128})?',v):raise ValueError('有限精確答案格式')
 return F(v)
def normal(p,a):
 if type(p)is not dict or set(p)!=set(a):raise ValueError('答案欄位不符')
 z={}
 for k,v in a.items():
  if type(v)is int:z[k]=derived(p[k])
  elif type(p[k])is str:z[k]=p[k]
  else:raise ValueError('答案文字角色不符')
 return z
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='非本有限操作模板')
 fs=REQ[subtype_id]
 if r.get('confirmed')is not True or any(r.get(k)is None for k in fs):return out('confirm',r='先確認原圖或實體操作的缺少條件，不自行補觀察')
 if subtype_id=='g1-original-cut-restore'and type(r.get('pieces'))is list and any(v is None for v in r['pieces']):return out('confirm',r='先確認全部原拼片')
 if subtype_id=='g1-original-cut-restore'and type(r.get('joins'))is list and any(p is None or type(p)is list and any(v is None for v in p)for p in r['joins']):return out('confirm',r='先確認原切邊對應')
 if r.get('task')not in('solve','check_proposal')or set(r)-set(fs)-{'confirmed','task','proposal'}:return out('block',r='任務或欄位不符')
 for k in fs:
  if k.endswith('Confirmed'):
   if type(r[k])is not bool:return out('block',r='操作確認需明確真偽')
   if not r[k]:return out('confirm',r='先實際操作或核對圖上標記，再提供確認條件')
 s=subtype_id
 try:
  if s=='g1-length-cover':a={'relation':rel(integer(r['aCount'],1,20),integer(r['bCount'],1,20))}
  elif s=='g1-length-direct':a={'relation':rel(integer(r['aEnd'],1,20),integer(r['bEnd'],1,20))}
  elif s=='g1-length-string-transfer':a={'relation':'彎線較短'if integer(r['curvedCount'],1,20)<integer(r['straightCount'],1,20)else'彎線較長'if r['curvedCount']>r['straightCount']else'一樣長'}
  elif s=='g1-length-common-reference':

   for name in ('aReference','bReference'):
    if type(r[name])is not str or not re.fullmatch(r'[\u4e00-\u9fffA-Za-z0-9]{1,16}',r[name]):raise ValueError('參照帶標記需確認')
   if r['aReference']!=r['bReference']:return out('confirm',r='不是同一條參照帶，不能把兩個比較直接接起來')
   x=enum(r['aRelation'],('<','=','>'));y=enum(r['bRelation'],('<','=','>'));v={'<':0,'=':1,'>':2};a={'relation':rel(v[x],v[y])if x!=y or x=='='else'不能確定'}
  elif s=='g1-calendar-neighbor':
   mo=integer(r['month'],1,12);day=integer(r['day'],1,31);when=enum(r['when'],('昨天','今天','明天'))
   if not 2<=day<=27:return out('block',r='月底/月初或本有限同月表外，請看原日曆相鄰格，不猜每月天數')
   a={'month':mo,'day':day+({'昨天':-1,'今天':0,'明天':1}[when])}
  elif s=='g1-clock-whole-half':
   h=integer(r['hourStart'],1,12);long=integer(r['longAt'],1,12);short=enum(r['shortAt'],('數字上','兩數之間'))
   if long not in(6,12):return out('block',r='只教整點半點；其他鐘面先轉適合活動')
   if short!=('數字上'if long==12 else'兩數之間'):return out('confirm',r='長短針相互矛盾，先核對原鐘面，不硬判時刻')
   a={'hour':h,'part':'整點'if long==12 else'半點'}
  elif s=='g1-day-period-order':
   x=enum(r['first'],PERIODS);y=enum(r['second'],PERIODS);a={'relation':'甲較早'if PERIODS.index(x)<PERIODS.index(y)else'甲較晚'if PERIODS.index(x)>PERIODS.index(y)else'同一時段'}
  elif s=='g1-original-cut-restore':
   recipe=enum(r['recipe'],RECIPES);name,cut,pieces,joins=RECIPES[recipe]
   if type(r['pieces'])is not list or any(type(p)is not str for p in r['pieces']):raise ValueError('原片標記需清單')
   if sorted(r['pieces'])!=sorted(pieces)or joins_norm(r['joins'])!=joins_norm(joins):return out('confirm',r='原片或切邊對應不足/矛盾，需重新實作，不從示意補關係')
   a={'shape':name}
  elif s=='g1-face-imprint':
   solid=enum(r['solid'],IMPRINTS);integer(r['quarterTurns'],0,4);a={'shape':IMPRINTS[solid][2]}
  else:return out('block',r='非本有限操作模板')
 except(ValueError,TypeError,KeyError,OverflowError,ZeroDivisionError)as e:return out('block',r=str(e))
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',a,'先提供要核對的想法')
  try:good=normal(r['proposal'],a)==normal(a,a)
  except(ValueError,TypeError,OverflowError,ZeroDivisionError):good=False
  if not good:return out('reject',a,'保留已確認原操作結果；錯因見具體步驟')
 return out('pass',a,'本結論只依已確認實體/圖上結構，不代替原圖理解')
def verify_package(p):
 errors=[];counts=collections.Counter()
 for s in SUBTYPES:
  if collections.Counter(c['kind']for c in p['cases']if c['subtypeId']==s)!=dict(normal=8,negative=6,boundary=4,ambiguous=2,holdout=4):errors.append(s+':counts')
 for c in p['cases']:
  g=evaluate(c['subtypeId'],c['input']);counts[g['decision']]+=1
  if(g['decision'],g['answer'])!=(c['expectedDecision'],c['expectedAnswer']):errors.append(c['id'])
  if c['studentFacing']!=(c['casePurpose']!='validator-guard')or c['teacherReviewed']is not False or c['appConnected']is not False:errors.append(c['id']+':flags')
 return errors,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());e,c=verify_package(p);assert not e,e;n=0
 for x in p['cases']:
  if x['expectedAnswer']is None:continue
  r=dict(x['input'],task='check_proposal',proposal=x['expectedAnswer']);assert evaluate(x['subtypeId'],r)['decision']=='pass';n+=1
 print(json.dumps(dict(pack=PACK,cases=len(p['cases']),roundtrips=n,decisions=c),ensure_ascii=False))
if __name__=='__main__':check(sys.argv[1]if len(sys.argv)>1 else None)
