import json,csv,numpy as np,collections,itertools,time
from rc import mesh,info,NAMES,TRI
import shapely
from shapely.geometry import LineString,Polygon,MultiLineString
from shapely.ops import unary_union,polygonize
integ={r['part']:r for r in json.load(open('part_integrity.json'))}
def major(n):
    return (n.startswith(('Podium_wall','Deck_','Cantilever_fascia','Tower_curtainwall','Rib_R','Basin_','Main_entry','Foundation','Occupied_roof','Central_glazed')) or '_arch_' in n)
PARTS=[n for n in NAMES if major(n)]
print(len(PARTS),'parts in scope')
zr={n:(mesh[n][0][:,2].min(),mesh[n][0][:,2].max()) for n in PARTS}
tri={n:mesh[n][0][mesh[n][1]] for n in PARTS}
def segs_at(n,z):
    T=tri[n];s=T[:,:,2]-z
    pos=s>0
    cross=np.stack([pos[:,0]!=pos[:,1],pos[:,1]!=pos[:,2],pos[:,2]!=pos[:,0]],1)
    sel=np.nonzero(cross.sum(1)==2)[0]
    if not len(sel): return np.zeros((0,2,2))
    out=np.zeros((len(sel),2,2))
    for k,i in enumerate(sel): pass
    Ts=T[sel];ss=s[sel];cs=cross[sel]
    pts=[]
    idx=[(0,1),(1,2),(2,0)]
    P=np.zeros((len(sel),2,2));cnt=np.zeros(len(sel),int)
    for e,(a,c) in enumerate(idx):
        m=cs[:,e]
        u=ss[m,a]/(ss[m,a]-ss[m,c])
        p=Ts[m,a,:2]+u[:,None]*(Ts[m,c,:2]-Ts[m,a,:2])
        rows=np.nonzero(m)[0]
        P[rows,cnt[rows]]=p;cnt[rows]+=1
    P=np.round(P,4)
    keep=np.linalg.norm(P[:,0]-P[:,1],axis=1)>1e-6
    return P[keep]
def fill_from_segs(P):
    if len(P)==0: return None,None
    lines=shapely.linestrings(P)
    u=unary_union(list(lines))
    cells=list(polygonize(u))
    if not cells: return None,u
    inside=[]
    x1,y1=P[:,0,0],P[:,0,1];x2,y2=P[:,1,0],P[:,1,1]
    for c in cells:
        p=c.representative_point();px,py=p.x,p.y
        m=((y1>py)!=(y2>py))
        xi=x1[m]+(py-y1[m])*(x2[m]-x1[m])/(y2[m]-y1[m])
        if (xi>px).sum()%2==1: inside.append(c)
    if not inside: return None,u
    return unary_union(inside),u
zs=sorted(set(list(np.arange(0.5,240,1.0))+[0.3,0.57,17.7,35.7,53.7,215.8,16.0,34.0,52.0]))
ov=collections.defaultdict(lambda:dict(maxA=0,zmaxA=None,vol=0.0,nslices=0))       # solid-solid & fill-fill
sh=collections.defaultdict(lambda:dict(maxL=0,zmaxL=None,nslices=0,vol=0.0))
t0=time.time()
dz={}
zl=np.array(zs)
for i,z in enumerate(zs):
    w=(zs[i+1]-zs[i-1])/2 if 0<i<len(zs)-1 else 0.5
    F={};U={}
    for n in PARTS:
        lo,hi=zr[n]
        if z<lo-1e-9 or z>hi+1e-9: continue
        P=segs_at(n,z)
        f,u=fill_from_segs(P)
        if f is not None and not f.is_empty: F[n]=f
        if u is not None: U[n]=u
    names=list(F)
    bb={n:F[n].bounds for n in names}
    for a,b in itertools.combinations(names,2):
        A=bb[a];B=bb[b]
        if A[2]<B[0] or B[2]<A[0] or A[3]<B[1] or B[3]<A[1]: continue
        ca=integ[a]['closed'];cb=integ[b]['closed']
        if ca and cb:
            ar=F[a].intersection(F[b]).area
            if ar>0.01:
                d=ov[(a,b)];d['nslices']+=1;d['vol']+=ar*w
                if ar>d['maxA']:d['maxA']=ar;d['zmaxA']=z
        elif (not ca) and (not cb):
            # shell vs shell: intersection of slice lines (count crossing points)
            x=U[a].intersection(U[b])
            n_pts=0 if x.is_empty else (len(x.geoms) if hasattr(x,'geoms') else 1)
            if n_pts>0:
                d=sh[(a,b,'shell-shell')];d['nslices']+=1
                if n_pts>d['maxL']:d['maxL']=n_pts;d['zmaxL']=z
        else:
            shell,solid=(a,b) if not ca else (b,a)
            L=U[shell].intersection(F[solid]).length
            if L>0.01:
                d=sh[(shell,solid,'shell-in-solid')];d['nslices']+=1;d['vol']+=L*w
                if L>d['maxL']:d['maxL']=L;d['zmaxL']=z
    if i%40==0: print(i,z,round(time.time()-t0,1),flush=True)
rows=[]
for (a,b),d in ov.items():
    rows.append(dict(kind='solid-solid(material overlap)',part_a=a,part_b=b,group_a=TRI[a]['grp'],group_b=TRI[b]['grp'],max_overlap_area_m2=round(d['maxA'],3),z_at_max=d['zmaxA'],slices_overlapping=d['nslices'],approx_overlap_volume_m3=round(d['vol'],2)))
for (a,b,k),d in sh.items():
    rows.append(dict(kind=k+('(crossing_length_m)' if k=='shell-in-solid' else '(crossing_points)'),part_a=a,part_b=b,group_a=TRI[a]['grp'],group_b=TRI[b]['grp'],max_overlap_area_m2=round(d['maxL'],3),z_at_max=d['zmaxL'],slices_overlapping=d['nslices'],approx_overlap_volume_m3=round(d['vol'],2)))
rows.sort(key=lambda r:(r['kind'],-r['max_overlap_area_m2']))
with open('interpenetration_pairs.csv','w',newline='') as f:
    w=csv.DictWriter(f,fieldnames=list(rows[0].keys()));w.writeheader();w.writerows(rows)
json.dump(rows,open('interpenetration_pairs.json','w'),indent=1,default=float)
for k in sorted({r['kind'] for r in rows}):
    rr=[r for r in rows if r['kind']==k];print('==',k,len(rr))
    for r in rr[:15]: print(r['part_a'],'|',r['part_b'],'max',r['max_overlap_area_m2'],'@z',r['z_at_max'],'slices',r['slices_overlapping'],'vol~',r['approx_overlap_volume_m3'])
