import numpy as np
import plotly.graph_objects as go

planet_data = [
    ("Mercury", 0.387, 7.00, 48.33, 0.055, 0.0553, "#9ca3af"),
    ("Venus",   0.723, 3.39, 76.68, 0.0068, 0.815, "#f59e0b"),
    ("Earth",   1.000, 0.00, 0.00, 0.0167, 1.000, "#2563eb"),
    ("Mars",    1.524, 1.85, 49.56, 0.0934, 0.107, "#dc2626"),
    ("Jupiter", 5.203, 1.30, 100.46, 0.0489, 317.8, "#b45309"),
    ("Saturn",  9.537, 2.49, 113.72, 0.0565, 95.2, "#eab308"),
    ("Uranus", 19.191, 0.77, 74.23, 0.0457, 14.5, "#06b6d4"),
    ("Neptune",30.069, 1.77, 131.72, 0.0113, 17.1, "#1d4ed8"),
]

def rot_x(angle):
    c, s = np.cos(angle), np.sin(angle)
    return np.array([[1, 0, 0], [0, c, -s], [0, s, c]])

def rot_z(angle):
    c, s = np.cos(angle), np.sin(angle)
    return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])

def orbit_normal(inc_deg, raan_deg):
    inc = np.radians(inc_deg)
    raan = np.radians(raan_deg)
    normal = rot_z(raan) @ rot_x(inc) @ np.array([0.0, 0.0, 1.0])
    return normal / np.linalg.norm(normal)

H = np.zeros(3)
orbit_curves = []
for name, a, inc_deg, raan_deg, ecc, mass_rel, color in planet_data:
    h_weight = mass_rel * np.sqrt(a * (1.0 - ecc**2))
    h_hat = orbit_normal(inc_deg, raan_deg)
    H += h_weight * h_hat

    nu = np.linspace(0.0, 2.0 * np.pi, 280)
    r = a * (1.0 - ecc**2) / (1.0 + ecc * np.cos(nu))
    perifocal = np.vstack([r * np.cos(nu), r * np.sin(nu), np.zeros_like(nu)])
    orbit_xyz = rot_z(np.radians(raan_deg)) @ rot_x(np.radians(inc_deg)) @ perifocal
    orbit_curves.append((name, orbit_xyz, color))

H_hat = H / np.linalg.norm(H)
tilt_deg = np.degrees(np.arccos(np.clip(np.dot(H_hat, np.array([0.0, 0.0, 1.0])), -1.0, 1.0)))

plane_size = 32.0
u = np.linspace(-plane_size, plane_size, 9)
Xg, Yg = np.meshgrid(u, u)
Zg = np.zeros_like(Xg)

trial = np.array([1.0, 0.0, 0.0])
if abs(np.dot(trial, H_hat)) > 0.9:
    trial = np.array([0.0, 1.0, 0.0])
plane_u = np.cross(H_hat, trial)
plane_u /= np.linalg.norm(plane_u)
plane_v = np.cross(H_hat, plane_u)
U, V = np.meshgrid(u, u)
plane_pts = U[..., None] * plane_u + V[..., None] * plane_v
Xi, Yi, Zi = plane_pts[..., 0], plane_pts[..., 1], plane_pts[..., 2]

fig = go.Figure()
fig.add_trace(go.Surface(
    x=Xg, y=Yg, z=Zg,
    opacity=0.18,
    showscale=False,
    colorscale=[[0, "#94a3b8"], [1, "#94a3b8"]],
    name="Ecliptic plane",
    hoverinfo="skip",
))
fig.add_trace(go.Surface(
    x=Xi, y=Yi, z=Zi,
    opacity=0.22,
    showscale=False,
    colorscale=[[0, "#22c55e"], [1, "#22c55e"]],
    name="Invariable plane",
    hoverinfo="skip",
))

for name, orbit_xyz, color in orbit_curves:
    fig.add_trace(go.Scatter3d(
        x=orbit_xyz[0], y=orbit_xyz[1], z=2.8 * orbit_xyz[2],
        mode="lines",
        line=dict(width=4, color=color),
        name=name,
    ))

fig.add_trace(go.Scatter3d(
    x=[0.0, 18.0 * H_hat[0]],
    y=[0.0, 18.0 * H_hat[1]],
    z=[0.0, 18.0 * 2.8 * H_hat[2]],
    mode="lines+markers",
    line=dict(width=10, color="#111827"),
    marker=dict(size=4, color="#111827"),
    name="Total angular momentum $\\mathbf{H}$",
))
fig.add_trace(go.Scatter3d(
    x=[0.0], y=[0.0], z=[0.0],
    mode="markers+text",
    marker=dict(size=8, color="#facc15"),
    text=["Sun"],
    textposition="top center",
    name="Sun",
))

fig.update_layout(
    template="plotly_white",
    margin=dict(l=0, r=0, t=40, b=0),
    legend=dict(x=0.01, y=0.99, bgcolor="rgba(255,255,255,0.8)"),
    scene=dict(
        xaxis_title="x (AU)",
        yaxis_title="y (AU)",
        zaxis_title="z (AU, exaggerated)",
        xaxis=dict(range=[-32, 32], backgroundcolor="#f8fafc", gridcolor="#e2e8f0"),
        yaxis=dict(range=[-32, 32], backgroundcolor="#f8fafc", gridcolor="#e2e8f0"),
        zaxis=dict(range=[-4.0, 4.0], backgroundcolor="#f8fafc", gridcolor="#e2e8f0"),
        aspectmode="manual",
        aspectratio=dict(x=1.2, y=1.2, z=0.45),
        camera=dict(eye=dict(x=1.55, y=1.35, z=0.7)),
        annotations=[
            dict(
                x=15.5 * H_hat[0],
                y=15.5 * H_hat[1],
                z=15.5 * 2.8 * H_hat[2],
                text=f"Tilt to ecliptic ≈ {tilt_deg:.2f}°",
                showarrow=False,
                bgcolor="rgba(255,255,255,0.85)",
            )
        ],
    ),
)
fig.show()
