"""Direct check: N real random chords in the unit disk, uniform random point, side count of its cell."""
import math, random, sys
from collections import Counter
from multiprocessing import Pool

def clip(poly, nx, ny, b):
    out=[]; prev=poly[-1]; pv=nx*prev[0]+ny*prev[1]-b
    for cur in poly:
        cv=nx*cur[0]+ny*cur[1]-b
        if (cv<=0)!=(pv<=0):
            t=pv/(pv-cv); out.append((prev[0]+t*(cur[0]-prev[0]),prev[1]+t*(cur[1]-prev[1])))
        if cv<=0: out.append(cur)
        prev,pv=cur,cv
    return out

def one(args):
    N,seed,samples=args; rng=random.Random(seed); c=Counter()
    for _ in range(samples):
        r=math.sqrt(rng.random()); a=rng.random()*2*math.pi; x=(r*math.cos(a),r*math.sin(a))
        poly=[(-2,-2),(2,-2),(2,2),(-2,2)]
        for _ in range(N):
            p=rng.random()*2*math.pi; q=rng.random()*2*math.pi
            m=(p+q)/2; nx,ny=math.cos(m),math.sin(m); b=math.cos((p-q)/2)   # line z.n=b through both endpoints
            if nx*x[0]+ny*x[1]>b: nx,ny,b=-nx,-ny,-b
            # quick reject: does the line cut the current polygon?
            if all(nx*v[0]+ny*v[1]<=b for v in poly): continue
            poly=clip(poly,nx,ny,b)
        if any(v[0]*v[0]+v[1]*v[1]>1+1e-12 for v in poly): c['rim']+=1
        else: c[len(poly)]+=1
    return c

if __name__=='__main__':
    N=int(sys.argv[1]); S=int(sys.argv[2]); P=8
    with Pool(P) as pool: res=pool.map(one,[(N,1000+i,S//P) for i in range(P)])
    c=sum(res,Counter()); T=sum(c.values())
    print(f"N={N} samples={T} rim={c['rim']/T:.4f} | "+" ".join(f"{k}:{c[k]/T:.4f}" for k in range(3,10)))
    inner=T-c['rim']
    print("  conditional on not touching rim: "+" ".join(f"{k}:{c[k]/inner:.4f}" for k in range(3,10)))
