"""Shark puzzle, the maths in plain Python (no libraries needed).

Run it:   python3 lesson_steps.py

Each STEP matches a step in shark-lesson.html and a function in ../make_stl.py.
"""
import math
import random

# ---------------------------------------------------------------- STEP 1
# A shape is a list of points. Moving a shape = adding to its numbers.
def move(shape, dx, dy):
    return [(x + dx, y + dy) for x, y in shape]


# ---------------------------------------------------------------- STEP 2
# Tile positions: i*v1 + j*v2 for whole numbers i and j.
def grid_positions(v1, v2, n1, n2):
    positions = []
    for i in range(n1):
        for j in range(n2):
            x = i * v1[0] + j * v2[0]
            y = i * v1[1] + j * v2[1]
            positions.append((x, y))
    return positions


# ---------------------------------------------------------------- STEP 3
# Turn a point half a turn around a centre c:   p_new = 2*c - p
def turn_180(point, centre):
    return (2 * centre[0] - point[0], 2 * centre[1] - point[1])


def turn_180_shape(shape, centre):
    return [turn_180(p, centre) for p in shape]


# ---------------------------------------------------------------- STEP 4
# Find an exact step from a rough guess by comparing every pair of points.
def all_differences(points):
    differences = []
    for a in points:
        for b in points:
            differences.append((b[0] - a[0], b[1] - a[1]))
    return differences


def distance(p, q):
    return math.hypot(p[0] - q[0], p[1] - q[1])          # sqrt(dx*dx + dy*dy)


def median(numbers):
    s = sorted(numbers)
    n = len(s)
    mid = n // 2
    return s[mid] if n % 2 else (s[mid - 1] + s[mid]) / 2


def refine_step(points, guess, tolerance=3.0, close=0.3):
    near = [d for d in all_differences(points) if distance(d, guess) < tolerance]
    if len(near) < 5:
        return guess                                       # not enough evidence
    mid = (median([d[0] for d in near]), median([d[1] for d in near]))
    good = [d for d in near if distance(d, mid) < close]
    if len(good) < 3:
        return mid
    return (sum(d[0] for d in good) / len(good), sum(d[1] for d in good) / len(good))


# ---------------------------------------------------------------- demo
if __name__ == "__main__":
    print("STEP 1: move a rectangle 10 to the right")
    rectangle = [(0, 0), (4, 0), (4, 3), (0, 3)]
    print("  ", move(rectangle, 10, 0))

    print("\nSTEP 2: positions of a 3 x 2 grid of tiles")
    for pos in grid_positions((10, 0), (3, 8), 3, 2):
        print("  tile at", pos)

    print("\nSTEP 3: turn (3, 2) half a turn around (1, 1)")
    new = turn_180((3, 2), (1, 1))
    print("  result", new, "   check: midpoint is",
          ((3 + new[0]) / 2, (2 + new[1]) / 2), "(should be (1.0, 1.0))")

    print("\nSTEP 4: recover the step (10, 4) from noisy points")
    random.seed(1)
    first = [(0, 0), (3, 1), (7, 2), (2, 6), (8, 7)]
    second = [(x + 10 + random.uniform(-0.1, 0.1), y + 4 + random.uniform(-0.1, 0.1)) for x, y in first]
    guess = (11.0, 3.2)
    found = refine_step(first + second, guess)
    print("  rough guess  ", guess)
    print("  refined step ", (round(found[0], 2), round(found[1], 2)), " (true step is (10, 4))")
