#!/usr/bin/env python3
"""Monte Carlo for the spatially varying local Poisson-line cell of random chords."""
import argparse
import math
import random
from collections import Counter


def clip(poly, nx, ny, bound):
    if not poly:
        return []
    out = []
    prev = poly[-1]
    pv = nx * prev[0] + ny * prev[1] - bound
    pin = pv <= 1e-11
    for cur in poly:
        cv = nx * cur[0] + ny * cur[1] - bound
        cin = cv <= 1e-11
        if cin != pin:
            den = pv - cv
            t = pv / den
            out.append((prev[0] + t * (cur[0] - prev[0]),
                        prev[1] + t * (cur[1] - prev[1])))
        if cin:
            out.append(cur)
        prev, pv, pin = cur, cv, cin
    return out


def cell_sides(radius, directions, rng):
    step = 2 * math.pi / directions
    poly = [(-64., -64.), (64., -64.), (64., 64.), (-64., 64.)]
    for j in range(directions):
        theta = step * (j + .371)
        normal_angle = theta % math.pi
        intensity = 1 / math.sqrt(max(1e-12, 1 - radius**2 * math.cos(normal_angle)**2))
        bound = rng.expovariate(intensity * step)
        poly = clip(poly, math.cos(theta), math.sin(theta), bound)
        if not poly:
            return 0
    # Remove consecutive numerical duplicates and collinear points.
    cleaned = []
    for point in poly:
        if not cleaned or math.dist(point, cleaned[-1]) > 1e-7:
            cleaned.append(point)
    if len(cleaned) > 1 and math.dist(cleaned[0], cleaned[-1]) < 1e-7:
        cleaned.pop()
    changed = True
    while changed and len(cleaned) > 3:
        changed = False
        for i in range(len(cleaned)):
            a, b, c = cleaned[i-1], cleaned[i], cleaned[(i+1) % len(cleaned)]
            cross = (b[0]-a[0])*(c[1]-b[1]) - (b[1]-a[1])*(c[0]-b[0])
            if abs(cross) < 1e-8:
                cleaned.pop(i)
                changed = True
                break
    return len(cleaned)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--samples', type=int, default=10000)
    parser.add_argument('--directions', type=int, default=256)
    parser.add_argument('--seed', type=int, default=20261202)
    parser.add_argument('--area', action='store_true', help='sample radius with area measure')
    args = parser.parse_args()
    rng = random.Random(args.seed)
    if args.area:
        counts = Counter()
        for _ in range(args.samples):
            radius = math.sqrt(rng.random())
            counts[cell_sides(radius, args.directions, rng)] += 1
        print(f"area-weighted samples={args.samples}, directions={args.directions}")
        print(" ".join(f"{k}:{counts[k]/args.samples:.5f}" for k in range(3, 12)))
        return
    radii = [0., .25, .5, .7, .85, .93, .97, .99]
    for radius in radii:
        counts = Counter(cell_sides(radius, args.directions, rng) for _ in range(args.samples))
        print(f'r={radius:.2f}', ' '.join(f'{k}:{counts[k]/args.samples:.4f}' for k in range(3, 11)))


if __name__ == '__main__':
    main()
