"""Independent feature checks on serialized UC1 STEP files, not build objects."""
from pathlib import Path
import json, math
import build123d as b
from OCP.BRepAdaptor import BRepAdaptor_Surface
from OCP.GeomAbs import GeomAbs_Cone, GeomAbs_Cylinder
from OCP.BRepCheck import BRepCheck_Analyzer
ROOT=Path(__file__).resolve().parents[1]
manifest=json.loads((ROOT/'audit/Concept_27_UC1_build_manifest.json').read_text())
checks=[]
for num in (1,2):
 row=next(r for r in manifest['part_manifest'] if r['name'].startswith(f'C27_UC1_{num:02d}_'))
 new=b.import_step(ROOT/'cad/parts'/f"{row['name']}.step")
 old=b.import_step(ROOT/'inputs/R2/parts'/f"{row['name'].replace('C27_UC1_','C27_R2_')}.step")
 assert all(BRepCheck_Analyzer(s.wrapped,True,False).IsValid() for s in new.solids())
 cones=[]
 for f in new.faces():
  a=BRepAdaptor_Surface(f.wrapped,True)
  if a.GetType()==GeomAbs_Cone and abs(abs(math.degrees(a.Cone().SemiAngle()))-1)<1e-6:
   c=a.Cone();cones.append({'origin':list(c.Location().Coord()),'angle':math.degrees(c.SemiAngle())})
 assert len(cones)==8,(num,len(cones))
 def grille(shape):
  rows=[]
  for f in shape.faces():
   a=BRepAdaptor_Surface(f.wrapped,True);bb=f.bounding_box()
   if a.GetType()==GeomAbs_Cylinder:
    c=a.Cylinder();x,y,z=c.Location().Coord()
    if abs(bb.max.Z)<1e-6 and abs(bb.min.Z+2.2)<1e-6 and 20<y<65 and c.Radius()<1.11:
     rows.append([round(x,6),round(y,6),round(c.Radius(),6)])
  return sorted(rows)
 if num==1:
  assert grille(new)==grille(old) and len(grille(new))==121
  master=b.import_step(ROOT/'cad/casting_masters/C27_UC1_FRONT_CASTING_MASTER_NO_GRILLE.step')
  assert len(grille(master))==0
 checks.append({'part':row['name'],'oneDegreeConeFaces':len(cones),'coneFeatures':cones,'valid':True})
out={'serializedShellChecks':checks,'grilleMatchesR2':True,'grilleCount':121,'frontMasterGrilleCount':0,'physicalTest':False,'passed':True}
(ROOT/'audit/UC1_serialized_feature_review.json').write_text(json.dumps(out,indent=2)+'\n')
print('Verified 16 one-degree conical faces, unchanged 121-hole grille and blank front casting master')
