#!/usr/bin/env python3
"""
Daily Curiosity #2 — Чому трава зелена?
Schematic: white sunlight hits a leaf; chloroplasts absorb red and blue,
reflect green back to the eye.
"""
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.patches import FancyArrowPatch, Circle, FancyBboxPatch, Polygon
import numpy as np

# ---- Canvas ----
fig, ax = plt.subplots(figsize=(12, 7), dpi=160)
ax.set_xlim(0, 12)
ax.set_ylim(0, 7)
ax.set_aspect('equal')
ax.axis('off')

# Dark forest-green gradient background
bg = np.linspace(0, 1, 256).reshape(-1, 1)
bg = np.repeat(bg, 256, axis=1)
ax.imshow(
    bg,
    extent=(0, 12, 0, 7),
    cmap=plt.cm.colors.LinearSegmentedColormap.from_list(
        "forest", ["#0a1f10", "#16361f", "#1f4a2a"]
    ),
    aspect='auto',
    zorder=0,
)

# ---- Title and subtitle (Ukrainian) ----
ax.text(
    6, 6.55,
    "Чому трава зелена?",
    ha='center', va='center',
    fontsize=26, fontweight='bold', color='#f4ffe8',
    zorder=10,
)
ax.text(
    6, 6.05,
    "Хлорофіл поглинає червоне і синє світло — а зелене відбиває назад до нас",
    ha='center', va='center',
    fontsize=12, style='italic', color='#cfe8b6',
    zorder=10,
)

# ---- Sun (top-left) ----
sun = Circle((1.2, 5.2), 0.42, color='#ffe168', zorder=5, ec='#ffd23a', lw=1.5)
ax.add_patch(sun)
for ang in range(0, 360, 30):
    a = np.deg2rad(ang)
    x0 = 1.2 + 0.5 * np.cos(a)
    y0 = 5.2 + 0.5 * np.sin(a)
    x1 = 1.2 + 0.78 * np.cos(a)
    y1 = 5.2 + 0.78 * np.sin(a)
    ax.plot([x0, x1], [y0, y1], color='#ffd23a', lw=1.5, zorder=5)
ax.text(1.2, 5.2, "☀", ha='center', va='center', fontsize=20, color='#7a5a00', zorder=6)
ax.text(1.2, 4.45, "Сонце", ha='center', va='top', fontsize=11, color='#ffe168', zorder=6, fontweight='bold')

# ---- Incoming "white" light ray bundle (red + green + blue side-by-side) ----
# Aim from sun toward leaf at ~ (5.5, 3.4)
def colored_ray(x0, y0, x1, y1, color, label_text=None, lw=2.6, zorder=5):
    arr = FancyArrowPatch(
        (x0, y0), (x1, y1),
        arrowstyle='-|>', mutation_scale=14,
        color=color, lw=lw, zorder=zorder,
    )
    ax.add_patch(arr)

# White-light label
ax.text(
    2.55, 4.95,
    "біле сонячне світло",
    ha='left', va='center', fontsize=10.5, color='#f4ffe8',
    zorder=8,
)
ax.text(
    2.55, 4.62,
    "(червоне + зелене + синє)",
    ha='left', va='center', fontsize=9, color='#cfe8b6', style='italic',
    zorder=8,
)

# Three parallel rays (red, green, blue) heading to the leaf
target = np.array([5.4, 3.55])
for dy, color in zip([+0.18, 0.0, -0.18], ['#ff5b5b', '#7fff8a', '#5fb6ff']):
    start = np.array([1.95, 4.85 + dy])
    end = target + np.array([0, dy * 0.4])
    colored_ray(start[0], start[1], end[0], end[1], color, lw=2.4)

# ---- The leaf ----
# Leaf as an ellipse-like polygon
theta = np.linspace(0, 2 * np.pi, 200)
leaf_x = 6.4 + 1.6 * np.cos(theta) - 0.35 * np.sin(2 * theta)
leaf_y = 3.3 + 0.85 * np.sin(theta)
ax.fill(leaf_x, leaf_y, color='#3fa860', ec='#1f7a3a', lw=2.2, zorder=4)

# Leaf central vein
ax.plot([4.85, 8.0], [3.3, 3.3], color='#1f5a2a', lw=1.6, zorder=5)
# Side veins
for vx in [5.3, 5.9, 6.5, 7.1, 7.55]:
    dy = 0.55 * (1 - abs(vx - 6.4) / 1.7)
    ax.plot([vx, vx + 0.35], [3.3, 3.3 + dy], color='#1f5a2a', lw=1.0, zorder=5)
    ax.plot([vx, vx + 0.35], [3.3, 3.3 - dy], color='#1f5a2a', lw=1.0, zorder=5)

# Chloroplasts as small green dots inside the leaf
rng = np.random.default_rng(42)
for _ in range(35):
    cx = 6.4 + rng.uniform(-1.25, 1.25)
    cy = 3.3 + rng.uniform(-0.6, 0.6)
    # keep inside ellipse-ish
    if ((cx - 6.4) / 1.45) ** 2 + ((cy - 3.3) / 0.7) ** 2 < 0.9:
        ax.add_patch(Circle((cx, cy), 0.07, color='#0e3d1a', zorder=6, alpha=0.85))

ax.text(6.4, 2.30, "лист (хлорофіл у клітинах)", ha='center', va='center',
        fontsize=10.5, color='#dff7c5', zorder=8, fontweight='bold')

# ---- Absorbed colors (red & blue) shown sinking INTO the leaf ----
ax.text(
    8.55, 4.55,
    "поглинається\n(енергія для\nфотосинтезу)",
    ha='left', va='center', fontsize=9.5, color='#ffd6d6', style='italic',
    zorder=8,
)
# Red absorbed arrow into leaf
arr_r = FancyArrowPatch((8.55, 4.45), (7.6, 3.55), arrowstyle='-|>',
                       mutation_scale=14, color='#ff5b5b', lw=2.2, zorder=7)
ax.add_patch(arr_r)
# Blue absorbed arrow into leaf
arr_b = FancyArrowPatch((8.55, 3.95), (7.6, 3.45), arrowstyle='-|>',
                       mutation_scale=14, color='#5fb6ff', lw=2.2, zorder=7)
ax.add_patch(arr_b)
# small absorbed labels
ax.text(8.62, 4.45, "  червоне", ha='left', va='center', fontsize=9, color='#ff8a8a', zorder=8)
ax.text(8.62, 3.95, "  синє", ha='left', va='center', fontsize=9, color='#9cd0ff', zorder=8)

# ---- Reflected GREEN bouncing toward the eye ----
# Several green arrows fanning down-right toward the eye
eye_pos = (10.6, 1.4)
for (sx, sy) in [(7.4, 3.2), (7.55, 3.0), (7.65, 2.85)]:
    arr_g = FancyArrowPatch(
        (sx, sy), eye_pos,
        arrowstyle='-|>', mutation_scale=16,
        color='#7fff8a', lw=2.6, zorder=7,
    )
    ax.add_patch(arr_g)

ax.text(
    8.95, 2.55,
    "зелене\nвідбивається",
    ha='center', va='center', fontsize=10.5, color='#c8ffd0', fontweight='bold',
    zorder=8,
)

# ---- Eye / observer ----
# Eye drawing: white sclera, green iris, black pupil
ax.add_patch(Circle(eye_pos, 0.42, color='#f4ffe8', ec='#1f5a2a', lw=1.5, zorder=8))
ax.add_patch(Circle(eye_pos, 0.22, color='#3fa860', zorder=9))
ax.add_patch(Circle(eye_pos, 0.09, color='#0a1f10', zorder=10))
# eye highlight
ax.add_patch(Circle((eye_pos[0] - 0.05, eye_pos[1] + 0.05), 0.025,
                   color='#ffffff', zorder=11))
ax.text(eye_pos[0], eye_pos[1] - 0.7, "ми бачимо\nзелений колір",
        ha='center', va='top', fontsize=10, color='#f4ffe8', zorder=8)

# ---- Bottom info strip: spectrum + absorption note ----
# Mini visible-light spectrum bar
spec_x0, spec_y0, spec_w, spec_h = 0.6, 0.55, 6.5, 0.32
spectrum_colors = [
    '#7a3aff', '#3a5cff', '#2ec5ff', '#2effa8',
    '#7fff42', '#fff148', '#ffa235', '#ff4a4a',
]
n = len(spectrum_colors)
for i, c in enumerate(spectrum_colors):
    ax.add_patch(plt.Rectangle(
        (spec_x0 + i * spec_w / n, spec_y0), spec_w / n, spec_h,
        color=c, ec='none', zorder=6,
    ))
ax.add_patch(plt.Rectangle((spec_x0, spec_y0), spec_w, spec_h,
                          fill=False, ec='#f4ffe8', lw=1.2, zorder=7))

# Absorption brackets
def bracket(x_start, x_end, y, label, color):
    ax.plot([x_start, x_start, x_end, x_end],
            [y + 0.05, y + 0.18, y + 0.18, y + 0.05],
            color=color, lw=1.6, zorder=8)
    ax.text((x_start + x_end) / 2, y + 0.30, label,
            ha='center', va='bottom', fontsize=9, color=color, zorder=8)

# Visible spectrum brackets:
# violet/blue range ~ first ~3/8, green middle, red last ~2/8
bracket(spec_x0, spec_x0 + spec_w * 0.32, spec_y0 + spec_h, "поглинається", '#9cd0ff')
bracket(spec_x0 + spec_w * 0.72, spec_x0 + spec_w, spec_y0 + spec_h, "поглинається", '#ff8a8a')
bracket(spec_x0 + spec_w * 0.40, spec_x0 + spec_w * 0.60, spec_y0 + spec_h, "відбивається", '#c8ffd0')

ax.text(spec_x0, spec_y0 - 0.18, "видиме світло",
        ha='left', va='top', fontsize=9, color='#cfe8b6', style='italic')
ax.text(spec_x0 + spec_w, spec_y0 - 0.18, "←  довжина хвилі  →",
        ha='right', va='top', fontsize=9, color='#cfe8b6', style='italic')

# Right-side annotation box
note = (
    "Хлорофіл — пігмент у хлоропластах,\n"
    "що захоплює енергію червоного й синього\n"
    "світла для фотосинтезу.\n"
    "Зелене світло йому не потрібне — і ми\n"
    "бачимо саме його."
)
ax.text(
    11.9, 1.05, note,
    ha='right', va='center', fontsize=9.5, color='#f4ffe8',
    bbox=dict(boxstyle='round,pad=0.45', fc='#0e3d1a', ec='#3fa860', lw=1.2),
    zorder=9,
)

# Save
out_path = "/sessions/busy-eloquent-edison/mnt/daily-curiosity/daily-curiosity-02.png"
plt.savefig(out_path, dpi=160, bbox_inches='tight', facecolor='#0a1f10')
print(f"Saved: {out_path}")
