import json,csv,numpy as np,collections
from rc import *
res={}
# --- Main entry: +Y rays from y=-70
xs=np.arange(-14,14.001,0.25);zs=np.arange(0.05,16.001,0.25)
X,Z=np.meshgrid(xs,zs);O=np.c_[X.ravel(),np.full(X.size,-70.0),Z.ravel()]
out=cast(O,[0,1,0],tmax=60);H=flat(out,len(O))
grid=np.empty(X.shape,object)
first_after=collections.Counter()
arch_hit=np.zeros(X.size,bool);wall_hit=np.zeros(X.size,bool);firstpart=[None]*X.size
for i,h in enumerate(H):
    names=[(n,70-0+t-70) for t,n,dt,nz in h]  # y = -70+t
    ys=[(n,-70+t) for t,n,dt,nz in h]
    arch_hit[i]=any(n=='Main_entry_clear_18x14' for n,_ in ys)
    wall_hit[i]=any(n=='Podium_wall_1' for n,_ in ys)
    firstpart[i]=ys[0] if ys else None
def interval_at(zh):
    j=int(np.argmin(abs(zs-zh)));row=slice(j*len(xs),(j+1)*len(xs))
    free=~arch_hit[row]
    # largest contiguous run of free x
    best=(0,None,None);run=0;s=None
    for k,f in enumerate(free):
        if f:
            if run==0:s=xs[k]
            run+=1
            if run*0.25>best[0]: best=(run*0.25,s,xs[k])
        else: run=0
    return best, zs[j]
for zh in (1.0,1.7):
    (wd,a,b),zz=interval_at(zh)
    j=int(np.argmin(abs(zs-zh)));row=slice(j*len(xs),(j+1)*len(xs))
    # rays with x in [-8.5,8.5] at that height: what is hit first/last
    fr=collections.Counter(str(firstpart[k][0]) if firstpart[k] else 'none' for k in range(row.start,row.stop) if abs(X.ravel()[k])<=8.5)
    walls=[firstpart[k] for k in range(row.start,row.stop) if abs(X.ravel()[k])<=8.5]
    wy=sorted({round(p[1],2) for p in walls if p})
    print('z=%.2f sampled %.2f: arch-free x run %.2f m (%s..%s); first hits for |x|<=8.5: %s ; first-hit y values %s'%(zh,zz,wd,a,b,dict(fr),wy))
    res['main_entry_z%.1f'%zh]=dict(sampled_z=float(zz),arch_free_run_m=wd,x_from=a,x_to=b,first_hit_counts_abs_x_le_8_5=dict(fr),first_hit_y=wy)
# arch frame opening: across all z at x=0 column: which z free of arch
col=np.argmin(abs(xs-0));free_z=[zs[j] for j in range(len(zs)) if not arch_hit[j*len(xs)+col]]
# first contiguous run from the ground
run=[];
for j in range(len(zs)):
    if not arch_hit[j*len(xs)+col]: run.append(zs[j])
    else:
        if run: break
print('x=0 column: arch-free z from',run[0],'to',run[-1],'(first contiguous run from low z)')
# overall bbox clear opening of frame: x extent free at z=1 and z height at x=0
res['main_entry_frame_clear_height_at_x0_m']=[float(run[0]),float(run[-1])]
# is it through? any ray (|x|<=8.5,z<=13.5) with no Podium_wall_1 hit and no hit at all between y=-70 and y=-40?
thru=0;tot=0;wallfirst=0
for k in range(X.size):
    if abs(X.ravel()[k])<=8.5 and Z.ravel()[k]<=13.5:
        tot+=1
        h=[(n,-70+t) for t,n,dt,nz in H[k]]
        inner=[p for p in h if p[1]<-30]
        if not inner: thru+=1
        if any(n=='Podium_wall_1' for n,_ in h if True): wallfirst+=1
print('rays in |x|<=8.5, z<=13.5 total',tot,'with NO hit at all for y<-30:',thru,'hitting Podium_wall_1:',wallfirst)
# Podium_wall_1 hit y and whether hits normal faces front
w=[(round(-70+t,2),round(dt,2)) for k in range(X.size) for t,n,dt,nz in H[k] if n=='Podium_wall_1' and abs(X.ravel()[k])<=8.5][:3]
print('wall hit sample (y,dot)',w)
# unique sets of x-range blocked by Podium_wall_1 at z=1.0
j=int(np.argmin(abs(zs-1.0)));row=range(j*len(xs),(j+1)*len(xs))
wx=[X.ravel()[k] for k in row if wall_hit[k]];print('Podium_wall_1 hit x-range at z=1.0:',min(wx),max(wx))
res['main_entry_rays_total_in_opening']=tot;res['main_entry_rays_with_no_hit_y_lt_-30']=thru;res['main_entry_rays_hitting_Podium_wall_1']=wallfirst
# arch bbox
v,t=mesh['Main_entry_clear_18x14'];print('arch bbox',v.min(0),v.max(0))
v,t=mesh['Podium_wall_1'];
# --- all arches
arch_rows=[]
for n in NAMES:
    if '_arch_' not in n and not n.startswith('Main_entry'): continue
    v,t=mesh[n];lo,hi=v.min(0),v.max(0)
    if n.startswith('Main'): side='front'
    else: side=n.split('_')[1]
    d={'front':(0,1.0,0),'rear':(0,-1.0,0),'left':(1.0,0,0),'right':(-1.0,0,0)}[side]
    lat=(1,0,0) if side in('front','rear') else (0,1,0)
    li=0 if side in('front','rear') else 1; di=1-li
    cx=(lo[li]+hi[li])/2;hw=(hi[li]-lo[li])/2
    # start outside along -d, 8m before the extreme
    ls=np.arange(lo[li]+0.125,hi[li],0.25)
    for zh in (1.0,1.7):
        O=[];
        for l in ls:
            p=np.zeros(3);p[li]=l;p[2]=lo[2]+zh
            # start point 8 m beyond outer face along -d
            if side in('front','left'): p[di]=lo[di]-8
            else: p[di]=hi[di]+8
            O.append(p)
        O=np.array(O);out=cast(O,d,tmax=250);Hh=flat(out,len(O))
        thru=[];blocked_by=collections.Counter();free=0;gaps=[]
        for p,h in zip(O,Hh):
            if any(nn==n for _,nn,_,_ in h): continue
            thru.append(p[li])
            others=[nn for _,nn,_,_ in h]
            if others: blocked_by[others[0]]+=1;gaps.append(h[0][0]-8)
            else: free+=1
        # clear run width through arch frame
        thru=np.array(sorted(thru));wd=0
        if len(thru):
            br=np.split(thru,np.where(np.diff(thru)>0.26)[0]+1);wd=max((b[-1]-b[0]+0.25) for b in br)
        arch_rows.append(dict(part=n,side=side,z_ray=zh,frame_clear_run_width_m=round(float(wd),2),rays_total=len(O),rays_through_frame=len(thru),rays_through_and_then_hit=sum(blocked_by.values()),rays_through_and_no_hit_250m=free,first_blocker_after_frame=';'.join(f'{k}x{v}' for k,v in blocked_by.items()),dist_to_first_blocker_from_start_minus8_m=(round(float(np.median(gaps)),2) if gaps else None)))
with open('arch_openings.csv','w',newline='') as f:
    w=csv.DictWriter(f,fieldnames=list(arch_rows[0].keys()));w.writeheader();w.writerows(arch_rows)
tot=collections.Counter()
for r in arch_rows:
    if r['z_ray']==1.0: 
        tot['arches']+=1;tot['frame_open']+=r['rays_through_frame']>0;tot['through_then_hit_all']+=(r['rays_through_frame']>0 and r['rays_through_and_no_hit_250m']==0);tot['some_free']+=r['rays_through_and_no_hit_250m']>0
print(dict(tot))
for r in arch_rows:
    if r['part'].startswith('T1_front') or r['part'].startswith('Main'): print(r)
json.dump(res,open('entry_results.json','w'),indent=1,default=float)
