#!/usr/bin/env python3
"""Generate mixel-free 1x 360-degree voxel turntable sprites contrasting an
interlocked 'hard-to-vary' axial-tilt mechanism (Scores 4-5) against loose
interchangeable pegs ('goddess myth', Scores 1-3) for can-hard-to-vary-be-scored.
"""

from __future__ import annotations

import math
from pathlib import Path

import numpy as np
from PIL import Image
from scipy import ndimage


def prune_floating_islands_26(vox: np.ndarray, keep_largest_n: int = 1) -> np.ndarray:
    arr = np.asarray(vox, dtype=np.uint8)
    mask = arr > 0
    if not np.any(mask):
        return arr.copy()
    labeled, n_comp = ndimage.label(mask, structure=np.ones((3, 3, 3), dtype=np.int8))
    if n_comp <= keep_largest_n:
        return arr.copy()
    counts = np.bincount(labeled.ravel())
    counts[0] = 0
    keep = set(np.argsort(counts)[::-1][:keep_largest_n].tolist())
    return np.where(np.isin(labeled, list(keep)), arr, np.uint8(0))


def render_turntable_1x(
    vox: np.ndarray,
    yaw_deg: float = 35.0,
    pitch_deg: float = 28.0,
    canvas_w: int = 256,
    canvas_h: int = 144,
    py_c: float = 108.0,
    outline_idx: int = 1,
    crease_jump: float = 8.8,
    crease_map: dict[int, int] | None = None,
) -> np.ndarray:
    vox_z, vox_l, vox_w = vox.shape
    theta = math.radians(float(yaw_deg))
    pitch = math.radians(float(np.clip(pitch_deg, 10.0, 75.0)))
    cos_t, sin_t = math.cos(theta), math.sin(theta)
    y_scale = max(0.22, math.sin(pitch))
    z_scale = max(0.25, math.cos(pitch))

    px_c = (canvas_w // 2) + (0.5 if (vox_w % 2 == 1) else 0.0)
    substeps = max(2, int(math.ceil(z_scale / max(0.25, y_scale))))
    sy_grid, sx_grid = np.mgrid[0:canvas_h, 0:canvas_w].astype(np.float64)
    rx = (sx_grid + 0.5) - px_c

    idx_buf = np.zeros((canvas_h, canvas_w), dtype=np.uint8)
    depth_buf = np.full((canvas_h, canvas_w), -1e9, dtype=np.float64)

    for z in range(vox_z):
        layer = vox[z]
        if not np.any(layer):
            continue
        for s in range(substeps):
            z_eff = z + (s / float(substeps))
            ry = ((sy_grid + 0.5) - py_c + z_eff * z_scale) / y_scale
            ix = np.floor(rx * cos_t + ry * sin_t + vox_w * 0.5).astype(np.int32)
            iy = np.floor(-rx * sin_t + ry * cos_t + vox_l * 0.5).astype(np.int32)
            valid = (ix >= 0) & (ix < vox_w) & (iy >= 0) & (iy < vox_l)
            if not np.any(valid):
                continue
            sampled = np.zeros((canvas_h, canvas_w), dtype=np.uint8)
            sampled[valid] = layer[iy[valid], ix[valid]]
            hit = sampled > 0
            if not np.any(hit):
                continue
            depth = ry * math.cos(pitch) + z_eff * math.sin(pitch)
            closer = hit & (depth >= depth_buf)
            idx_buf[closer] = sampled[closer]
            depth_buf[closer] = depth[closer]

    body = idx_buf > 0
    if crease_map:
        max_nb = ndimage.maximum_filter(
            np.where(body, depth_buf, -1e9),
            footprint=np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=bool),
            mode="constant",
            cval=-1e9,
        )
        hits = body & ((max_nb - depth_buf) > crease_jump)
        for src_i, dark_i in crease_map.items():
            idx_buf[hits & (idx_buf == src_i)] = np.uint8(dark_i)

    if outline_idx > 0 and np.any(body):
        dilated = ndimage.binary_dilation(body, structure=np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=bool))
        idx_buf[dilated & (idx_buf == 0)] = np.uint8(outline_idx)
    return idx_buf


def indexed_to_rgba(idx_buf: np.ndarray, palette: dict[int, tuple[int, int, int, int]]) -> np.ndarray:
    out = np.zeros((*idx_buf.shape, 4), dtype=np.uint8)
    for idx, rgba in palette.items():
        out[idx_buf == idx] = rgba
    return out


def build_mechanism(tight: bool) -> tuple[np.ndarray, dict[int, tuple[int, int, int, int]]]:
    vz, vy, vx = 92, 85, 85
    vox = np.zeros((vz, vy, vx), dtype=np.uint8)
    cx, cy = vx // 2, vy // 2

    # Base plinth
    yy, xx = np.mgrid[0:vy, 0:vx]
    rr = np.sqrt((xx - cx) ** 2 + (yy - cy) ** 2)
    vox[6:10, rr <= 26] = 3
    vox[10:13, rr <= 25] = 2

    if tight:
        # Tall interlocked brass armillary/gimbal lock + tilted globe + calibrated jewel cap
        vox[13:26, cy - 4 : cy + 5, cx - 4 : cx + 5] = 4  # heavy base collar
        vox[26:34, cy - 2 : cy + 3, cx - 2 : cx + 3] = 5  # brass stem
        for a in np.linspace(0, 2 * math.pi, 180):
            # Primary vertical brass meridian ring (z centered at 51, radius 24 -> spans z 27..75)
            px = cx + int(round(24 * math.cos(a)))
            pz = 51 + int(round(24 * math.sin(a)))
            if 13 <= pz < vz - 3:
                vox[pz - 2 : pz + 3, cy - 2 : cy + 3, px - 2 : px + 3] = 5
            # Orthogonal meridian ring rotated in Y for symmetrical 3D cage silhouette
            py = cy + int(round(21 * math.cos(a)))
            pz_y = 51 + int(round(21 * math.sin(a)))
            if 13 <= pz_y < vz - 3:
                vox[pz_y - 1 : pz_y + 2, py - 1 : py + 2, cx - 1 : cx + 2] = 6
            # Oblique tilted ecliptic band (zero free parameters)
            px2 = cx + int(round(22 * math.cos(a)))
            py2 = cy + int(round(22 * math.sin(a)))
            pz2 = 51 + int(round(9.5 * math.cos(a)))
            vox[pz2 - 2 : pz2 + 2, py2 - 2 : py2 + 2, px2 - 2 : px2 + 2] = 6
        # Central locked globe & calibrated polar spindle
        zz, y2, x2 = np.mgrid[0:vz, 0:vy, 0:vx]
        sp = ((x2 - cx) ** 2 + (y2 - cy) ** 2 + (zz - 51) ** 2) <= 11.5 ** 2
        vox[sp] = 7
        vox[72:81, cy - 2 : cy + 3, cx - 2 : cx + 3] = 4  # north pole spindle
        vox[81:87, cy - 3 : cy + 4, cx - 3 : cx + 4] = 8  # calibrated lock seal
    else:
        # Loose uncoupled pillars ('free details'): interchangeable tall clay pegs of variable height
        vox[13:64, cy - 4 : cy + 5, cx - 4 : cx + 5] = 4
        vox[64:74, cy - 3 : cy + 4, cx - 3 : cx + 4] = 9
        for dx, dy, h_top in ((-14, 0, 56), (14, 0, 46), (0, -14, 52), (0, 14, 38)):
            vox[13:h_top, cy + dy - 4 : cy + dy + 5, cx + dx - 4 : cx + dx + 5] = 9
            vox[h_top : h_top + 6, cy + dy - 5 : cy + dy + 6, cx + dx - 5 : cx + dx + 6] = 10

    vox = prune_floating_islands_26(vox, keep_largest_n=1)
    palette = {
        0: (0, 0, 0, 0),
        1: (20, 20, 19, 255),
        2: (224, 214, 196, 255),
        3: (168, 158, 142, 255),
        4: (78, 84, 92, 255),
        5: (178, 134, 72, 255),
        6: (212, 168, 100, 255),
        7: (61, 90, 108, 255),
        8: (96, 152, 124, 255),
        9: (186, 99, 72, 255),
        10: (224, 132, 92, 255),
    }
    return vox, palette


def audit_and_export() -> None:
    repo = Path(__file__).resolve().parents[3]
    out_int = repo / "public" / "interactive" / "htv-rubric"
    out_img = repo / "public" / "images" / "can-hard-to-vary-be-scored"
    out_int.mkdir(parents=True, exist_ok=True)
    out_img.mkdir(parents=True, exist_ok=True)

    vox_tight, pal = build_mechanism(True)
    vox_free, _ = build_mechanism(False)

    yaws = (0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0)
    for fi, vox in enumerate((vox_tight, vox_free)):
        for pitch in (14.0, 28.0, 66.0):
            widths = {}
            ratios = []
            for yaw in yaws:
                idx = render_turntable_1x(vox, yaw_deg=yaw, pitch_deg=pitch, crease_map={2: 3, 5: 4})
                ys, xs = np.where(idx > 0)
                assert ys.min() > 0 and ys.max() < 143 and xs.min() > 0 and xs.max() < 255, f"Clip {fi} {yaw} {pitch}"
                widths[yaw] = int(xs.max() - xs.min() + 1)
                ratios.append(float(ys.max() - ys.min() + 1) / 144.0)
            if fi == 0:
                assert widths[0.0] == widths[180.0], f"Symmetry break {widths[0.0]} != {widths[180.0]}"
            if pitch == 28.0:
                print(f"htv state={fi} height={np.mean(ratios):.1%} 0/180={widths[0.0]}..{widths[180.0]} OK")

    for name, vox in (("sprites-tight.png", vox_tight), ("sprites-free.png", vox_free)):
        frames = [indexed_to_rgba(render_turntable_1x(vox, yaw_deg=i * 22.5, pitch_deg=28.0, crease_map={2: 3, 5: 4}), pal) for i in range(16)]
        Image.fromarray(np.hstack(frames), "RGBA").save(out_int / name, compress_level=6)

    def on_paper(vox):
        rgba = indexed_to_rgba(render_turntable_1x(vox, yaw_deg=22.5, pitch_deg=28.0, crease_map={2: 3, 5: 4}), pal)
        bg = np.full((144, 256, 3), (250, 249, 245), np.uint8)
        return np.where(rgba[:, :, 3:4] > 0, rgba[:, :, :3], bg)

    pair = np.hstack([on_paper(vox_tight), np.full((144, 16, 3), (225, 222, 214), np.uint8), on_paper(vox_free)])
    Image.fromarray(pair, "RGB").resize((pair.shape[1] * 3, pair.shape[0] * 3), Image.Resampling.NEAREST).save(
        out_img / "rubric-sieve-poster.webp", format="WEBP", quality=92, method=6
    )
    print("Exported htv-rubric voxel strips and poster")


if __name__ == "__main__":
    audit_and_export()
