#!/usr/bin/env python3
"""Finite confirmed grade4 measurement contracts. stdlib only; no OCR/SVG/App."""
import json,pathlib,sys,re,copy,collections
from fractions import Fraction as F
PACK='grade4-length-methods';SUBTYPES=('g4-length-convert', 'g4-length-add-subtract', 'g4-length-benchmark')
REQ={'g4-length-convert':['quantity','fromUnit','toUnit'],'g4-length-add-subtract':['firstKm','firstM','secondKm','secondM','operation'],'g4-length-benchmark':['perSegmentM','segments','approximate'], 'g4-area-cover':['fullSquares','halfSquares','unitSquaresConfirmed','noOverlapConfirmed'],'g4-area-remaining':['total','covered','unit'],'g4-area-estimate':['fullSquares','partialSquares','unitSquaresConfirmed','boundaryPartialConfirmed'], 'g4-volume-layers':['layerCounts','unitCubesConfirmed','allLayersConfirmed','noOverlapConfirmed'],'g4-volume-changes':['original','added','removed','unitCubesConfirmed'],'g4-time-elapsed':['start','end'],'g4-time-shift':['clock','durationMinutes','direction'],'g4-time-normalize':['days','hours','minutes','seconds']}
class Need(Exception):pass
class Bad(Exception):pass
class Outside(Exception):pass
def out(decision,answer=None,reason=''):return dict(decision=decision,answer=answer,reason=reason)
def ni(v,lo,hi):
 if type(v)is not int:raise Bad('原量須整數，不用布林/浮點或字串猜值')
 if not lo<=v<=hi:raise Outside('超出明列有限數域，轉適用方法')
 return v
def choice(v,values):
 if type(v)is not str or v not in values:raise Bad('原單位或角色需明確指定')
 return v
def derived(v):
 if type(v)is int:
  if abs(v)>10**128:raise Bad('答案超出精確輸入界限')
  return F(v)
 if type(v)is not str or len(v)>260 or not re.fullmatch(r'-?[0-9]{1,128}(?:/[1-9][0-9]{0,127}|\.[0-9]{1,128})?',v):raise Bad('答案需有限精確有理數')
 try:return F(v)
 except(ValueError,ZeroDivisionError):raise Bad('答案分母不能為0')
def normalize(p,a):
 if type(p)is not dict or set(p)!=set(a):raise Bad('答案所有欄位與角色須保留')
 ans={}
 for k,v in a.items():
  x=p[k]
  if type(v)is bool:
   if type(x)is not bool:raise Bad('估測/精確標記須真偽')
   ans[k]=x
  elif type(v)is int or k in('area','estimate'):ans[k]=derived(x)
  else:
   if type(x)is not str:raise Bad('答案單位/角色需文字')
   ans[k]=x
 return ans
def clock_missing(c):
 if type(c)is not dict:return False
 required=['system','hour','minute','day']
 if type(c.get('system'))is str and c.get('system')=='12':required+=['period']
 return any(c.get(k)is None for k in required)
def clock(c):
 if type(c)is not dict:raise Bad('時刻需完整紀錄')
 sys=choice(c['system'],('12','24'));required={'system','hour','minute','day'}|({'period'}if sys=='12'else set())
 if set(c)!=required:raise Bad('時刻欄位不符，不從未知附註補值')
 h=ni(c['hour'],1,12)if sys=='12'else ni(c['hour'],0,23);m=ni(c['minute'],0,59);day=ni(c['day'],0,2)
 if sys=='12':h=h%12+(12 if choice(c['period'],('上午','下午'))=='下午'else 0)
 return day*1440+h*60+m

def evaluate(s,r):
 if type(s)is not str or s not in SUBTYPES or type(r)is not dict:return out('block',reason='非本有限方法')
 fs=REQ[s]
 # Missing original facts precede type errors; only known required nested fields are scanned.
 if r.get('confirmed')is not True or any(r.get(k)is None for k in fs):return out('confirm',reason='先補清同一題原量/單位，不猜條件')
 for key in('start','end','clock'):
  if key in fs and clock_missing(r[key]):return out('confirm',reason='時刻制/上午下午/日序缺少，先核對')
 if s=='g4-volume-layers'and type(r['layerCounts'])is list and any(v is None for v in r['layerCounts']):return out('confirm',reason='先確認每一層含被遮住的全部顆數')
 if r.get('task')not in('solve','check_proposal')or set(r)-set(fs)-{'task','confirmed','proposal'}:return out('block',reason='任務或未知欄位不適用')
 try:
  for k in fs:
   if k.endswith('Confirmed'):
    if type(r[k])is not bool:raise Bad('原操作確認須明確真偽')
    if not r[k]:raise Need('先核對單位、全部範圍與不重疊前提')
  if s=='g4-length-convert':
   n=ni(r['quantity'],0,9999);source=choice(r['fromUnit'],('公里','公尺','公分','毫米'));target=choice(r['toUnit'],('公里','公尺','公分','毫米'));units=['公里','公尺','公分','毫米'];i,j=units.index(source),units.index(target)
   if abs(i-j)!=1:raise Outside('首包只相鄰單位；跨多級換算另路由')
   factor=[1000,100,10][min(i,j)]
   if i<j:a=dict(value=n*factor,unit=target)
   else:q,rem=divmod(n,factor);a=dict(whole=q,unit=target,remainder=rem,remainderUnit=source)
  elif s=='g4-length-add-subtract':
   a1=ni(r['firstKm'],0,20)*1000+ni(r['firstM'],0,999);a2=ni(r['secondKm'],0,20)*1000+ni(r['secondM'],0,999);op=choice(r['operation'],('add','subtract'));v=a1+a2 if op=='add'else a1-a2
   if v<0:raise Need('題目要拿走的路程大於原量，先核對角色；不造負路程')
   a=dict(kilometers=v//1000,meters=v%1000)
  elif s=='g4-length-benchmark':
   n=ni(r['perSegmentM'],0,1000);times=ni(r['segments'],0,20)
   if type(r['approximate'])is not bool:raise Bad('先確認原基準是否概數')
   v=n*times;a=dict(meters=v,kilometers=v//1000,remainingMeters=v%1000,approximate=r['approximate']and times>0)
  elif s=='g4-area-cover':
   full=ni(r['fullSquares'],0,100);half=ni(r['halfSquares'],0,40);a=dict(area=str(F(full)+F(half,2)),unit='平方公尺')
  elif s=='g4-area-remaining':
   choice(r['unit'],('平方公尺',));total=ni(r['total'],0,1000);covered=ni(r['covered'],0,1000)
   if covered>total:raise Need('已鋪面積超過總面積，先確認兩個量與重疊')
   a=dict(area=str(total-covered),unit='平方公尺')
  elif s=='g4-area-estimate':
   full=ni(r['fullSquares'],0,100);partial=ni(r['partialSquares'],0,40);a=dict(estimate=str(F(full)+F(partial,2)),lowerBound=full,upperBound=full+partial,approximate=partial>0,unit='平方公尺')
  elif s=='g4-volume-layers':
   xs=r['layerCounts']
   if type(xs)is not list or not 1<=len(xs)<=8:raise Bad('各層顆數需1至8層完整清單')
   values=[ni(x,0,100)for x in xs];a=dict(cubes=sum(values),volume=sum(values),unit='立方公分')
  elif s=='g4-volume-changes':
   initial=ni(r['original'],0,200);plus=ni(r['added'],0,200);minus=ni(r['removed'],0,400)
   if minus>initial+plus:raise Need('拿走超過全部積木，先核對原量及新增量')
   v=initial+plus-minus;a=dict(cubes=v,volume=v,unit='立方公分')
  elif s=='g4-time-elapsed':
   start,end=clock(r['start']),clock(r['end'])
   if end<start:raise Need('明示日序下結束早於開始，核對日序/上午下午，不自動補隔日')
   v=end-start;a=dict(hours=v//60,minutes=v%60,totalMinutes=v)
  elif s=='g4-time-shift':
   base=clock(r['clock']);duration=ni(r['durationMinutes'],0,2880);way=choice(r['direction'],('forward','backward'));v=base+duration if way=='forward'else base-duration;day,within=divmod(v,1440);a=dict(day=day,hour=within//60,minute=within%60)
  else:
   days=ni(r['days'],0,3);hours=ni(r['hours'],0,72);minutes=ni(r['minutes'],0,180);seconds=ni(r['seconds'],0,180);total=((days*24+hours)*60+minutes)*60+seconds;rest=total;nd,rest=divmod(rest,86400);nh,rest=divmod(rest,3600);nm,ns=divmod(rest,60);a=dict(days=nd,hours=nh,minutes=nm,seconds=ns,totalSeconds=total)
 except Need as e:return out('confirm',reason=str(e))
 except Bad as e:return out('block',reason=str(e))
 except Outside as e:return out('block',reason=str(e))
 if r['task']=='check_proposal':
  if r.get('proposal')is None:return out('confirm',a,'先提供想法，保留原題')
  try:good=normalize(r['proposal'],a)==normalize(a,a)
  except Bad:good=False
  if not good:return out('reject',a,'保留原題正解，回到具體錯步')
 return out('pass',a,'依固定方法並由原量驗回')
def validate_pack(p):
 errors=[]
 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']:
  got=evaluate(c['subtypeId'],c['input'])
  if(got['decision'],got['answer'])!=(c['expectedDecision'],c['expectedAnswer']):errors.append(c['id'])
  if c['teacherReviewed']is not False or c['appConnected']is not False or c['casePurpose']not in('teaching-example','proposal-review','validator-guard')or c['studentFacing']!=(c['casePurpose']!='validator-guard'):errors.append(c['id']+':flags')
 return errors
def check(path=None):
 p=json.loads(pathlib.Path(path or pathlib.Path(__file__).with_name(PACK+'.json')).read_text());errors=validate_pack(p);assert not errors,errors;print(json.dumps(dict(pack=PACK,cases=len(p['cases']),subtypes=len(SUBTYPES),passed=True),ensure_ascii=False))
if __name__=='__main__':check(sys.argv[1]if len(sys.argv)>1 else None)
