#!/usr/bin/env python3
"""Generate mixel-free 1x 360-degree voxel turntable sprites for The Quiet Room Relay
(tending-a-room-of-agents) and verify 0/180 symmetry, border clearances, and height ratio.
"""

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_room_state(chatter_loop: bool) -> tuple[np.ndarray, dict[int, tuple[int, int, int, int]]]:
    vz, vy, vx = 96, 85, 85  # odd width guarantees 0/180 parity
    vox = np.zeros((vz, vy, vx), dtype=np.uint8)
    cx, cy = vx // 2, vy // 2

    # 1. Warm oak/stone floor plinth (z=6..12)
    vox[6:10, cy - 22 : cy + 23, cx - 28 : cx + 29] = 3
    vox[10:13, cy - 21 : cy + 22, cx - 27 : cx + 28] = 2

    # 2. Central router & silence bell arch (keeps bots + memory ledger connected cleanly)
    vox[13:62, cy - 3 : cy + 4, cx - 4 : cx + 5] = 4
    vox[62:67, cy - 4 : cy + 5, cx - 22 : cx + 23] = 5  # crossbar tying both bot terminals
    vox[67:84, cy - 5 : cy + 6, cx - 6 : cx + 7] = 6 if not chatter_loop else 8
    vox[84:90, cy - 3 : cy + 4, cx - 3 : cx + 4] = 7 if not chatter_loop else 9

    # 3. Left and right symmetric Bot terminals (Bot A & Bot B)
    for side in (-1, 1):
        bx = cx + side * 20
        vox[13:34, cy - 8 : cy + 9, bx - 7 : bx + 8] = 4   # desk pedestal
        vox[34:54, cy - 7 : cy + 8, bx - 6 : bx + 7] = 10  # monitor chassis
        screen_idx = 11 if not chatter_loop else 8
        inner_x = bx - side * 6
        x0, x1 = min(inner_x, bx - side * 5), max(inner_x, bx - side * 5) + 1
        vox[37:50, cy - 5 : cy + 6, x0:x1] = screen_idx
        # Overhead antenna strut linking to router crossbar
        vox[54:62, cy - 2 : cy + 3, bx - 2 : bx + 3] = 5
        if chatter_loop:
            # Red chatter loop beacons atop each bot
            vox[67:79, cy - 3 : cy + 4, bx - 3 : bx + 4] = 8

    # 4. Forward human provenance & durable memory desk (front-center)
    vox[13:26, cy + 10 : cy + 20, cx - 9 : cx + 10] = 3
    vox[26:32, cy + 12 : cy + 18, cx - 6 : cx + 7] = 12 if not chatter_loop else 8

    vox = prune_floating_islands_26(vox, keep_largest_n=1)

    palette = {
        0: (0, 0, 0, 0),
        1: (20, 20, 19, 255),      # #141413 ink outline
        2: (224, 214, 196, 255),   # warm stone floor top
        3: (168, 158, 142, 255),   # cool shadow stone edge
        4: (82, 86, 94, 255),      # slate steel chassis
        5: (122, 128, 138, 255),   # lit steel strut
        6: (61, 90, 108, 255),     # calm slate router core
        7: (116, 166, 138, 255),   # quiet gate verified teal lantern
        8: (186, 99, 72, 255),     # terracotta alert / chatter ping
        9: (224, 132, 92, 255),    # bright chatter flare
        10: (56, 58, 64, 255),     # terminal casing
        11: (94, 134, 122, 255),   # calm waiting terminal glow
        12: (76, 128, 98, 255),    # verified human-memory lock
    }
    return vox, palette


def audit_and_export() -> None:
    repo = Path(__file__).resolve().parents[3]
    out_int = repo / "public" / "interactive" / "agent-room"
    out_img = repo / "public" / "images" / "tending-a-room-of-agents"
    out_int.mkdir(parents=True, exist_ok=True)
    out_img.mkdir(parents=True, exist_ok=True)

    vox_calm, pal = build_room_state(chatter_loop=False)
    vox_chat, _ = build_room_state(chatter_loop=True)

    # Quantitative 8-yaw x 3-pitch gate check
    yaws = (0.0, 45.0, 90.0, 135.0, 180.0, 225.0, 270.0, 315.0)
    for fi, vox in enumerate((vox_calm, vox_chat)):
        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, 4: 10})
                ys, xs = np.where(idx > 0)
                assert ys.min() > 0 and ys.max() < 143 and xs.min() > 0 and xs.max() < 255, (
                    f"Clip on state={fi} yaw={yaw} pitch={pitch}: ({xs.min()},{ys.min()})..({xs.max()},{ys.max()})"
                )
                widths[yaw] = int(xs.max() - xs.min() + 1)
                ratios.append(float(ys.max() - ys.min() + 1) / 144.0)
            assert widths[0.0] == widths[180.0], f"0/180 symmetry break: {widths[0.0]} != {widths[180.0]}"
            mean_h = float(np.mean(ratios))
            if pitch == 28.0:
                assert 0.55 <= mean_h <= 0.80, f"Height {mean_h:.2%} out of [55%, 80%]"
                print(f"state={fi} pitch={pitch} height={mean_h:.1%} 0/180_w={widths[0.0]} OK")

    # Export 16-angle strips (4096x144) for mixel-free client canvas drag/scrub
    for name, vox in (("sprites-calm.png", vox_calm), ("sprites-chatter.png", vox_chat)):
        frames = [
            indexed_to_rgba(
                render_turntable_1x(vox, yaw_deg=i * 22.5, pitch_deg=28.0, crease_map={2: 3, 4: 10}),
                pal,
            )
            for i in range(16)
        ]
        strip = np.hstack(frames)
        Image.fromarray(strip, mode="RGBA").save(out_int / name, compress_level=6)

    # Static crisp 3x side-by-side comparison poster (calm vs chatter)
    p_calm = indexed_to_rgba(render_turntable_1x(vox_calm, yaw_deg=22.5, pitch_deg=28.0, crease_map={2: 3, 4: 10}), pal)
    p_chat = indexed_to_rgba(render_turntable_1x(vox_chat, yaw_deg=22.5, pitch_deg=28.0, crease_map={2: 3, 4: 10}), pal)
    def on_paper(rgba: np.ndarray) -> np.ndarray:
        bg = np.full((144, 256, 3), (250, 249, 245), dtype=np.uint8)
        m = rgba[:, :, 3:4] > 0
        return np.where(m, rgba[:, :, :3], bg)
    pair = np.hstack([on_paper(p_calm), np.full((144, 16, 3), (225, 222, 214), dtype=np.uint8), on_paper(p_chat)])
    poster = Image.fromarray(pair, mode="RGB").resize((pair.shape[1] * 3, pair.shape[0] * 3), Image.Resampling.NEAREST)
    poster.save(out_img / "quiet-room-poster.webp", format="WEBP", quality=92, method=6)
    print("Exported voxel strips and poster to", out_int, "and", out_img)


if __name__ == "__main__":
    audit_and_export()
