#!/usr/bin/env python3
"""A black wall. Three thousand chance points, crowded toward the center of the
wall. Find the shortest closed line through all of them, visiting each once and
never crossing itself, and do not draw it. Paint everything inside it flat white.

The program samples the points, builds a short closed tour (greedy nearest
neighbour, then 2-opt and Or-opt over k-nearest-neighbour candidate lists, then
an exhaustive uncrossing pass that guarantees a simple polygon), and then fills
the interior of that polygon flat white on black. The line itself is never
stroked: every white/black boundary in the image is the tour, implied.
"""

import math
import numpy as np
from PIL import Image, ImageDraw
from scipy.spatial import cKDTree

# ----------------------------------------------------------------- parameters
SEED = 20261129
N = 3000                 # three thousand chance points
SIDE = 2500              # the wall, in pixels
SUPERSAMPLE = 4          # fill is computed at 4x and box-averaged down
SIGMA = 0.160            # crowding: gaussian spread, in units of the side
R_MAX = 0.455            # points kept inside this radius, in units of the side
K = 12                   # candidate neighbours per point for local search
KICKS = 30000            # localised double-bridge kicks, best tour kept
KICK_WINDOW = 60         # how far apart the cut points of a kick may sit


# ------------------------------------------------------------------- sampling
def sample_points(rng):
    """Isotropic gaussian cloud about the centre of the wall, truncated to a
    disc that leaves a margin at the edges."""
    pts = np.empty((N, 2))
    filled = 0
    while filled < N:
        batch = rng.normal(0.0, SIGMA, size=(4 * N, 2))
        r = np.hypot(batch[:, 0], batch[:, 1])
        keep = batch[r < R_MAX]
        take = min(len(keep), N - filled)
        pts[filled:filled + take] = keep[:take]
        filled += take
    return (pts + 0.5) * SIDE


# -------------------------------------------------------------- tour building
def tour_length(pts, tour):
    p = pts[tour]
    return float(np.hypot(*(np.roll(p, -1, axis=0) - p).T).sum())


def greedy_nn_tour(pts, tree):
    n = len(pts)
    unvisited = np.ones(n, dtype=bool)
    tour = np.empty(n, dtype=np.int64)
    cur = 0
    tour[0] = cur
    unvisited[cur] = False
    for i in range(1, n):
        k = 8
        nxt = -1
        while nxt < 0:
            k = min(k * 4, n)
            _, idx = tree.query(pts[cur], k=k)
            for j in idx:
                if unvisited[j]:
                    nxt = j
                    break
            if k >= n and nxt < 0:                     # fall back to a scan
                cand = np.flatnonzero(unvisited)
                d = np.hypot(*(pts[cand] - pts[cur]).T)
                nxt = int(cand[np.argmin(d)])
        tour[i] = nxt
        unvisited[nxt] = False
        cur = nxt
    return tour


def local_search(pts, tour, neigh, seeds=None):
    """2-opt plus Or-opt (segments of 1..3 cities) over candidate lists, with
    don't-look bits. Operates in place on `tour`; keeps `pos` in sync."""
    n = len(tour)
    pos = np.empty(n, dtype=np.int64)
    pos[tour] = np.arange(n)
    X = pts[:, 0]
    Y = pts[:, 1]

    def d(a, b):
        return math.hypot(X[a] - X[b], Y[a] - Y[b])

    def reverse(i, j):
        """Reverse tour[i..j] inclusive (cyclic), choosing the shorter arc."""
        inner = (j - i) % n + 1
        if inner * 2 > n:
            i, j = (j + 1) % n, (i - 1) % n
            inner = n - inner
        for _ in range(inner // 2):
            a, b = tour[i], tour[j]
            tour[i], tour[j] = b, a
            pos[a], pos[b] = j, i
            i = (i + 1) % n
            j = (j - 1) % n

    if seeds is None:
        queue = list(tour)
        in_queue = np.ones(n, dtype=bool)
    else:
        queue = list(seeds)
        in_queue = np.zeros(n, dtype=bool)
        in_queue[queue] = True

    def push(c):
        if not in_queue[c]:
            in_queue[c] = True
            queue.append(c)

    while queue:
        a = queue.pop()
        in_queue[a] = False
        improved = False

        # ---- 2-opt: for both tour neighbours of a, try replacing with (a,b)
        for direction in (1, -1):
            pa = pos[a]
            a_next = tour[(pa + direction) % n]
            d_a = d(a, a_next)
            for b in neigh[a]:
                if b == a or b == a_next:
                    continue
                d_ab = d(a, b)
                if d_ab >= d_a:
                    break                              # neighbours are sorted
                b_next = tour[(pos[b] + direction) % n]
                if b_next == a:
                    continue
                delta = d_ab + d(a_next, b_next) - d_a - d(b, b_next)
                if delta < -1e-10:
                    if direction == 1:
                        reverse(pos[a_next], pos[b])
                    else:
                        reverse(pos[b], pos[a_next])
                    for c in (a, a_next, b, b_next):
                        push(c)
                    improved = True
                    break
            if improved:
                break
        if improved:
            push(a)
            continue

        # ---- Or-opt: move the segment starting at a (length 1..3) elsewhere
        for seg_len in (1, 2, 3):
            pa = pos[a]
            seg = [tour[(pa + t) % n] for t in range(seg_len)]
            s0, s1 = seg[0], seg[-1]
            prev = tour[(pa - 1) % n]
            nxt = tour[(pa + seg_len) % n]
            if prev in seg or nxt in seg:
                continue
            removed = d(prev, s0) + d(s1, nxt) - d(prev, nxt)
            if removed <= 1e-10:
                continue
            done = False
            for c in neigh[s0]:
                if c in seg or c == prev:
                    continue
                for rev in (False, True):
                    head, tail = (s0, s1) if not rev else (s1, s0)
                    # insert between c and its successor
                    c_next = tour[(pos[c] + 1) % n]
                    if c_next in seg:
                        continue
                    added = d(c, head) + d(tail, c_next) - d(c, c_next)
                    if added - removed < -1e-10:
                        order = list(tour)
                        base = pos[s0]
                        for t in range(seg_len):
                            order[(base + t) % n] = -1
                        order = [v for v in order if v >= 0]
                        ins = order.index(c) + 1
                        body = seg if not rev else seg[::-1]
                        order[ins:ins] = body
                        tour[:] = np.asarray(order, dtype=np.int64)
                        pos[tour] = np.arange(n)
                        for q in (prev, nxt, s0, s1, c, c_next):
                            push(q)
                        done = True
                        break
                if done:
                    break
            if done:
                break
    return tour


# ------------------------------------------------------------- de-crossing
def seg_cross(p1, p2, p3, p4):
    """True iff open segments p1p2 and p3p4 properly cross."""
    def orient(a, b, c):
        return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
    d1 = orient(p3, p4, p1)
    d2 = orient(p3, p4, p2)
    d3 = orient(p1, p2, p3)
    d4 = orient(p1, p2, p4)
    if ((d1 > 0) != (d2 > 0)) and ((d3 > 0) != (d4 > 0)):
        return True
    # touching / collinear overlap counts as crossing for our purposes
    def on_seg(a, b, c):
        return (min(a[0], b[0]) <= c[0] <= max(a[0], b[0]) and
                min(a[1], b[1]) <= c[1] <= max(a[1], b[1]))
    if d1 == 0 and on_seg(p3, p4, p1):
        return True
    if d2 == 0 and on_seg(p3, p4, p2):
        return True
    if d3 == 0 and on_seg(p1, p2, p3):
        return True
    if d4 == 0 and on_seg(p1, p2, p4):
        return True
    return False


def find_crossings(pts, tour):
    """All properly crossing pairs of tour edges, via a uniform grid over the
    edges' bounding boxes."""
    n = len(tour)
    P = pts[tour]
    Q = np.roll(P, -1, axis=0)
    lo = np.minimum(P, Q)
    hi = np.maximum(P, Q)
    cell = max((hi - lo).max(), 1e-9) * 1.0001
    origin = pts.min(axis=0)
    buckets = {}
    for e in range(n):
        x0, y0 = ((lo[e] - origin) / cell).astype(int)
        x1, y1 = ((hi[e] - origin) / cell).astype(int)
        for cx in range(x0, x1 + 1):
            for cy in range(y0, y1 + 1):
                buckets.setdefault((cx, cy), []).append(e)
    found = set()
    for es in buckets.values():
        for i in range(len(es)):
            for j in range(i + 1, len(es)):
                e, f = es[i], es[j]
                if e == f or (e + 1) % n == f or (f + 1) % n == e:
                    continue
                if hi[e][0] < lo[f][0] or hi[f][0] < lo[e][0]:
                    continue
                if hi[e][1] < lo[f][1] or hi[f][1] < lo[e][1]:
                    continue
                if seg_cross(P[e], Q[e], P[f], Q[f]):
                    found.add((min(e, f), max(e, f)))
    return found


def uncross(pts, tour, verbose=True):
    """Repeatedly 2-opt away crossings until the closed line is simple. A
    2-opt reversal on two crossing edges always shortens the tour, so this
    terminates."""
    n = len(tour)
    for sweep in range(400):
        crossings = find_crossings(pts, tour)
        if not crossings:
            if verbose:
                print(f"  uncross: simple after {sweep} sweep(s)")
            return tour
        if verbose:
            print(f"  uncross sweep {sweep}: {len(crossings)} crossing pair(s)")
        used = np.zeros(n, dtype=bool)
        for e, f in sorted(crossings):
            if used[e] or used[f]:
                continue
            i, j = e + 1, f                 # reverse tour[e+1 .. f]
            if i > j:
                continue
            tour[i:j + 1] = tour[i:j + 1][::-1]
            used[max(e - 1, 0):f + 2] = True
    raise RuntimeError("uncrossing did not converge")


def double_bridge(rng, tour, window):
    """Double-bridge kick with the three cut points close together in tour
    order, so the seeded local search can repair it cheaply. Returns the kicked
    tour and the cities whose edges changed."""
    n = len(tour)
    a = int(rng.integers(1, n - 3))
    b = a + 1 + int(rng.integers(1, window))
    c = b + 1 + int(rng.integers(1, window))
    if c >= n:
        return None, None
    out = np.concatenate([tour[:a], tour[b:c], tour[a:b], tour[c:]])
    touched = [tour[a - 1], tour[a], tour[b - 1], tour[b],
               tour[c - 1], tour[c % n]]
    return out, touched


# ------------------------------------------------------------------ rendering
def render(pts, tour, path):
    s = SIDE * SUPERSAMPLE
    img = Image.new("L", (s, s), 0)                     # a black wall
    poly = [(float(x) * SUPERSAMPLE, float(y) * SUPERSAMPLE)
            for x, y in pts[tour]]
    ImageDraw.Draw(img).polygon(poly, fill=255, outline=None)
    img = img.resize((SIDE, SIDE), Image.LANCZOS)
    arr = np.asarray(img).astype(np.int16)
    arr = np.clip(arr, 0, 255).astype(np.uint8)
    Image.fromarray(arr, mode="L").convert("RGB").save(path)
    return arr


def main():
    rng = np.random.default_rng(SEED)
    pts = sample_points(rng)
    tree = cKDTree(pts)
    _, neigh_idx = tree.query(pts, k=K + 1)
    neigh = [row[1:].tolist() for row in neigh_idx]

    tour = greedy_nn_tour(pts, tree)
    print(f"nearest-neighbour tour: {tour_length(pts, tour):.1f}")
    tour = local_search(pts, tour, neigh)
    print(f"after 2-opt + Or-opt:   {tour_length(pts, tour):.1f}")

    best = tour.copy()
    best_len = tour_length(pts, best)
    accepted = 0
    for r in range(KICKS):
        cand, touched = double_bridge(rng, best, KICK_WINDOW)
        if cand is None:
            continue
        cand = local_search(pts, cand, neigh, seeds=touched)
        cl = tour_length(pts, cand)
        if cl < best_len - 1e-9:
            best, best_len = cand.copy(), cl
            accepted += 1
    print(f"after {KICKS} kicks:    {best_len:.1f}  ({accepted} accepted)")

    best = uncross(pts, best)
    print(f"simple closed line:     {tour_length(pts, best):.1f}")

    out = "renders-champion/render-1.png"
    render(pts, best, out)
    print(f"wrote {out}")


if __name__ == "__main__":
    main()
