#!/usr/bin/env python3
"""
Vega (alpha Lyrae) and the Pole-on Calibration Mirage
=====================================================
First-principles Roche equipotential + gravity darkening (von Zeipel 1924 vs.
Espinosa Lara & Rieutord 2011) + Milne-Eddington wavelength-dependent gray
atmosphere integrator in pure Python (zero external dependencies).

Generates all numerical tables reported in notes.md and writes vega_figures.svg.
"""

from __future__ import annotations

import math
from pathlib import Path

# Physical constants (SI)
SIGMA_SB = 5.670374419e-8
H_PLANCK = 6.62607015e-34
C_LIGHT = 2.99792458e8
K_BOLTZ = 1.380649e-23
R_SUN = 6.957e8
L_SUN = 3.828e26
MAGIC_ANGLE_DEG = math.degrees(math.acos(1.0 / math.sqrt(3.0)))


# ---------------------------------------------------------------------------
# 1. Quadrature (Gauss-Laguerre for radiative transfer, Gauss-Legendre for phi)
# ---------------------------------------------------------------------------
def gauss_laguerre(n: int) -> tuple[list[float], list[float]]:
    def L_and_dL(x: float, order: int) -> tuple[float, float, float]:
        L0, L1 = 1.0, 1.0 - x
        for k in range(2, order + 1):
            L2 = ((2 * k - 1 - x) * L1 - (k - 1) * L0) / k
            L0, L1 = L1, L2
        dL = order * (L1 - L0) / x
        return L1, dL, L0

    nodes: list[float] = []
    weights: list[float] = []
    for i in range(1, n + 1):
        if i == 1:
            z = 3.0 / (1.0 + 2.4 * n)
        elif i == 2:
            z = nodes[-1] + 15.0 / (1.0 + 2.5 * n)
        else:
            ai = i - 2
            z = nodes[-1] + ((1.0 + 2.55 * ai) / (1.9 * ai)) * (nodes[-1] - nodes[-2])
        for _ in range(40):
            Ln, dLn, _ = L_and_dL(z, n)
            dz = Ln / dLn
            z -= dz
            if abs(dz) < 1e-14 * max(1.0, z):
                break
        w = z / (((n + 1) ** 2) * (L_and_dL(z, n + 1)[0] ** 2))
        nodes.append(z)
        weights.append(w)
    return nodes, weights


def gauss_legendre(n: int) -> tuple[list[float], list[float]]:
    nodes: list[float] = []
    weights: list[float] = []
    m = (n + 1) // 2
    for i in range(1, m + 1):
        x = math.cos(math.pi * (i - 0.25) / (n + 0.5))
        dp = 1.0
        for _ in range(30):
            p0, p1 = 1.0, x
            for k in range(2, n + 1):
                p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
            dp = n * (x * p1 - p0) / (x * x - 1.0)
            dx = p1 / dp
            x -= dx
            if abs(dx) < 1e-15:
                break
        w = 2.0 / ((1.0 - x * x) * dp * dp)
        nodes.append(-x)
        weights.append(w)
        if i != n + 1 - i:
            nodes.append(x)
            weights.append(w)
    pairs = sorted(zip(nodes, weights))
    return [p[0] for p in pairs], [p[1] for p in pairs]


GL_T, GL_W = gauss_laguerre(12)
GP_X, GP_W = gauss_legendre(12)


# ---------------------------------------------------------------------------
# 2. Roche Equipotential & Gravity Darkening (von Zeipel & ELR 2011)
# ---------------------------------------------------------------------------
def omega_from_Om_ratio(Om_over_Omc: float) -> float:
    """Invert Om/Om_c = w * (3 / (2 + w^2))^(3/2) for w = Om / Om_K(R_e) in [0, 1]."""
    if Om_over_Omc <= 0.0:
        return 0.0
    if Om_over_Omc >= 1.0:
        return 1.0
    lo, hi = 0.0, 1.0
    for _ in range(80):
        mid = 0.5 * (lo + hi)
        val = mid * (3.0 / (2.0 + mid * mid)) ** 1.5
        if val < Om_over_Omc:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def roche_r(theta: float, w: float) -> float:
    """Dimensionless radius r / R_e solving 1/(w^2 r) + (1/2) r^2 sin^2(theta) = 1/w^2 + 1/2."""
    if w == 0.0:
        return 1.0
    s = math.sin(theta)
    r_p = 2.0 / (2.0 + w * w)
    if s < 1e-12:
        return r_p
    r = r_p + (1.0 - r_p) * s * s
    c1 = 1.0 + 0.5 * w * w
    a = 0.5 * (w * s) ** 2
    for _ in range(30):
        f = a * r**3 - c1 * r + 1.0
        df = 3.0 * a * r**2 - c1
        step = f / df
        r -= step
        if abs(step) < 1e-15:
            break
    return r


def solve_vartheta(theta: float, r: float, w: float) -> float:
    """Solve Espinosa Lara & Rieutord (2011) Eq. (24) for flux streamline angle vartheta."""
    if w == 0.0:
        return theta
    south = theta > 0.5 * math.pi
    th = math.pi - theta if south else theta
    if th <= 1e-10:
        return math.pi if south else 0.0
    if th >= 0.5 * math.pi - 1e-10:
        return 0.5 * math.pi
    rhs = (
        (1.0 / 3.0) * (w**2) * (r**3) * (math.cos(th) ** 3)
        + math.cos(th)
        + math.log(math.tan(0.5 * th))
    )
    lo, hi = th, 0.5 * math.pi - 1e-15
    x = min(0.5 * (lo + hi), th + 0.05)
    for _ in range(60):
        fx = math.cos(x) + math.log(math.tan(0.5 * x)) - rhs
        if fx < 0.0:
            lo = x
        else:
            hi = x
        if abs(fx) < 1e-14 or (hi - lo) < 1e-14:
            break
        dfx = (math.cos(x) ** 2) / math.sin(x)
        xn = x - fx / max(dfx, 1e-15)
        x = 0.5 * (lo + hi) if (xn <= lo or xn >= hi) else xn
    return (math.pi - x) if south else x


def surface_point(theta: float, w: float, model: str = "elr", beta: float = 0.25):
    r = roche_r(theta, w)
    s, c = math.sin(theta), math.cos(theta)
    g_r = -1.0 / (r * r) + w * w * r * s * s
    g_th = w * w * r * s * c
    g_mag = math.hypot(g_r, g_th)
    n_r = -g_r / g_mag
    n_th = -g_th / g_mag
    n_rho = n_r * s + n_th * c
    n_z = n_r * c - n_th * s

    r_p = 2.0 / (2.0 + w * w)
    g_p = 1.0 / (r_p * r_p)

    if model == "elr":
        th_f = math.pi - theta if theta > 0.5 * math.pi else theta
        if th_f <= 1e-7:
            F_w = math.exp((2.0 / 3.0) * w * w * r**3)
        elif th_f >= 0.5 * math.pi - 1e-7:
            F_w = (1.0 - w * w * r**3) ** (-2.0 / 3.0)
        else:
            vt = solve_vartheta(th_f, r, w)
            F_w = (math.tan(vt) / math.tan(th_f)) ** 2
        F_w_p = math.exp((2.0 / 3.0) * w * w * r_p**3)
        F_rel = (F_w * g_mag) / (F_w_p * g_p)
        T_rel = F_rel**0.25
    elif model == "vz":
        T_rel = (g_mag / g_p) ** beta
        F_rel = T_rel**4
    elif model == "uniform":
        T_rel = 1.0
        F_rel = 1.0
    else:
        raise ValueError(f"Unknown model: {model}")

    return r, g_mag, n_r, n_rho, n_z, T_rel, F_rel


# ---------------------------------------------------------------------------
# 3. Radiative Transfer & Exact Axisymmetric Ring Integrals
# ---------------------------------------------------------------------------
def planck_lambda(lam_m: float, T: float) -> float:
    x = (H_PLANCK * C_LIGHT) / (lam_m * K_BOLTZ * T)
    if x > 700.0:
        return 0.0
    return (2.0 * H_PLANCK * C_LIGHT * C_LIGHT) / ((lam_m**5) * math.expm1(x))


def I_gray_lambda(lam_m: float, T_eff: float, mu: float) -> float:
    """Emergent intensity of a Milne-Eddington gray atmosphere T^4(tau) = 3/4 T_eff^4 (tau + 2/3)."""
    acc = 0.0
    for t, wt in zip(GL_T, GL_W):
        T_tau = T_eff * ((0.75 * (mu * t + 2.0 / 3.0)) ** 0.25)
        acc += wt * planck_lambda(lam_m, T_tau)
    return acc


def ring_visibility_moments(n_rho: float, n_z: float, inc: float, u: float = 0.0) -> float:
    """Exact analytic azimuthal integral int_{mu>0} mu * (1 - u + u*mu)/(1 - u/3) dphi."""
    A = n_z * math.cos(inc)
    B = n_rho * math.sin(inc)
    if B <= 1e-15:
        if A <= 0.0:
            return 0.0
        M1 = 2.0 * math.pi * A
        M2 = 2.0 * math.pi * A * A
    elif A >= B:
        M1 = 2.0 * math.pi * A
        M2 = 2.0 * math.pi * (A * A + 0.5 * B * B)
    elif A <= -B:
        return 0.0
    else:
        c0 = max(-1.0, min(1.0, -A / B))
        phi0 = math.acos(c0)
        s0 = math.sqrt(max(0.0, 1.0 - c0 * c0))
        M1 = 2.0 * (A * phi0 + B * s0)
        M2 = 2.0 * ((A * A + 0.5 * B * B) * phi0 + 1.5 * A * B * s0)
    return ((1.0 - u) * M1 + u * M2) / (1.0 - u / 3.0)


def build_star(
    w: float,
    R_e_rsun: float,
    T_pole: float,
    model: str = "elr",
    beta: float = 0.25,
    u: float = 0.6,
    N_th: int = 240,
):
    R_e = R_e_rsun * R_SUN
    dth = math.pi / N_th
    rings = []
    L_bol = 0.0
    area = 0.0
    for k in range(N_th):
        th = (k + 0.5) * dth
        r, g_mag, n_r, n_rho, n_z, T_rel, _ = surface_point(th, w, model=model, beta=beta)
        dA_dphi = (R_e**2) * (r * r) * math.sin(th) / n_r * dth
        T = T_pole * T_rel
        F = SIGMA_SB * (T**4)
        L_bol += 2.0 * math.pi * dA_dphi * F
        area += 2.0 * math.pi * dA_dphi
        rings.append((th, r, n_r, n_rho, n_z, dA_dphi, T, F))

    def L_app(inc_deg: float) -> float:
        inc = math.radians(inc_deg)
        tot = 0.0
        for (_, _, _, n_rho, n_z, dA_dphi, _, F) in rings:
            tot += F * dA_dphi * ring_visibility_moments(n_rho, n_z, inc, u=u)
        return 4.0 * tot

    return L_bol, area, rings, L_app


def monochromatic_flux(rings, lam_m: float, inc_deg: float, gray_atm: bool = True) -> float:
    inc = math.radians(inc_deg)
    ci, si = math.cos(inc), math.sin(inc)
    tot = 0.0
    if not gray_atm:
        for (_, _, _, n_rho, n_z, dA_dphi, T, _) in rings:
            tot += dA_dphi * planck_lambda(lam_m, T) * ring_visibility_moments(n_rho, n_z, inc, u=0.0)
        return 4.0 * tot
    for (_, _, _, n_rho, n_z, dA_dphi, T, _) in rings:
        A = n_z * ci
        B = n_rho * si
        if A <= -B:
            continue
        phi0 = math.pi if (B <= 1e-15 or A >= B) else math.acos(max(-1.0, min(1.0, -A / B)))
        ring_acc = 0.0
        half = 0.5 * phi0
        for gx, gw in zip(GP_X, GP_W):
            phi = half * (gx + 1.0)
            mu = A + B * math.cos(phi)
            if mu > 0.0:
                ring_acc += gw * mu * I_gray_lambda(lam_m, T, mu)
        tot += dA_dphi * (2.0 * half * ring_acc)
    return 4.0 * math.pi * tot


def spherical_flux(lam_m: float, T_eff: float, R_rsun: float, gray_atm: bool = True) -> float:
    R = R_rsun * R_SUN
    if not gray_atm:
        return 4.0 * (math.pi**2) * (R**2) * planck_lambda(lam_m, T_eff)
    acc = 0.0
    for gx, gw in zip(GP_X, GP_W):
        mu = 0.5 * (gx + 1.0)
        acc += 0.5 * gw * mu * I_gray_lambda(lam_m, T_eff, mu)
    return 8.0 * (math.pi**2) * (R**2) * acc


def fit_single_T(rings, inc_deg: float, opt_lams_nm: list[int], gray_atm: bool = True):
    true_vals = [monochromatic_flux(rings, nm * 1e-9, inc_deg, gray_atm=gray_atm) for nm in opt_lams_nm]

    def loss(T: float) -> tuple[float, float]:
        ratios = [
            math.log(tv / spherical_flux(nm * 1e-9, T, 1.0, gray_atm=gray_atm))
            for tv, nm in zip(true_vals, opt_lams_nm)
        ]
        ml = sum(ratios) / len(ratios)
        return sum((r - ml) ** 2 for r in ratios), math.exp(0.5 * ml)

    a, b = 6000.0, 12000.0
    gr = (math.sqrt(5.0) - 1.0) / 2.0
    c, d = b - gr * (b - a), a + gr * (b - a)
    fc, _ = loss(c)
    fd, _ = loss(d)
    for _ in range(55):
        if fc < fd:
            b, d, fd = d, c, fc
            c = b - gr * (b - a)
            fc, _ = loss(c)
        else:
            a, c, fc = c, d, fd
            d = a + gr * (b - a)
            fd, _ = loss(d)
    Tb = 0.5 * (a + b)
    _, Rb = loss(Tb)
    return Tb, Rb


# ---------------------------------------------------------------------------
# 4. Gulliver-Hill-Adelman (1994) Spectral Line Profile Simulator
# ---------------------------------------------------------------------------
def saha_FeI_weight(T: float) -> float:
    kT_eV = 8.617333262e-5 * T
    return (T**-2.5) * math.exp(7.902 / kT_eV)


def boltzmann_HeI_weight(T: float) -> float:
    kT_eV = 8.617333262e-5 * T
    return math.exp(-20.96 / kT_eV)


def compute_line_profile(
    rings, inc_deg: float, v_eq_kms: float, lam_m: float, weight_fn, v_grid: list[float], sigma_th: float = 2.0
):
    inc = math.radians(inc_deg)
    ci, si = math.cos(inc), math.sin(inc)
    N_phi = 240
    dphi = 2.0 * math.pi / N_phi
    prof = [0.0] * len(v_grid)
    inv_2s2 = 0.5 / (sigma_th * sigma_th)
    norm_g = 1.0 / (math.sqrt(2.0 * math.pi) * sigma_th)
    u_v = 0.42

    for (th, r, _, n_rho, n_z, dA_dphi, T, _) in rings:
        A = n_z * ci
        B = n_rho * si
        if A <= -B:
            continue
        w_T = weight_fn(T)
        v_ring_sini = v_eq_kms * r * math.sin(th) * si
        B_cont = planck_lambda(lam_m, T)
        for m in range(N_phi):
            phi = (m + 0.5) * dphi
            mu = A + B * math.cos(phi)
            if mu <= 0.0:
                continue
            I_c = B_cont * (1.0 - u_v * (1.0 - mu))
            w_line = dA_dphi * dphi * mu * I_c * w_T
            v_los = v_ring_sini * math.sin(phi)
            for idx, vg in enumerate(v_grid):
                dv = vg - v_los
                if abs(dv) < 5.0 * sigma_th:
                    prof[idx] += w_line * norm_g * math.exp(-dv * dv * inv_2s2)

    dv_step = v_grid[1] - v_grid[0]
    ew = sum(prof) * dv_step
    return [val / ew for val in prof]


# ---------------------------------------------------------------------------
# 5. SVG Figure Generator (3-panel clean visual summary)
# ---------------------------------------------------------------------------
def write_svg(out_path: Path, w_mon: float, Lb_mon: float, Lfn_mon, c2_mon: float, v_grid, p_unif, p_fe1, p_he1, p_fe1_auf):
    # Panel 1 (left): Meridional cross-section of Vega (Om/Omc=0.774) vs Sphere vs Breakup (1.0)
    # Panel 2 (middle): L_app(i)/L_bol vs inclination i (exact vs pure P2)
    # Panel 3 (right): Normalized absorption line profiles (Fe I vs Uniform vs He I vs Auf06 Fe I)
    W, H = 1080, 380

    def poly_roche(w: float, cx: float, cy: float, scale: float, n: int = 180) -> str:
        pts = []
        # Scale so polar radius is fixed at R_p_px = scale (shows centrifugal equatorial bulge!)
        r_p = 2.0 / (2.0 + w * w)
        for k in range(n + 1):
            ang = 2.0 * math.pi * k / n
            th = ang if ang <= math.pi else 2.0 * math.pi - ang
            r_norm = roche_r(th, w) / r_p  # in units of R_pole
            x = cx + scale * r_norm * math.sin(ang)
            y = cy - scale * r_norm * math.cos(ang)
            pts.append(f"{x:.1f},{y:.1f}")
        return " ".join(pts)

    # Panel 1 coords
    p1_cx, p1_cy, p1_rp = 175.0, 195.0, 86.0
    pts_sphere = poly_roche(0.0, p1_cx, p1_cy, p1_rp)
    pts_vega = poly_roche(w_mon, p1_cx, p1_cy, p1_rp)
    pts_crit = poly_roche(0.999, p1_cx, p1_cy, p1_rp)

    # Panel 2 coords: x in [390, 690] -> i in [0, 90], y in [65, 305] -> L_app/L_bol in [0.85, 1.25]
    p2_x0, p2_x1, p2_y0, p2_y1 = 400.0, 695.0, 60.0, 305.0
    def p2_xy(inc_deg: float, ratio: float) -> tuple[float, float]:
        x = p2_x0 + (inc_deg / 90.0) * (p2_x1 - p2_x0)
        y = p2_y1 - ((ratio - 0.85) / 0.40) * (p2_y1 - p2_y0)
        return x, y

    curve_exact = []
    curve_p2 = []
    for inc in range(0, 91, 2):
        r_ex = Lfn_mon(float(inc)) / Lb_mon
        mu = math.cos(math.radians(inc))
        r_p2 = 1.0 + c2_mon * 0.5 * (3 * mu * mu - 1.0)
        x, y = p2_xy(inc, r_ex)
        curve_exact.append(f"{x:.1f},{y:.1f}")
        x2, y2 = p2_xy(inc, r_p2)
        curve_p2.append(f"{x2:.1f},{y2:.1f}")

    x_earth, y_earth = p2_xy(6.2, Lfn_mon(6.2) / Lb_mon)
    x_magic, y_magic = p2_xy(MAGIC_ANGLE_DEG, 1.0)
    x_eq, y_eq = p2_xy(90.0, Lfn_mon(90.0) / Lb_mon)
    _, y_one = p2_xy(0.0, 1.0)

    # Panel 3 coords: x in [765, 1055] -> v in [-26, 26], y in [60, 305] -> absorption depth 0..1.05
    p3_x0, p3_x1, p3_y0, p3_y1 = 765.0, 1055.0, 60.0, 305.0
    def line_pts(prof: list[float]) -> str:
        pk = max(prof)
        pts = []
        for v, val in zip(v_grid, prof):
            if -26 <= v <= 26:
                x = p3_x0 + ((v + 26.0) / 52.0) * (p3_x1 - p3_x0)
                # Absorption line hangs downward from continuum y = p3_y0 + 18
                y = (p3_y0 + 18.0) + (val / pk) * (p3_y1 - p3_y0 - 32.0)
                pts.append(f"{x:.1f},{y:.1f}")
        return " ".join(pts)

    s_unif = line_pts(p_unif)
    s_fe1 = line_pts(p_fe1)
    s_he1 = line_pts(p_he1)
    s_auf = line_pts(p_fe1_auf)

    svg = f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" font-family="ui-sans-serif, system-ui, sans-serif">
  <defs>
    <radialGradient id="vegaGrad" cx="50%" cy="50%" r="55%" fx="50%" fy="15%">
      <stop offset="0%" stop-color="#dbeafe"/>
      <stop offset="55%" stop-color="#93c5fd"/>
      <stop offset="100%" stop-color="#f59e0b" stop-opacity="0.75"/>
    </radialGradient>
  </defs>
  <rect width="{W}" height="{H}" fill="#0f172a"/>

  <!-- Title -->
  <text x="24" y="30" fill="#f8fafc" font-size="16" font-weight="700">Vega (α Lyrae): Roche Shape, Quadrupole Luminosity Bias, and Flat-Bottomed Line Split</text>

  <!-- PANEL 1: Roche Cross-Section -->
  <text x="{p1_cx}" y="55" fill="#cbd5e1" font-size="12.5" font-weight="600" text-anchor="middle">1. Meridional Roche Profile (fixed R_pole)</text>
  <polygon points="{pts_crit}" fill="none" stroke="#475569" stroke-width="1.2" stroke-dasharray="4,4"/>
  <polygon points="{pts_vega}" fill="url(#vegaGrad)" fill-opacity="0.35" stroke="#60a5fa" stroke-width="2.2"/>
  <polygon points="{pts_sphere}" fill="none" stroke="#94a3b8" stroke-width="1.2" stroke-dasharray="2,3"/>
  <!-- Spin axis & Earth line of sight (6.2 deg) -->
  <line x1="{p1_cx}" y1="74" x2="{p1_cx}" y2="316" stroke="#64748b" stroke-width="1" stroke-dasharray="3,3"/>
  <line x1="{p1_cx}" y1="{p1_cy}" x2="{p1_cx + 125*math.sin(math.radians(6.2)):.1f}" y2="{p1_cy - 125*math.cos(math.radians(6.2)):.1f}" stroke="#38bdf8" stroke-width="1.8"/>
  <text x="{p1_cx + 20}" y="82" fill="#38bdf8" font-size="11">Earth (i = 6.2°)</text>
  <text x="{p1_cx}" y="102" fill="#e0f2fe" font-size="11" text-anchor="middle">Pole: 10,070 K</text>
  <text x="{p1_cx + 102}" y="{p1_cy + 14}" fill="#fbbf24" font-size="11">Eq: 8,984 K</text>
  <text x="32" y="336" fill="#94a3b8" font-size="10.5">Solid blue: Vega (Ω/Ω_c = 0.774, R_e/R_p = 1.127)</text>
  <text x="32" y="352" fill="#64748b" font-size="10.5">Outer dash: breakup limit (R_e/R_p = 1.500); Inner dot: sphere</text>

  <!-- PANEL 2: L_app(i) / L_bol -->
  <text x="{0.5*(p2_x0+p2_x1):.1f}" y="50" fill="#cbd5e1" font-size="12.5" font-weight="600" text-anchor="middle">2. Apparent Luminosity Bias vs. Viewing Angle i</text>
  <rect x="{p2_x0}" y="{p2_y0}" width="{p2_x1-p2_x0}" height="{p2_y1-p2_y0}" fill="#1e293b" stroke="#334155"/>
  <line x1="{p2_x0}" y1="{y_one:.1f}" x2="{p2_x1}" y2="{y_one:.1f}" stroke="#475569" stroke-dasharray="4,4"/>
  <line x1="{x_magic:.1f}" y1="{p2_y0}" x2="{x_magic:.1f}" y2="{p2_y1}" stroke="#475569" stroke-dasharray="3,4"/>
  <polyline points="{' '.join(curve_exact)}" fill="none" stroke="#38bdf8" stroke-width="2.5"/>
  <polyline points="{' '.join(curve_p2)}" fill="none" stroke="#f472b6" stroke-width="1.3" stroke-dasharray="4,3"/>
  <circle cx="{x_earth:.1f}" cy="{y_earth:.1f}" r="4.5" fill="#38bdf8"/>
  <circle cx="{x_magic:.1f}" cy="{y_magic:.1f}" r="4.5" fill="#a78bfa"/>
  <circle cx="{x_eq:.1f}" cy="{y_eq:.1f}" r="4.5" fill="#fbbf24"/>
  <text x="{x_earth + 8:.1f}" y="{y_earth + 4:.1f}" fill="#38bdf8" font-size="10.5">Earth 6.2° (+21.3%, V=+0.03)</text>
  <text x="{x_magic - 4:.1f}" y="{y_magic - 10:.1f}" fill="#c4b5fd" font-size="10.5" text-anchor="end">i* = 54.75° (honest)</text>
  <text x="{x_eq - 6:.1f}" y="{y_eq - 9:.1f}" fill="#fbbf24" font-size="10.5" text-anchor="end">Eq 90° (-10.9%, V=+0.30)</text>
  <!-- Axis labels -->
  <text x="{p2_x0 - 6}" y="{p2_y0 + 5}" fill="#94a3b8" font-size="10" text-anchor="end">1.25</text>
  <text x="{p2_x0 - 6}" y="{y_one + 4:.1f}" fill="#94a3b8" font-size="10" text-anchor="end">1.00</text>
  <text x="{p2_x0 - 6}" y="{p2_y1}" fill="#94a3b8" font-size="10" text-anchor="end">0.85</text>
  <text x="{p2_x0}" y="{p2_y1 + 16}" fill="#94a3b8" font-size="10" text-anchor="middle">0°</text>
  <text x="{0.5*(p2_x0+p2_x1):.1f}" y="{p2_y1 + 16}" fill="#94a3b8" font-size="10" text-anchor="middle">45° (inclination i)</text>
  <text x="{p2_x1}" y="{p2_y1 + 16}" fill="#94a3b8" font-size="10" text-anchor="middle">90°</text>
  <text x="{p2_x0}" y="352" fill="#94a3b8" font-size="10.5">Blue: exact ELR+LD | Pink dash: 1 + c₂P₂(cos i) (99.7% fit)</text>

  <!-- PANEL 3: Spectral Line Profiles -->
  <text x="{0.5*(p3_x0+p3_x1):.1f}" y="50" fill="#cbd5e1" font-size="12.5" font-weight="600" text-anchor="middle">3. Weak Absorption Line Profiles (i = 6.2°)</text>
  <rect x="{p3_x0}" y="{p3_y0}" width="{p3_x1-p3_x0}" height="{p3_y1-p3_y0}" fill="#1e293b" stroke="#334155"/>
  <line x1="{p3_x0}" y1="{p3_y0+18}" x2="{p3_x1}" y2="{p3_y0+18}" stroke="#475569" stroke-dasharray="3,3"/>
  <polyline points="{s_unif}" fill="none" stroke="#94a3b8" stroke-width="1.6" stroke-dasharray="4,3"/>
  <polyline points="{s_he1}" fill="none" stroke="#38bdf8" stroke-width="2.2"/>
  <polyline points="{s_fe1}" fill="none" stroke="#fbbf24" stroke-width="2.4"/>
  <polyline points="{s_auf}" fill="none" stroke="#f87171" stroke-width="1.6" stroke-dasharray="2,2"/>
  <text x="{p3_x0}" y="{p3_y1 + 16}" fill="#94a3b8" font-size="10" text-anchor="middle">-26</text>
  <text x="{0.5*(p3_x0+p3_x1):.1f}" y="{p3_y1 + 16}" fill="#94a3b8" font-size="10" text-anchor="middle">0 (Δv km/s)</text>
  <text x="{p3_x1}" y="{p3_y1 + 16}" fill="#94a3b8" font-size="10" text-anchor="middle">+26</text>
  <!-- Legend -->
  <text x="{p3_x0 + 6}" y="338" fill="#38bdf8" font-size="10.5">He I (hot pole, FWHM 20 km/s)</text>
  <text x="{p3_x0 + 6}" y="354" fill="#fbbf24" font-size="10.5">Fe I (cool eq, flat-bottomed 38 km/s) | Red: Ω=0.916</text>
</svg>
'''
    out_path.write_text(svg, encoding="utf-8")


def main() -> None:
    w_mon = omega_from_Om_ratio(0.774)
    w_auf = omega_from_Om_ratio(0.916)
    w_ext = omega_from_Om_ratio(0.990)

    print("=== 1. ELR (2011) vs. von Zeipel (beta=0.25) across rotation rates ===")
    print(f"{'Om/Omc':>7} {'w':>7} {'Re/Rp':>7} {'v/vc':>7} {'Teq/Tp(vZ)':>11} {'Teq/Tp(ELR)':>12} {'beta_eff':>10}")
    for Om_c in [0.01, 0.30, 0.50, 0.70, 0.774, 0.86, 0.916, 0.95, 0.99, 0.999]:
        w = omega_from_Om_ratio(Om_c)
        _, gp, *_ = surface_point(0.0, w, "elr")
        _, ge, *_, t_elr, _ = surface_point(0.5 * math.pi, w, "elr")
        *_, t_vz, _ = surface_point(0.5 * math.pi, w, "vz", beta=0.25)
        re_rp = 1.0 + 0.5 * w * w
        v_vc = w * math.sqrt(3.0 / (2.0 + w * w))
        beta_eff = math.log(t_elr) / math.log(ge / gp)
        print(f"{Om_c:7.3f} {w:7.4f} {re_rp:7.4f} {v_vc:7.4f} {t_vz:11.5f} {t_elr:12.5f} {beta_eff:10.5f}")

    # 2. Monnier Model 3 vs ELR conservation & quadrupole lock
    Lb_elr, area_elr, rings_elr, Lfn_elr = build_star(w_mon, 2.726, 10070.0, model="elr", u=0.6, N_th=240)
    Lb_m3, area_m3, rings_m3, Lfn_m3 = build_star(w_mon, 2.726, 10070.0, model="vz", beta=0.231, u=0.6, N_th=240)
    _, _, rings_auf, _ = build_star(w_auf, 2.818, 10150.0, model="elr", u=0.6, N_th=160)

    N_i = 180
    di = 0.5 * math.pi / N_i
    sky_avg = sum(Lfn_elr(math.degrees((j + 0.5) * di)) * math.sin((j + 0.5) * di) * di for j in range(N_i))
    print(f"\n=== 2. Vega Conservation Check (ELR, Om/Omc=0.774, u=0.6) ===")
    print(f"L_bol      = {Lb_elr/L_SUN:.2f} Lsun (M3 beta=0.231: {Lb_m3/L_SUN:.2f}, Monnier 2012: 47.2 ± 2.0)")
    print(f"L_sky_avg  = {sky_avg/L_SUN:.2f} Lsun (rel err = {(sky_avg - Lb_elr)/Lb_elr:+.2e})")
    print(f"L_app(6.2) = {Lfn_elr(6.2)/L_SUN:.2f} Lsun (ratio = {Lfn_elr(6.2)/Lb_elr:.4f}; Monnier: 58.4 ± 2.2)")
    print(f"L_app(90)  = {Lfn_elr(90.0)/L_SUN:.2f} Lsun (ratio = {Lfn_elr(90.0)/Lb_elr:.4f})")

    # Legendre c2, c4
    def P2(x: float) -> float: return 0.5 * (3 * x * x - 1.0)
    def P4(x: float) -> float: return 0.125 * (35 * x**4 - 30 * x * x + 3.0)
    N_mu = 120
    c2 = sum(5.0 * (Lfn_elr(math.degrees(math.acos((j + 0.5) / N_mu))) / Lb_elr) * P2((j + 0.5) / N_mu) / N_mu for j in range(N_mu))
    c4 = sum(9.0 * (Lfn_elr(math.degrees(math.acos((j + 0.5) / N_mu))) / Lb_elr) * P4((j + 0.5) / N_mu) / N_mu for j in range(N_mu))
    print(f"Legendre harmonics: c2 = {c2:+.5f}, c4 = {c4:+.6f} (|c4/c2| = {abs(c4/c2):.4f})")

    # 3. 3-way brightening decomposition & honest angle i*
    def find_honest_angle(L_bol: float, Lfn) -> float:
        lo, hi = 0.0, 90.0
        for _ in range(50):
            mid = 0.5 * (lo + hi)
            if Lfn(mid) > L_bol:
                lo = mid
            else:
                hi = mid
        return 0.5 * (lo + hi)

    print("\n=== 3. 3-Way Brightening Decomposition & Honest Angle i* ===")
    print(f"{'Case':28s} {'L(0)/Lb':>8} {'L(90)/Lb':>9} {'dMag(90-0)':>11} {'i_honest':>9} {'i*-54.74':>9}")
    for label, w, mod, beta, u in [
        ("Vega M3: Geom only (u=0)", w_mon, "uniform", 0.0, 0.0),
        ("Vega M3: Geom + LD (u=0.6)", w_mon, "uniform", 0.0, 0.6),
        ("Vega M3: Geom + ELR (u=0)", w_mon, "elr", 0.0, 0.0),
        ("Vega M3: Geom + ELR + LD", w_mon, "elr", 0.0, 0.6),
        ("Vega M3: Geom + vZ.231 + LD", w_mon, "vz", 0.231, 0.6),
        ("Aufdenberg 06 (0.916) ELR+LD", w_auf, "elr", 0.0, 0.6),
        ("Near-breakup (0.990) ELR+LD", w_ext, "elr", 0.0, 0.6),
    ]:
        Lb, _, _, Lfn = build_star(w, 2.726, 10070.0, model=mod, beta=beta, u=u, N_th=240)
        r0, r90 = Lfn(0.0) / Lb, Lfn(90.0) / Lb
        dmag = -2.5 * math.log10(r90 / r0)
        ih = find_honest_angle(Lb, Lfn)
        print(f"{label:28s} {r0:8.4f} {r90:9.4f} {dmag:+11.4f} {ih:8.3f}° {ih-MAGIC_ANGLE_DEG:+8.3f}°")

    # 4. Multiband magnitudes vs inclination (Monnier ELR, gray atmosphere)
    _, _, rings_elr_120, _ = build_star(w_mon, 2.726, 10070.0, model="elr", u=0.6, N_th=120)
    bands = [("UV250", 250e-9), ("U", 365e-9), ("B", 445e-9), ("V", 551e-9), ("K", 2190e-9)]
    ref = {b: monochromatic_flux(rings_elr_120, lam, 6.2, gray_atm=True) for b, lam in bands}
    print("\n=== 4. Multiband Photometry vs Inclination (Vega ELR, gray atmosphere) ===")
    print(f"{'inc':>6} {'V':>7} {'dUV250':>8} {'dU':>7} {'dB':>7} {'dV':>7} {'dK':>7} {'B-V':>7} {'V-K':>7}")
    for inc in [0.0, 6.2, 30.0, 54.74, 75.0, 90.0]:
        dm = {b: -2.5 * math.log10(monochromatic_flux(rings_elr_120, lam, inc, gray_atm=True) / ref[b]) for b, lam in bands}
        print(f"{inc:5.1f}° {0.03+dm['V']:+7.3f} {dm['UV250']:+8.3f} {dm['U']:+7.3f} {dm['B']:+7.3f} {dm['V']:+7.3f} {dm['K']:+7.3f} {dm['B']-dm['V']:+7.3f} {dm['V']-dm['K']:+7.3f}")

    # 5. Optical single-T SED mirage & depth-latitude interference
    opt_grid = [380, 420, 460, 500, 550, 600, 650, 700, 750]
    print("\n=== 5. Optical Single-T SED Residuals (Pure Planck vs Milne-Eddington Gray Atm) ===")
    for inc in [6.2, 54.74, 90.0]:
        Tp, Rp = fit_single_T(rings_elr_120, inc, opt_grid, gray_atm=False)
        Tg, Rg = fit_single_T(rings_elr_120, inc, opt_grid, gray_atm=True)
        rp = " | ".join(
            f"{nm}nm:{100*(monochromatic_flux(rings_elr_120, nm*1e-9, inc, False)/spherical_flux(nm*1e-9, Tp, Rp, False)-1):+.2f}%"
            for nm in [200, 551, 2190, 10000]
        )
        rg = " | ".join(
            f"{nm}nm:{100*(monochromatic_flux(rings_elr_120, nm*1e-9, inc, True)/spherical_flux(nm*1e-9, Tg, Rg, True)-1):+.2f}%"
            for nm in [200, 551, 2190, 10000]
        )
        print(f"  i={inc:5.2f}° Planck (T={Tp:6.1f}K): {rp}")
        print(f"  i={inc:5.2f}° GrayAtm(T={Tg:6.1f}K): {rg}")

    # 6. Line profiles & SVG generation
    v_eq_mon = (2.0 * math.pi * 2.726 * R_SUN) / (0.71 * 86400.0) / 1000.0
    v_grid = [float(v) for v in range(-30, 31)]
    p_unif = compute_line_profile(rings_elr, 6.2, v_eq_mon, 500e-9, lambda T: 1.0, v_grid)
    p_fe1 = compute_line_profile(rings_elr, 6.2, v_eq_mon, 500e-9, saha_FeI_weight, v_grid)
    p_he1 = compute_line_profile(rings_elr, 6.2, v_eq_mon, 500e-9, boltzmann_HeI_weight, v_grid)
    p_fe1_auf = compute_line_profile(rings_auf, 4.5, 274.0, 500e-9, saha_FeI_weight, v_grid)

    def fwhm(prof: list[float]) -> float:
        half = 0.5 * max(prof)
        above = [v for v, p in zip(v_grid, prof) if p >= half]
        return above[-1] - above[0]

    print("\n=== 6. Gulliver-Hill-Adelman Weak Line Profile Split (i = 6.2°, v sin i = 21.0 km/s) ===")
    for label, prof in [
        ("Uniform W(T)=const", p_unif),
        ("Cool-eq Fe I (Monnier 0.774)", p_fe1),
        ("Hot-pole He I (Monnier 0.774)", p_he1),
        ("Cool-eq Fe I (Aufdenberg 0.916)", p_fe1_auf),
    ]:
        c0, pk = prof[v_grid.index(0.0)], max(prof)
        print(f"  {label:32s}: Center/Peak={c0/pk:.4f}, FWHM={fwhm(prof):4.1f} km/s")

    svg_path = Path(__file__).resolve().parent / "vega_figures.svg"
    write_svg(svg_path, w_mon, Lb_elr, Lfn_elr, c2, v_grid, p_unif, p_fe1, p_he1, p_fe1_auf)
    print(f"\nWrote {svg_path} ({svg_path.stat().st_size} bytes)")

if __name__ == "__main__":
    main()
