#!/usr/bin/env python3
"""python3 grade.py DESIGN.json READER.json > result.json; no scores imply human review."""
import json,sys,math
D=json.load(open(sys.argv[1])); R=json.load(open(sys.argv[2])); checks=[]
def check(name,ok,detail=''): checks.append({'check':name,'pass':bool(ok),'detail':detail})
def close(a,b,tol=.01): return isinstance(a,(float,int)) and isinstance(b,(float,int)) and abs(a-b)<=tol
try:
 p=D['plans']; e={v['side']:v for v in D['elevations']}; s=D['section']; t=D['stairDetail']
 check('two levels',len(p)==2 and {x['level'] for x in p}=={'ground','upper'})
 for floor in p:
  rooms=floor['rooms']; check(floor['level']+' room bounds',all(x>=0 and y>=0 and w>0 and h>0 and x+w<=32 and y+h<=24 for _,x,y,w,h in rooms))
  check(floor['level']+' room overlap',all(not (max(a[1],b[1])<min(a[1]+a[3],b[1]+b[3]) and max(a[2],b[2])<min(a[2]+a[4],b[2]+b[4])) for i,a in enumerate(rooms) for b in rooms[i+1:]))
  for typ in ('doors','windows'):
   for id,x1,y1,x2,y2 in floor[typ]:
    on=any((x1==x2==a==c and min(b,d)<=min(y1,y2) and max(y1,y2)<=max(b,d)) or (y1==y2==b==d and min(a,c)<=min(x1,x2) and max(x1,x2)<=max(a,c)) for a,b,c,d in floor['walls'])
    check(floor['level']+' '+id+' on wall',on)
 ground=next(x for x in p if x['level']=='ground'); upper=next(x for x in p if x['level']=='upper')
 names=lambda f:' '.join(str(x[0]).lower() for x in f['rooms'])
 for name in ['living','kitchen','dining','bedroom']:check('ground '+name,name in names(ground))
 check('upper two bedrooms',sum('bed' in x[0].lower() for x in upper['rooms'])>=2);check('upper bath','bath' in names(upper))
 check('north entry',any(y1==y2==0 for _,x1,y1,x2,y2 in ground['doors']))
 check('south windows',any(y1==y2==24 for _,x1,y1,x2,y2 in ground['windows']))
 for floor in p:
  for side,line in [('north',(0,0,32,0)),('south',(0,24,32,24)),('west',(0,0,0,24)),('east',(32,0,32,24))]:
   check(floor['level']+' '+side+' outer wall',any(tuple(w)==line or tuple(w)==(line[2],line[3],line[0],line[1]) for w in floor['walls']))
 check('central stove',abs(ground['stove'][0]-16)<=6 and abs(ground['stove'][1]-12)<=6)
 check('stair alignment',ground['stair']==upper['stair']);check('section floor heights',s['floors']==[0,9]);check('site slope',s['ground']==[0,-4])
 check('roof heights',close(s['eave'],18) and close(s['ridge'],24))
 for side in ('north','south','east','west'):
  v=e[side];check(side+' elevation dimensions',close(v['width'],32 if side in ('north','south') else 24) and close(v['eave'],s['eave']) and close(v['ridge'],s['ridge']))
  expected_ground={'north':[0,0],'south':[-4,-4],'east':[0,-4],'west':[0,-4]}[side]
  check(side+' site elevation',v['ground']==expected_ground)
  for kind in ('doors','windows'):
   for id,offset,width,sill,head in v[kind]:
    openings=[o for floor in p for o in floor[kind] if o[0]==id]
    def matches(o):
     _,x1,y1,x2,y2=o
     if side=='north' and y1==y2==0: return close(min(x1,x2),offset) and close(abs(x2-x1),width)
     if side=='south' and y1==y2==24: return close(min(x1,x2),offset) and close(abs(x2-x1),width)
     if side=='west' and x1==x2==0: return close(min(y1,y2),offset) and close(abs(y2-y1),width)
     if side=='east' and x1==x2==32: return close(min(y1,y2),offset) and close(abs(y2-y1),width)
     return False
    check(side+' '+id+' plan position',any(matches(o) for o in openings))
    schedule=D['doorSchedule' if kind=='doors' else 'windowSchedule']; match=next((z for z in schedule if z[0]==id),None)
    check(side+' '+id+' schedule',bool(match) and close(width,match[1]) and close(head-sill,match[2]))
 for k in ('risers','rise','tread','run'):check('stair section/detail '+k,close(s[k],t[k]))
 check('stair rise sums',close(t['risers']*t['rise'],t['floorToFloor'],.05) and close(t['floorToFloor'],9))
 check('stair run sums',close((t['risers']-1)*t['tread'],t['run'],.05))
 check('two render descriptions',all(isinstance(D['renders'].get(k),dict) and len(D['renders'][k].get('position',[]))==3 and len(D['renders'][k].get('target',[]))==3 and len(D['renders'][k].get('description','').strip())>10 for k in ('exterior','interior')))
except (KeyError,TypeError,ValueError,StopIteration,IndexError) as ex:check('schema',False,str(ex))
def flatten(x,path=''):
 if isinstance(x,dict):
  for k,v in x.items(): yield from flatten(v,path+'/'+k)
 elif isinstance(x,list):
  for i,v in enumerate(x): yield from flatten(v,path+'/'+str(i))
 else: yield path,x
def canonical(doc):
 import copy
 doc=copy.deepcopy(doc)
 for floor in doc.get('plans',[]):
  for key in ('walls','doors','windows'):
   for item in floor.get(key,[]):
    j=0 if key=='walls' else 1
    if len(item)>=j+4 and tuple(item[j:j+2])>tuple(item[j+2:j+4]): item[j:j+4]=item[j+2:j+4]+item[j:j+2]
   floor[key]=sorted(floor.get(key,[]),key=lambda v:repr(v))

  def room_key(row):
   return str(row[0]).lower().replace(' and ',' / ').replace('  ',' ').strip()
  for room in floor.get('rooms',[]): room[0]=room_key(room)
  floor['rooms']=sorted(floor.get('rooms',[]),key=room_key)
 doc['plans']=sorted(doc.get('plans',[]),key=lambda v:v.get('level',''))
 for elev in doc.get('elevations',[]):
  for k in ('doors','windows'):elev[k]=sorted(elev.get(k,[]),key=lambda v:str(v[0]))
 doc['elevations']=sorted(doc.get('elevations',[]),key=lambda v:v.get('side',''))
 for k in ('doorSchedule','windowSchedule'):doc[k]=sorted(doc.get(k,[]),key=lambda v:str(v[0]))
 return doc
expected=canonical({k:D[k] for k in ('plans','elevations','section','stairDetail','doorSchedule','windowSchedule') if k in D}); actual=canonical(R)
def mergewalls(walls):
 groups={}
 for wall in walls:
  if not isinstance(wall,list) or len(wall)!=4 or not all(isinstance(n,(int,float)) for n in wall):continue
  x1,y1,x2,y2=wall
  if abs(x1-x2)<1e-6 and y1!=y2: key=('v',x1); interval=(min(y1,y2),max(y1,y2))
  elif abs(y1-y2)<1e-6 and x1!=x2:key=('h',y1);interval=(min(x1,x2),max(x1,x2))
  else:continue
  groups.setdefault(key,[]).append(interval)
 out=[]
 for (axis,pos),intervals in groups.items():
  intervals.sort();merged=[]
  for lo,hi in intervals:
   if merged and lo<=merged[-1][1]+1e-6: merged[-1]=(merged[-1][0],max(merged[-1][1],hi))
   else:merged.append((lo,hi))
  out.extend((axis,pos,lo,hi) for lo,hi in merged)
 return out
def wallscore(a,b):
 raw_b=b
 a=mergewalls(a);b=mergewalls(b);la=sum(y-x for _,_,x,y in a);lb=sum(y-x for _,_,x,y in b)
 # Union intersection per reference segment; prevents double credit from near-parallel duplicate lines.
 hit=0
 for axis,pos,lo,hi in a:
  overlaps=sorted((max(lo,l),min(hi,h)) for ax,p,l,h in b if ax==axis and abs(pos-p)<=.25 and min(hi,h)>max(lo,l))
  merged=[]
  for l,h in overlaps:
   if merged and l<=merged[-1][1]:merged[-1]=(merged[-1][0],max(merged[-1][1],h))
   else:merged.append((l,h))
  hit+=sum(h-l for l,h in merged)
 invalid=sum(1 for q in raw_b if not isinstance(q,list) or len(q)!=4 or not all(isinstance(n,(int,float)) for n in q) or not (q[0]==q[2] or q[1]==q[3]) or (q[0]==q[2] and q[1]==q[3]))
 return {'invalidSegments':invalid,'referenceFeet':la,'submittedFeet':lb,'matchedFeet':hit,'precision':hit/lb if lb else (1 if not la else 0),'recall':hit/la if la else (1 if not lb else 0)}
wallmetrics={}
for level in ('ground','upper'):
 ref=next((v for v in expected.get('plans',[]) if v.get('level')==level),{})
 got=next((v for v in actual.get('plans',[]) if v.get('level')==level),{})
 wallmetrics[level]=wallscore(ref.get('walls',[]),got.get('walls',[]))
for doc in (expected,actual):
 for floor in doc.get('plans',[]):floor.pop('walls',None)
a=dict(flatten(expected)); b=dict(flatten(actual));diffs=[{'path':k,'expected':v,'read':b.get(k)} for k,v in a.items() if k not in b or not (close(v,b[k],.25) if isinstance(v,(int,float)) and not isinstance(v,bool) else v==b[k])];extras=[{'path':k,'value':v} for k,v in b.items() if k not in a]
required=['plans','elevations','section','stairDetail','doorSchedule','windowSchedule'];missing=[k for k in required if k not in R]
print(json.dumps({'clientAndConsistency':{'passed':sum(c['pass'] for c in checks),'total':len(checks),'checks':checks},'blindReconstruction':{'matched':len(a)-len(diffs),'total':len(a),'differences':diffs,'extraScalars':extras,'precision':(len(a)-len(diffs))/(len(a)-len(diffs)+len(diffs)+len(extras)) if a or extras else 1,'missingRequiredFields':missing,'schemaValid':not missing and all(isinstance(R.get(k),type(D.get(k))) for k in required) and not any(v['invalidSegments'] for v in wallmetrics.values()) and all(any(f.get('level')==lv and all(k in f for k in ('rooms','walls','doors','windows','stair')) for f in R.get('plans',[]) if isinstance(f,dict)) for lv in ('ground','upper')) and all(any(e.get('side')==side and all(k in e for k in ('width','ground','eave','ridge','doors','windows')) for e in R.get('elevations',[]) if isinstance(e,dict)) for side in ('north','south','east','west')),'walls':wallmetrics},'humanValidation':'pending','limitations':'Automated checks are partial; no code, constructability, egress, completeness, circulation or visual quality certification.'},indent=2))
