#!/usr/bin/env python3
"""
Physically colored disk-resolved ray-traced renders of Vega (alpha Lyrae).
=========================================================================
Ray-traces the exact Roche equipotential surface Phi(x, y, z) = Phi_0, evaluates
Espinosa Lara & Rieutord (2011) gravity darkening T_eff(theta) and Milne-Eddington
wavelength-dependent gray radiative transfer I_lambda(T_eff, mu) across 380-780 nm,
convolves with CIE 1931 2-deg color matching functions (Wyman-Sloan-Shirley 2013
piecewise Gaussian fit), and converts XYZ -> linear sRGB -> sRGB gamma at matched
exposure across all viewing inclinations.

Pure Python + Pillow (zero numpy/scipy dependency).
Writes vega_disks.png in the same directory.
"""

from __future__ import annotations

import math
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

from roche_vega import (
    I_gray_lambda,
    omega_from_Om_ratio,
    roche_r,
    surface_point,
)


# ---------------------------------------------------------------------------
# 1. CIE 1931 2-deg color matching functions (Wyman, Sloan & Shirley 2013)
# ---------------------------------------------------------------------------
def cie_x_bar(lam_nm: float) -> float:
    t1 = (lam_nm - 442.0) * (0.0624 if lam_nm < 442.0 else 0.0374)
    t2 = (lam_nm - 599.8) * (0.0264 if lam_nm < 599.8 else 0.0323)
    t3 = (lam_nm - 501.1) * (0.0490 if lam_nm < 501.1 else 0.0382)
    return 0.362 * math.exp(-0.5 * t1 * t1) + 1.056 * math.exp(-0.5 * t2 * t2) - 0.065 * math.exp(-0.5 * t3 * t3)


def cie_y_bar(lam_nm: float) -> float:
    t1 = (lam_nm - 568.8) * (0.0213 if lam_nm < 568.8 else 0.0247)
    t2 = (lam_nm - 530.9) * (0.0613 if lam_nm < 530.9 else 0.0322)
    return 0.821 * math.exp(-0.5 * t1 * t1) + 0.286 * math.exp(-0.5 * t2 * t2)


def cie_z_bar(lam_nm: float) -> float:
    t1 = (lam_nm - 437.0) * (0.0845 if lam_nm < 437.0 else 0.0278)
    t2 = (lam_nm - 459.0) * (0.0385 if lam_nm < 459.0 else 0.0725)
    return 1.217 * math.exp(-0.5 * t1 * t1) + 0.681 * math.exp(-0.5 * t2 * t2)


LAMS_NM = [380.0 + 5.0 * i for i in range(81)]  # 380..780 nm in 5 nm steps
CMF = [(lam * 1e-9, cie_x_bar(lam), cie_y_bar(lam), cie_z_bar(lam)) for lam in LAMS_NM]


def xyz_from_T_mu(T_eff: float, mu: float) -> tuple[float, float, float]:
    """Integrate Milne-Eddington emergent spectrum through CIE 1931 2-deg CMFs."""
    X = Y = Z = 0.0
    for i, (lam_m, xb, yb, zb) in enumerate(CMF):
        w = 0.5 if (i == 0 or i == len(CMF) - 1) else 1.0
        I = I_gray_lambda(lam_m, T_eff, mu)
        X += w * I * xb
        Y += w * I * yb
        Z += w * I * zb
    return X * 5.0, Y * 5.0, Z * 5.0


def xyz_to_linear_srgb(X: float, Y: float, Z: float) -> tuple[float, float, float]:
    r = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z
    g = -0.9692660 * X + 1.8760108 * Y + 0.0415560 * Z
    b = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z
    return r, g, b


def srgb_gamma(c: float) -> float:
    if c <= 0.0:
        return 0.0
    if c >= 1.0:
        return 1.0
    if c <= 0.0031308:
        return 12.92 * c
    return 1.055 * (c ** (1.0 / 2.4)) - 0.055


def teff_colormap(T: float, T_lo: float = 7000.0, T_hi: float = 10100.0) -> tuple[int, int, int]:
    """Perceptually ordered thermal palette: amber (7,000 K) -> cream (9,100 K) -> ice blue (10,100 K)."""
    stops = [
        (0.00, (128, 38, 18)),
        (0.32, (214, 112, 40)),
        (0.60, (246, 202, 128)),
        (0.76, (245, 242, 236)),
        (0.90, (158, 208, 255)),
        (1.00, (72, 148, 255)),
    ]
    t = max(0.0, min(1.0, (T - T_lo) / (T_hi - T_lo)))
    for k in range(len(stops) - 1):
        t0, c0 = stops[k]
        t1, c1 = stops[k + 1]
        if t <= t1:
            f = (t - t0) / (t1 - t0) if t1 > t0 else 0.0
            return (
                int(round(c0[0] + f * (c1[0] - c0[0]))),
                int(round(c0[1] + f * (c1[1] - c0[1]))),
                int(round(c0[2] + f * (c1[2] - c0[2]))),
            )
    return stops[-1][1]


# ---------------------------------------------------------------------------
# 2. Precomputed lookup tables for fast exact ray-tracing
# ---------------------------------------------------------------------------
class SpectrumLUT:
    def __init__(self, T_min: float = 5500.0, T_max: float = 10500.0, nT: int = 51, nMu: int = 41):
        self.T_min = T_min
        self.T_max = T_max
        self.nT = nT
        self.nMu = nMu
        self.dT = (T_max - T_min) / (nT - 1)
        self.dMu = 1.0 / (nMu - 1)
        self.grid: list[list[tuple[float, float, float]]] = []
        for i in range(nT):
            T = T_min + i * self.dT
            row = []
            for j in range(nMu):
                mu = max(1e-4, j * self.dMu)
                row.append(xyz_from_T_mu(T, mu))
            self.grid.append(row)

    def lookup(self, T: float, mu: float) -> tuple[float, float, float]:
        u = max(0.0, min(self.nT - 1.000001, (T - self.T_min) / self.dT))
        v = max(0.0, min(self.nMu - 1.000001, mu / self.dMu))
        i0 = int(u)
        j0 = int(v)
        fu = u - i0
        fv = v - j0
        g = self.grid
        a = g[i0][j0]
        b = g[i0 + 1][j0]
        c = g[i0][j0 + 1]
        d = g[i0 + 1][j0 + 1]
        w00 = (1.0 - fu) * (1.0 - fv)
        w10 = fu * (1.0 - fv)
        w01 = (1.0 - fu) * fv
        w11 = fu * fv
        return (
            w00 * a[0] + w10 * b[0] + w01 * c[0] + w11 * d[0],
            w00 * a[1] + w10 * b[1] + w01 * c[1] + w11 * d[1],
            w00 * a[2] + w10 * b[2] + w01 * c[2] + w11 * d[2],
        )


class StarProfileLUT:
    """Tabulates ELR T_eff(theta) for a fixed rotation parameter w."""

    def __init__(self, w: float, T_pole: float, nTh: int = 512):
        self.w = w
        self.T_pole = T_pole
        self.nTh = nTh
        self.half_pi = 0.5 * math.pi
        self.dth = self.half_pi / (nTh - 1)
        self.T_arr = []
        for i in range(nTh):
            th = i * self.dth
            _, _, _, _, _, T_rel, _ = surface_point(th, w, model="elr")
            self.T_arr.append(T_pole * T_rel)

    def T_at_theta(self, theta: float) -> float:
        th = math.pi - theta if theta > self.half_pi else theta
        u = max(0.0, min(self.nTh - 1.000001, th / self.dth))
        i0 = int(u)
        f = u - i0
        return (1.0 - f) * self.T_arr[i0] + f * self.T_arr[i0 + 1]


# ---------------------------------------------------------------------------
# 3. Exact orthographic Roche ray tracer
# ---------------------------------------------------------------------------
def roche_phi_minus_surf(x: float, y: float, z: float, w2: float, phi_surf: float) -> float:
    """Signed Roche potential difference: negative inside the star, positive outside."""
    r = math.sqrt(x * x + y * y + z * z)
    if r < 1e-9:
        return -1e9
    return (-1.0 / r - 0.5 * w2 * (x * x + y * y)) - phi_surf


def trace_pixel(
    u: float,
    v: float,
    sin_i: float,
    cos_i: float,
    w2: float,
    phi_surf: float,
    star_lut: StarProfileLUT,
    spec_lut: SpectrumLUT,
) -> tuple[float, float, float, float, float] | None:
    """Orthographic ray trace at sky-plane (u, v) in units of R_e."""
    r2_sky = u * u + v * v
    if r2_sky > 1.002:
        return None
    s_max = math.sqrt(max(0.0, 1.004 - r2_sky))
    n_steps = 28
    ds = (2.0 * s_max) / n_steps
    s_prev = s_max
    x0 = u

    hit = False
    s_hi = s_prev
    s_lo = s_prev
    for k in range(1, n_steps + 1):
        s_cur = s_max - k * ds
        y = -v * cos_i + s_cur * sin_i
        z = v * sin_i + s_cur * cos_i
        if roche_phi_minus_surf(x0, y, z, w2, phi_surf) <= 0.0:
            s_hi = s_prev
            s_lo = s_cur
            hit = True
            break
        s_prev = s_cur

    if not hit:
        return None

    for _ in range(30):
        s_mid = 0.5 * (s_hi + s_lo)
        y = -v * cos_i + s_mid * sin_i
        z = v * sin_i + s_mid * cos_i
        if roche_phi_minus_surf(x0, y, z, w2, phi_surf) <= 0.0:
            s_lo = s_mid
        else:
            s_hi = s_mid

    s_hit = 0.5 * (s_hi + s_lo)
    x = x0
    y = -v * cos_i + s_hit * sin_i
    z = v * sin_i + s_hit * cos_i
    r2 = x * x + y * y + z * z
    r = math.sqrt(r2)
    inv_r3 = 1.0 / (r2 * r)
    nx = x * (inv_r3 - w2)
    ny = y * (inv_r3 - w2)
    nz = z * inv_r3
    n_norm = math.sqrt(nx * nx + ny * ny + nz * nz)
    nx /= n_norm
    ny /= n_norm
    nz /= n_norm
    mu = ny * sin_i + nz * cos_i
    if mu <= 0.0:
        return None
    theta = math.acos(max(-1.0, min(1.0, z / r)))
    T_eff = star_lut.T_at_theta(theta)
    X, Y, Z = spec_lut.lookup(T_eff, mu)
    return X, Y, Z, T_eff, mu


def render_disk(
    size: int,
    extent: float,
    inc_deg: float,
    w: float,
    T_pole: float,
    spec_lut: SpectrumLUT,
):
    """Render a (size x size) grid of raw linear XYZ values + T_eff map + diagnostics."""
    inc = math.radians(inc_deg)
    sin_i, cos_i = math.sin(inc), math.cos(inc)
    w2 = w * w
    phi_surf = -(1.0 + 0.5 * w2)
    star_lut = StarProfileLUT(w, T_pole)

    xyz_buf: list[tuple[float, float, float] | None] = [None] * (size * size)
    teff_buf: list[float] = [0.0] * (size * size)
    hit_mask = [False] * (size * size)
    max_rgb = 0.0
    total_X = total_Y = total_Z = 0.0
    center_info = None

    for py in range(size):
        v = extent * (1.0 - 2.0 * (py + 0.5) / size)
        row_off = py * size
        for px in range(size):
            u = extent * (2.0 * (px + 0.5) / size - 1.0)
            res = trace_pixel(u, v, sin_i, cos_i, w2, phi_surf, star_lut, spec_lut)
            if res is not None:
                X, Y, Z, T_eff, mu = res
                xyz_buf[row_off + px] = (X, Y, Z)
                teff_buf[row_off + px] = T_eff
                hit_mask[row_off + px] = True
                r, g, b = xyz_to_linear_srgb(X, Y, Z)
                m = max(r, g, b)
                if m > max_rgb:
                    max_rgb = m
                total_X += X
                total_Y += Y
                total_Z += Z
                if py == size // 2 and px == size // 2:
                    center_info = (T_eff, mu, X, Y, Z)

    pix_step = 2.0 * extent / size
    aa_buf: list[tuple[float, float, float]] = [(0.0, 0.0, 0.0)] * (size * size)
    aa_teff: list[tuple[float, float]] = [(0.0, 0.0)] * (size * size)
    for py in range(size):
        row_off = py * size
        v_c = extent * (1.0 - 2.0 * (py + 0.5) / size)
        for px in range(size):
            idx = row_off + px
            h = hit_mask[idx]
            boundary = False
            for dy in (-1, 0, 1):
                ny = py + dy
                if ny < 0 or ny >= size:
                    continue
                for dx in (-1, 0, 1):
                    nx = px + dx
                    if nx < 0 or nx >= size:
                        continue
                    if hit_mask[ny * size + nx] != h:
                        boundary = True
                        break
                if boundary:
                    break
            if boundary:
                u_c = extent * (2.0 * (px + 0.5) / size - 1.0)
                sX = sY = sZ = sT = 0.0
                hits = 0
                for sy in range(4):
                    vv = v_c + ((sy + 0.5) / 4.0 - 0.5) * pix_step
                    for sx in range(4):
                        uu = u_c + ((sx + 0.5) / 4.0 - 0.5) * pix_step
                        res = trace_pixel(uu, vv, sin_i, cos_i, w2, phi_surf, star_lut, spec_lut)
                        if res is not None:
                            sX += res[0]
                            sY += res[1]
                            sZ += res[2]
                            sT += res[3]
                            hits += 1
                aa_buf[idx] = (sX / 16.0, sY / 16.0, sZ / 16.0)
                aa_teff[idx] = (sT / hits if hits else 0.0, hits / 16.0)
            elif h:
                aa_buf[idx] = xyz_buf[idx]  # type: ignore[assignment]
                aa_teff[idx] = (teff_buf[idx], 1.0)

    T_eq = star_lut.T_at_theta(0.5 * math.pi)
    s_tot = total_X + total_Y + total_Z
    chrom = (total_X / s_tot, total_Y / s_tot) if s_tot > 0 else (0.0, 0.0)
    return {
        "buf": aa_buf,
        "teff": aa_teff,
        "max_rgb": max_rgb,
        "total_Y": total_Y,
        "chrom": chrom,
        "T_pole": T_pole,
        "T_eq": T_eq,
        "R_ratio": 1.0 / roche_r(0.0, w),
        "center": center_info,
    }


def load_font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
    candidates = (
        [
            "/usr/share/fonts/google-noto/NotoSans-Bold.ttf",
            "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans-Bold.ttf",
            "/usr/share/fonts/liberation-sans-fonts/LiberationSans-Bold.ttf",
        ]
        if bold
        else [
            "/usr/share/fonts/google-noto/NotoSans-Regular.ttf",
            "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf",
            "/usr/share/fonts/liberation-sans-fonts/LiberationSans-Regular.ttf",
        ]
    )
    for p in candidates:
        if Path(p).exists():
            return ImageFont.truetype(p, size)
    return ImageFont.load_default()


def main():
    spec_lut = SpectrumLUT(T_min=5500.0, T_max=10500.0, nT=51, nMu=41)

    w_vega = omega_from_Om_ratio(0.774)
    w_crit = omega_from_Om_ratio(0.990)
    T_pole = 10070.0

    panels = [
        ("Vega · Pole-on (Earth)", "i = 6.2°  ·  Ω/Ωc = 0.774", 6.2, w_vega),
        ("Vega · Magic Honest Angle", "i = 54.7°  ·  Ω/Ωc = 0.774", 54.74, w_vega),
        ("Vega · Equator-on", "i = 90.0°  ·  Ω/Ωc = 0.774", 90.0, w_vega),
        ("Extreme · 99% Breakup", "i = 90.0°  ·  Ω/Ωc = 0.990", 90.0, w_crit),
    ]

    disk_size = 340
    extent = 1.15
    renders = []
    for title, sub, inc_deg, w in panels:
        r = render_disk(disk_size, extent, inc_deg, w, T_pole, spec_lut)
        renders.append((title, sub, r))

    peak_ref = renders[0][2]["max_rgb"]
    exposure = 0.98 / peak_ref
    Y_ref = renders[0][2]["total_Y"]

    pad_x = 24
    gap_x = 18
    top_hdr = 78
    row_lbl_h = 28
    cap_h = 78
    cbar_h = 48
    footer_h = 34
    W = 2 * pad_x + 4 * disk_size + 3 * gap_x
    H = top_hdr + row_lbl_h + disk_size + cap_h + row_lbl_h + disk_size + cbar_h + footer_h

    BG = (8, 10, 15)
    CARD_BG = (3, 4, 7)
    BORDER = (34, 40, 56)
    FG = (232, 238, 248)
    MUTED = (148, 160, 182)
    ACCENT = (126, 186, 255)

    img = Image.new("RGB", (W, H), BG)
    draw = ImageDraw.Draw(img)

    f_title = load_font(22, bold=True)
    f_sub = load_font(13, bold=False)
    f_sec = load_font(13, bold=True)
    f_card = load_font(14, bold=True)
    f_meta = load_font(12, bold=False)

    draw.text((pad_x, 16), "Vega (α Lyrae): Disk-Resolved CIE 1931 sRGB Ray-Traced Renders", fill=FG, font=f_title)
    draw.text(
        (pad_x, 45),
        "Exact Roche equipotential + Espinosa Lara-Rieutord (2011) gravity darkening + Milne-Eddington gray RT (380-780 nm), matched exposure across all panels",
        fill=MUTED,
        font=f_sub,
    )

    row1_y = top_hdr
    draw.text(
        (pad_x, row1_y + 4),
        "TRUE EYE COLOR · Matched-exposure CIE 1931 to sRGB (D65 white point; Vega pole center peak linear channel = 0.98)",
        fill=ACCENT,
        font=f_sec,
    )
    disk_y1 = row1_y + row_lbl_h

    row2_y = disk_y1 + disk_size + cap_h
    draw.text(
        (pad_x, row2_y + 4),
        "SURFACE EFFECTIVE TEMPERATURE T_eff(theta) · Same Roche geometry (7,000 K amber equator to 10,070 K blue-white polar caps)",
        fill=ACCENT,
        font=f_sec,
    )
    disk_y2 = row2_y + row_lbl_h

    for idx, (title, sub, r) in enumerate(renders):
        x0 = pad_x + idx * (disk_size + gap_x)
        tile1 = Image.new("RGB", (disk_size, disk_size), CARD_BG)
        tile2 = Image.new("RGB", (disk_size, disk_size), CARD_BG)
        p1 = tile1.load()
        p2 = tile2.load()
        buf = r["buf"]
        tbuf = r["teff"]
        for py in range(disk_size):
            ro = py * disk_size
            for px in range(disk_size):
                X, Y, Z = buf[ro + px]
                if Y > 0.0:
                    lr, lg, lb = xyz_to_linear_srgb(X * exposure, Y * exposure, Z * exposure)
                    p1[px, py] = (
                        int(round(srgb_gamma(lr) * 255)),
                        int(round(srgb_gamma(lg) * 255)),
                        int(round(srgb_gamma(lb) * 255)),
                    )
                T_val, cov = tbuf[ro + px]
                if cov > 0.0:
                    tr, tg, tb = teff_colormap(T_val)
                    p2[px, py] = (
                        int(round(CARD_BG[0] * (1.0 - cov) + tr * cov)),
                        int(round(CARD_BG[1] * (1.0 - cov) + tg * cov)),
                        int(round(CARD_BG[2] * (1.0 - cov) + tb * cov)),
                    )

        img.paste(tile1, (x0, disk_y1))
        draw.rectangle([x0, disk_y1, x0 + disk_size - 1, disk_y1 + disk_size - 1], outline=BORDER, width=1)
        img.paste(tile2, (x0, disk_y2))
        draw.rectangle([x0, disk_y2, x0 + disk_size - 1, disk_y2 + disk_size - 1], outline=BORDER, width=1)

        dV = -2.5 * math.log10(r["total_Y"] / Y_ref)
        dV_str = "0.00 mag" if abs(dV) < 0.005 else f"{dV:+.2f} mag"
        cx, cy = r["chrom"]
        draw.text((x0 + 4, disk_y1 + disk_size + 8), title, fill=FG, font=f_card)
        draw.text(
            (x0 + 4, disk_y1 + disk_size + 28),
            f"{sub}  ·  Re/Rp = {r['R_ratio']:.3f}",
            fill=MUTED,
            font=f_meta,
        )
        draw.text(
            (x0 + 4, disk_y1 + disk_size + 45),
            f"Teq = {r['T_eq']:.0f} K  ·  ΔV = {dV_str}  ·  CIE ({cx:.3f}, {cy:.3f})",
            fill=MUTED,
            font=f_meta,
        )

    cb_w = 560
    cb_h = 12
    cb_x0 = (W - cb_w) // 2
    cb_y0 = disk_y2 + disk_size + 14
    for dx in range(cb_w):
        T_s = 7000.0 + (dx / (cb_w - 1)) * 3100.0
        draw.line([(cb_x0 + dx, cb_y0), (cb_x0 + dx, cb_y0 + cb_h)], fill=teff_colormap(T_s))
    draw.rectangle([cb_x0, cb_y0, cb_x0 + cb_w - 1, cb_y0 + cb_h], outline=BORDER, width=1)
    for tick_T in (7000, 7500, 8000, 8500, 9000, 9500, 10070):
        tx = cb_x0 + int(round((tick_T - 7000.0) / 3100.0 * (cb_w - 1)))
        draw.line([(tx, cb_y0 + cb_h), (tx, cb_y0 + cb_h + 4)], fill=MUTED)
        lbl = f"{tick_T:,} K"
        draw.text((tx - 20, cb_y0 + cb_h + 6), lbl, fill=MUTED, font=f_meta)

    draw.text(
        (pad_x, H - 24),
        "Tp = 10,070 K (Monnier et al. 2012) · North rotation axis points up · All panels share identical R_e angular scale and radiometric exposure.",
        fill=MUTED,
        font=f_meta,
    )

    out_path = Path(__file__).resolve().with_name("vega_disks.png")
    img.save(out_path, optimize=True)
    print(f"Wrote {out_path} ({W}x{H})")


if __name__ == "__main__":
    main()
