# -*- coding: utf-8 -*-
# =============================================================================
# hexgrid.py - finding the hexagon GRID of a map picture (shared code, future home: rail_core).
#
# EVERYTHING INSIDE THIS PROGRAM IS ENGLISH (code, comments) - rule 1.
#
# This is DEL 20 of Py\Hex_Labels.py (2026-11-15), copied VERBATIM on 2026-11-19 so the picture
# importer does not have to load the whole Hex_Labels window program.  Keep the two in sync
# (ToDo: make Hex_Labels import this file once rail_core exists).
# Needs: numpy.
# =============================================================================

import math
import numpy as np


# *************** DEL 20 - FINDING THE HEXAGON GRID *****************
# The grid is a lattice: centre(c, r2) = origin + c*P + r2*Q, valid when (c + r2) is even.
# Work happens in a FLAT-TOP "frame" (x along the columns c, y in half rows r2).  A
# pointy-top picture is the same thing turned 90 degrees (swap=True: picture (x, y) =
# frame (y, x)), so "line" = a column (flat-top) or a row (pointy-top).

def flood_region(arr, x, y, tol=24):
    """The plain-coloured area around (x, y).  Returns dict(bw, bh, bbox, count, mask,
    ox, oy) or None when the area leaks out (not a closed hexagon)."""
    h, w = arr.shape[:2]
    if not (0 <= x < w and 0 <= y < h):
        return None
    seed = arr[y, x].astype(np.int16)
    for R in (70, 160, 400):
        x0, y0 = max(0, x - R), max(0, y - R)
        x1, y1 = min(w, x + R + 1), min(h, y + R + 1)
        win = arr[y0:y1, x0:x1]
        sim = np.abs(win.astype(np.int16) - seed).max(axis=2) <= tol
        wh, ww = sim.shape
        pad = np.zeros((wh + 2, ww + 2), dtype=bool)
        pad[1:-1, 1:-1] = sim
        W2 = ww + 2
        flat = pad.ravel().tolist()
        start = (y - y0 + 1) * W2 + (x - x0 + 1)
        seen = bytearray(len(flat))
        seen[start] = 1
        stack = [start]
        cells = []
        while stack:
            i = stack.pop()
            cells.append(i)
            for j in (i + 1, i - 1, i + W2, i - W2):
                if flat[j] and not seen[j]:
                    seen[j] = 1
                    stack.append(j)
            if len(cells) > 60000:
                break
        idx = np.array(cells, dtype=np.int64)
        py, px = idx // W2 - 1, idx % W2 - 1
        bx0, bx1, by0, by1 = int(px.min()), int(px.max()), int(py.min()), int(py.max())
        touches = (bx0 == 0 and x0 > 0) or (by0 == 0 and y0 > 0) or \
                  (bx1 == ww - 1 and x1 < w) or (by1 == wh - 1 and y1 < h)
        if len(cells) > 60000 or touches:
            continue                        # leaked or cut by the window: bigger window
        mask = np.zeros((wh, ww), dtype=bool)
        mask[py, px] = True
        return dict(bw=bx1 - bx0 + 1, bh=by1 - by0 + 1, count=len(cells), mask=mask,
                    ox=x0, oy=y0,
                    bbox=(x0 + bx0, y0 + by0, x0 + bx1, y0 + by1))
    return None


def hex_shape_ok(reg):
    bw, bh = reg["bw"], reg["bh"]
    fill = reg["count"] / float(bw * bh)
    ratio = max(bw, bh) / float(min(bw, bh))
    return 0.62 <= fill <= 0.88 and 1.0 <= ratio <= 1.45 and min(bw, bh) >= 8


def border_colour(arr, reg):
    """Most common colour just outside the plain area = the hexagon border colour."""
    m = reg["mask"]
    d = m.copy()
    d[1:] |= m[:-1]
    d[:-1] |= m[1:]
    d[:, 1:] |= m[:, :-1]
    d[:, :-1] |= m[:, 1:]
    ring = d & ~m
    win = arr[reg["oy"]:reg["oy"] + m.shape[0], reg["ox"]:reg["ox"] + m.shape[1]]
    cols = win[ring]
    if len(cols) == 0:
        return None
    vals, counts = np.unique(cols, axis=0, return_counts=True)
    return tuple(int(v) for v in vals[int(np.argmax(counts))])


def make_mask(arr, colour, tol=40):
    d = np.abs(arr.astype(np.int16) - np.array(colour, dtype=np.int16)).max(axis=2)
    return d <= tol


def autocorr(mask):
    """Autocorrelation of the border mask (peaks at the lattice steps)."""
    m = mask.astype(np.float32)
    m -= m.mean()
    h, w = m.shape
    H, W = 2 * h, 2 * w
    f = np.fft.rfft2(m, s=(H, W))
    return np.fft.irfft2(f * np.conj(f), s=(H, W))


def refine_peak(ac, dx0, dy0, rad):
    H, W = ac.shape
    cx, cy = int(round(dx0)), int(round(dy0))
    best = None
    for dy in range(cy - rad, cy + rad + 1):
        for dx in range(cx - rad, cx + rad + 1):
            v = float(ac[dy % H, dx % W])
            if best is None or v > best[0]:
                best = (v, dx, dy)
    v, bx, by = best

    def par(vm, v0, vp):
        d = vm - 2 * v0 + vp
        return 0.0 if abs(d) < 1e-9 else 0.5 * (vm - vp) / d

    sx = par(float(ac[by % H, (bx - 1) % W]), v, float(ac[by % H, (bx + 1) % W]))
    sy = par(float(ac[(by - 1) % H, bx % W]), v, float(ac[(by + 1) % H, bx % W]))
    return bx + sx, by + sy


def bootstrap_vector(ac, vx, vy, limit_x, limit_y):
    """Refine a lattice step by looking at ever longer multiples of it (k = 2, 4, 8 ...):
    the error shrinks by the same factor."""
    ux, uy = refine_peak(ac, vx, vy, 3)
    k = 1
    while True:
        k2 = k * 2
        if abs(ux * k2) > limit_x or abs(uy * k2) > limit_y:
            break
        gx, gy = refine_peak(ac, ux * k2, uy * k2, 2)
        ux, uy = gx / k2, gy / k2
        k = k2
    return ux, uy


class Lattice(object):
    """centre(c, r2) = (ox, oy) + c*(px, pyx) + r2*(qx, qy) in the flat-top frame."""

    def __init__(self, ox, oy, px, pyx, qx, qy, swap):
        self.ox, self.oy = float(ox), float(oy)
        self.px, self.pyx, self.qx, self.qy = float(px), float(pyx), float(qx), float(qy)
        self.swap = bool(swap)
        self.a = math.hypot(self.px, self.pyx)          # distance between lines
        self.hh = 2.0 * math.hypot(self.qx, self.qy)     # hexagon size along the line
        self.ys = 0.57735 * self.a / max(1e-6, self.hh / 2.0)   # makes slightly stretched
        # hexagons behave like regular ones when looking for the nearest centre

    def to_dict(self):
        return dict(ox=self.ox, oy=self.oy, px=self.px, pyx=self.pyx,
                    qx=self.qx, qy=self.qy, swap=self.swap)

    @staticmethod
    def from_dict(d):
        return Lattice(d["ox"], d["oy"], d["px"], d["pyx"], d["qx"], d["qy"], d["swap"])

    def frame_pos(self, c, r2):
        return (self.ox + c * self.px + r2 * self.qx, self.oy + c * self.pyx + r2 * self.qy)

    def pos(self, c, r2):
        fx, fy = self.frame_pos(c, r2)
        return (fy, fx) if self.swap else (fx, fy)

    def real(self, x, y):
        fx, fy = (y, x) if self.swap else (x, y)
        dx, dy = fx - self.ox, fy - self.oy
        det = self.px * self.qy - self.qx * self.pyx
        return ((dx * self.qy - self.qx * dy) / det, (self.px * dy - self.pyx * dx) / det)

    def nearest(self, x, y):
        """(c, r2) of the hexagon whose centre is closest to the picture point."""
        fx, fy = (y, x) if self.swap else (x, y)
        cf, rf = self.real(x, y)
        best = None
        c0 = int(round(cf))
        for c in (c0 - 1, c0, c0 + 1):
            r = int(round(rf))
            for r2 in (r - 1, r, r + 1):
                if (r2 + c) % 2:
                    continue
                cx, cy = self.frame_pos(c, r2)
                d = (cx - fx) ** 2 + ((cy - fy) * self.ys) ** 2
                if best is None or d < best[0]:
                    best = (d, c, r2)
        return best[1], best[2]

    def hexes_in(self, x0, y0, x1, y1):
        """Every (c, r2, x, y) whose centre lies in the picture box."""
        cs, rs = [], []
        for (x, y) in ((x0, y0), (x1, y0), (x0, y1), (x1, y1)):
            cf, rf = self.real(x, y)
            cs.append(cf)
            rs.append(rf)
        out = []
        for c in range(int(math.floor(min(cs))) - 1, int(math.ceil(max(cs))) + 2):
            r_lo = int(math.floor(min(rs))) - 1
            if (r_lo + c) % 2:
                r_lo += 1
            for r2 in range(r_lo, int(math.ceil(max(rs))) + 2, 2):
                x, y = self.pos(c, r2)
                if x0 <= x <= x1 and y0 <= y <= y1:
                    out.append((c, r2, x, y))
        return out

    def pic_dims(self):
        """Hexagon size in the picture: (width, height), corner to corner / flat to flat."""
        v, f = 4.0 * self.a / 3.0, self.hh
        return (f, v) if self.swap else (v, f)

    def polygon_offsets(self):
        """The six corners relative to the centre, in PICTURE coordinates."""
        a, hh = self.a, self.hh
        fr = [(2 * a / 3, 0), (a / 3, hh / 2), (-a / 3, hh / 2),
              (-2 * a / 3, 0), (-a / 3, -hh / 2), (a / 3, -hh / 2)]
        return [(y, x) for (x, y) in fr] if self.swap else fr

    def recentred(self, w, h):
        """Same lattice, origin moved to the hexagon nearest the picture's top left corner,
        so the same grid always gets the same numbers whichever hexagon was marked."""
        c0, r0 = self.nearest(0, 0)
        fx, fy = self.frame_pos(c0, r0)
        return Lattice(fx, fy, self.px, self.pyx, self.qx, self.qy, self.swap)


def lattice_score(mask_f, lat):
    """Share of hexagons whose six edges are all (>=5 of 6) visible as border pixels.
    mask_f is the border mask in the FRAME (transposed for pointy-top)."""
    fh, fw = mask_f.shape
    m = mask_f.copy()
    m[1:] |= mask_f[:-1]
    m[:-1] |= mask_f[1:]
    m[:, 1:] |= mask_f[:, :-1]
    m[:, :-1] |= mask_f[:, 1:]
    flat = Lattice(lat.ox, lat.oy, lat.px, lat.pyx, lat.qx, lat.qy, False)
    a, hh = lat.a, lat.hh
    offs = [(0, hh / 2), (0, -hh / 2), (a / 2, hh / 4), (-a / 2, hh / 4),
            (a / 2, -hh / 4), (-a / 2, -hh / 4)]
    pts = []
    for (c, r2, x, y) in flat.hexes_in(a, hh, fw - a, fh - hh):
        pts.append([(x + ox, y + oy) for ox, oy in offs])
    if not pts:
        return 0.0
    p = np.array(pts)
    xi = np.clip(np.rint(p[:, :, 0]).astype(int), 0, fw - 1)
    yi = np.clip(np.rint(p[:, :, 1]).astype(int), 0, fh - 1)
    hit = m[yi, xi].sum(axis=1)
    return float((hit >= 5).mean())


def detect_lattice(arr, seed, log=None):
    """Find the hexagon grid from ONE plain hexagon at picture point `seed` (x, y).
    Returns (Lattice, info dict).  Raises ValueError with a message for the user."""
    log = log or (lambda s: None)
    if np is None:
        raise ValueError("numpy is not installed - type the grid in 'Grid settings...'.")
    h, w = arr.shape[:2]
    reg = flood_region(arr, int(seed[0]), int(seed[1]))
    if reg is None:
        raise ValueError("That spot is not inside one closed hexagon "
                         "(the plain colour runs out through the borders).")
    if not hex_shape_ok(reg):
        raise ValueError("That spot does not look like a plain hexagon (%d x %d px). "
                         "Pick an empty hexagon without a city or text." % (reg["bw"], reg["bh"]))
    x0, y0, x1, y1 = reg["bbox"]
    bw, bh = reg["bw"], reg["bh"]
    swap = bh > bw
    bcol = border_colour(arr, reg)
    if bcol is None:
        raise ValueError("No border line found around that hexagon.")
    mask = make_mask(arr, bcol)
    cx, cy = (x0 + x1) / 2.0, (y0 + y1) / 2.0
    if swap:
        mask = mask.T
        bw, bh = bh, bw
        cx, cy = cy, cx
    # keep the FFT small: a window of at most 1800 x 1800 px around the marked hexagon
    fh, fw = mask.shape
    wx0 = int(max(0, min(cx - 900, fw - 1800)))
    wy0 = int(max(0, min(cy - 900, fh - 1800)))
    sub = mask[wy0:wy0 + 1800, wx0:wx0 + 1800]
    ac = autocorr(sub)
    sh, sw = sub.shape
    Hh = bh + 1.0
    px_est = 0.75 * (bw + 2.0)
    vx, vy = bootstrap_vector(ac, 0.0, Hh, 0.5 * sw, 0.55 * sh)
    hx, hy = bootstrap_vector(ac, 2 * px_est, 0.0, 0.55 * sw, 0.5 * sh)
    log("lag along half-rows (%.3f, %.3f)  lag between same columns (%.3f, %.3f)" % (vx, vy, hx, hy))
    P = (hx / 2.0, hy / 2.0)
    Q = (vx / 2.0, vy / 2.0)
    dxv, dyv = refine_peak(ac, P[0] + Q[0], P[1] + Q[1], 3)
    err = max(abs(dxv - (P[0] + Q[0])), abs(dyv - (P[1] + Q[1])))
    if err > 1.6 or P[0] < 4 or Q[1] < 3:
        raise ValueError("The hexagon rows do not line up (check %.1f px). "
                         "Try another hexagon or type the grid by hand." % err)
    lat = Lattice(cx, cy, P[0], P[1], Q[0], Q[1], swap).recentred(w, h)
    score = lattice_score(mask, Lattice(lat.ox, lat.oy, lat.px, lat.pyx, lat.qx, lat.qy, swap))
    log("grid check %.0f %%" % (score * 100))
    if score < 0.03:
        raise ValueError("The grid found does not fit the picture (check %.0f %%)." % (score * 100))
    return lat, dict(score=score, border=bcol, hex_w=bw, hex_h=bh, err=err)


def auto_seed(arr, tries=160):
    """Look for a plain hexagon without help: spread test points over the picture, keep
    the ones that sit in a hexagon-shaped plain area and take the most common size."""
    if np is None:
        return None
    h, w = arr.shape[:2]
    found = []
    for i in range(tries):
        x = int(((i + 0.5) * 0.6180339887) % 1.0 * (w - 1))
        y = int(((i + 0.5) * 0.7548776662) % 1.0 * (h - 1))
        reg = flood_region(arr, x, y)
        if reg is None or not hex_shape_ok(reg):
            continue
        found.append((reg["bw"], reg["bh"], x, y))
        agree = [g for g in found if abs(g[0] - reg["bw"]) <= 1 and abs(g[1] - reg["bh"]) <= 1]
        if len(agree) >= 3:
            return (agree[0][2], agree[0][3])
    if found:
        best = max(found, key=lambda f: sum(1 for g in found if abs(g[0] - f[0]) <= 1 and abs(g[1] - f[1]) <= 1))
        return (best[2], best[3])
    return None

