"""Génère illustrations/03-petits-mots.svg : SA main à lui, paume vers le haut, qui se
referme sur des petits mots pliés puis se rouvre.
Chaque doigt a 3 phalanges : on calcule l'angle de flexion cumulé de chacune et on la
projette vue de dessus (raccourci = cos de l'angle). Au-delà de 90°, on voit le dos de
la phalange (et l'ongle pour la dernière)."""
import math, sys

out = sys.argv[1]
DUREE = 5            # secondes par cycle
N = 40               # échantillons d'animation par cycle

PALM = "#EDBBA0"; PALM_SH = "#C98C70"; DORS = "#D99B7E"; DORS_SH = "#A96C54"
NAIL = "#F2C9BA"; SILVER = "#D4D4DC"; SILVER_D = "#9A9AA8"; CREASE = "#CF977B"
FONT = "'Bradley Hand','Segoe Print','Snell Roundhand','Comic Sans MS',cursive"

def smooth(x):
    x = max(0.0, min(1.0, x))
    return x * x * (3 - 2 * x)

def prog(t, d=0.0):
    """0 = main ouverte, 1 = main fermée."""
    t = (t - d) % 1.0
    if t < 0.18: return 0.0
    if t < 0.40: return smooth((t - 0.18) / 0.22)
    if t < 0.58: return 1.0
    if t < 0.80: return 1.0 - smooth((t - 0.58) / 0.22)
    return 0.0

def lerp(a, b, k): return a + (b - a) * k

def hexmix(c1, c2, k):
    k = max(0.0, min(1.0, k))
    a = [int(c1[i:i+2], 16) for i in (1, 3, 5)]
    b = [int(c2[i:i+2], 16) for i in (1, 3, 5)]
    return "#" + "".join(f"{round(lerp(x, y, k)):02X}" for x, y in zip(a, b))

def shade(c):
    """couleur d'une phalange selon son orientation (c = cos de l'angle)."""
    return hexmix(PALM_SH, PALM, c) if c >= 0 else hexmix(DORS_SH, DORS, -c)

css = []
uid = [0]
def anim(frames):
    uid[0] += 1
    name = f"k{uid[0]}"
    body = "".join(f"{i*100/N:.1f}%{{{f}}}" for i, f in enumerate(frames))
    css.append(f"@keyframes {name}{{{body}}}")
    return f"animation:{name} {DUREE}s linear infinite"

def chain(lengths, open_a, closed_a, d):
    res = []
    for i in range(N + 1):
        p = prog(i / N, d)
        cum, y, segs = 0.0, 0.0, []
        for L, a0, a1 in zip(lengths, open_a, closed_a):
            cum += lerp(a0, a1, p)
            c = math.cos(math.radians(cum))
            segs.append((y, c))
            y -= L * c
        res.append((p, segs, y))
    return res

def ring(w_, L_, thick=False):
    h = 5.2 if thick else 4.2
    return (f'<rect x="{-w_/2-1:.1f}" y="{-L_*.45:.1f}" width="{w_+2:.1f}" height="{h}" rx="2" fill="{SILVER}"/>'
            f'<path d="M{-w_/2:.1f} {-L_*.45+h-1:.1f}H{w_/2:.1f}" stroke="{SILVER_D}" stroke-width="1"/>')

def finger(bx, by, ang_open, ang_closed, w, L, d, bague=None):
    Ls = [L * .45, L * .30, L * .25]
    ws = [w, w * .93, w * .86]
    data = chain(Ls, [4, 4, 2], [72, 95, 45], d)
    rot = anim([f"transform:rotate({lerp(ang_open, ang_closed, p):.2f}deg)" for p, _, _ in data])
    parts = []
    for k in range(3):
        L_, w_ = Ls[k], ws[k]
        st = anim([f"transform:translateY({s[k][0]:.2f}px) scaleY({s[k][1]:.3f});fill:{shade(s[k][1])}" for _, s, _ in data])
        front = anim([f"opacity:{max(0, min(1, s[k][1]*2)):.2f}" for _, s, _ in data])
        inner = f'<rect x="{-w_/2:.1f}" y="{-L_-1:.1f}" width="{w_:.1f}" height="{L_+2:.1f}"/>'
        inner += (f'<path style="{front}" d="M{-w_*.32:.1f} -2Q0 0 {w_*.32:.1f} -2" fill="none" stroke="{CREASE}" '
                  f'stroke-width="1.1" stroke-linecap="round" opacity=".7"/>')
        if k == 0 and bague:
            inner += ring(w_, L_, thick=(bague == "large"))
        if k == 2:
            nail = anim([f"opacity:{max(0, min(1, -s[k][1]*2.5)):.2f}" for _, s, _ in data])
            inner += (f'<g style="{nail}"><rect x="{-w_*.31:.1f}" y="{-L_+1:.1f}" width="{w_*.62:.1f}" height="{L_*.6:.1f}" '
                      f'rx="{w_*.26:.1f}" fill="{NAIL}"/><path d="M{-w_*.12:.1f} {-L_+4:.1f}h{w_*.24:.1f}" stroke="#FFF" '
                      f'stroke-width="1.3" stroke-linecap="round" opacity=".6"/></g>')
        parts.append(f'<g style="{st}">{inner}</g>')
        if k < 2:
            end = [(s[k+1][0], (s[k][1] + s[k+1][1]) / 2) for _, s, _ in data]
            r = ws[k+1] / 2
        else:
            end = [(tip, s[2][1]) for _, s, tip in data]
            r = w_ / 2
        j = anim([f"transform:translateY({y:.2f}px);fill:{shade(c)}" for y, c in end])
        parts.append(f'<circle r="{r:.1f}" style="{j}"/>')
    return f'<g transform="translate({bx} {by})"><g style="{rot}">{"".join(parts)}</g></g>'

def thumb():
    Ls = [42, 36, 30]; ws = [38, 30, 27]
    data = chain(Ls, [0, 0, 6], [10, 14, 40], 0.035)
    rot = anim([f"transform:rotate({lerp(46, -54, p):.2f}deg)" for p, _, _ in data])
    parts = []
    for k in range(3):
        L_, w_ = Ls[k], ws[k]
        st = anim([f"transform:translateY({s[k][0]:.2f}px) scaleY({s[k][1]:.3f});fill:{shade(s[k][1])}" for _, s, _ in data])
        inner = f'<rect x="{-w_/2:.1f}" y="{-L_-1:.1f}" width="{w_:.1f}" height="{L_+2:.1f}"/>'
        if k == 1:
            inner += f'<path d="M{-w_*.32:.1f} -2Q0 0 {w_*.32:.1f} -2" fill="none" stroke="{CREASE}" stroke-width="1.1" stroke-linecap="round" opacity=".7"/>'
        if k == 2:
            nail = anim([f"opacity:{lerp(.25, 1, p):.2f}" for p, _, _ in data])
            inner += f'<path style="{nail}" d="M{w_*.42:.1f} {-L_+3:.1f}Q{w_*.58:.1f} {-L_*.6:.1f} {w_*.4:.1f} {-L_*.3:.1f}" fill="none" stroke="{NAIL}" stroke-width="3.2" stroke-linecap="round"/>'
        parts.append(f'<g style="{st}">{inner}</g>')
        if k < 2:
            end = [(s[k+1][0], s[k+1][1]) for _, s, _ in data]; r = ws[k+1] / 2
        else:
            end = [(tip, s[2][1]) for _, s, tip in data]; r = w_ / 2
        j = anim([f"transform:translateY({y:.2f}px);fill:{shade(c)}" for y, c in end])
        parts.append(f'<circle r="{r:.1f}" style="{j}"/>')
    return f'<g transform="translate(268 356)"><g style="{rot}">{"".join(parts)}</g></g>'

def note(x, y, rot, col, ink, word=None):
    w, h = 28, 20
    t = (f'<text x="-11" y="3" font-family="{FONT}" font-size="8" fill="{ink}" transform="rotate(-4)">{word}</text>'
         if word else
         f'<path d="M-10 4q3-2 6 0t6 0M-10 7.5q3-2 6 0" fill="none" stroke="{ink}" stroke-width=".9" stroke-linecap="round" opacity=".75"/>')
    return f'''<g transform="translate({x} {y}) rotate({rot})">
    <rect x="{-w/2+1.5}" y="{-h/2+2}" width="{w}" height="{h}" rx="2" fill="#000" opacity=".12"/>
    <rect x="{-w/2}" y="{-h/2}" width="{w}" height="{h}" rx="2" fill="{col}"/>
    <path d="M0 {-h/2}V{h/2}M{-w/2} 0H{w/2}" stroke="#000" stroke-opacity=".1" stroke-width=".8"/>
    <path d="M{w/2} {-h/2}L{w/2-8} {-h/2}L{w/2} {-h/2+8}Z" fill="#FFF" opacity=".6"/>
    {t}</g>'''

notes = "\n".join([
    note(166, 292, -18, "#FFE1E8", "#B03A5E", "toi ♥"),
    note(242, 294, 22, "#FFF2B8", "#8A6A20"),
    note(176, 336, 10, "#DDEFFF", "#2F5E9E", "bisou"),
    note(238, 336, -14, "#E6F5E1", "#3D7A4A", "merci"),
])
big_note = f'''<g transform="translate(205 314) rotate(-7)">
    <rect x="-30" y="-19" width="62" height="42" rx="2.5" fill="#000" opacity=".12"/>
    <rect x="-32" y="-22" width="62" height="42" rx="2.5" fill="#FFF8E7"/>
    <path d="M-16.5-22V20M-1-22V20M14.5-22V20M-32-1H30" stroke="#C9B48A" stroke-opacity=".55" stroke-width=".8"/>
    <path d="M-32-22L-16.5-22L-32-10Z" fill="#F3E6C9"/>
    <text x="-25" y="-5" font-family="{FONT}" font-size="12.5" fill="#D2335B" transform="rotate(-3)">je t'aime</text>
    <path d="M14 6C14 3.5 10.5 3.5 10.5 6C10.5 8 14 10 14 11.5C14 10 17.5 8 17.5 6C17.5 3.5 14 3.5 14 6Z" fill="#E8466E"/>
    <text x="-26" y="13" font-family="{FONT}" font-size="7.5" fill="#7A5A8C">fort fort fort</text>
  </g>'''

# main droite paume vers le haut : auriculaire à gauche, index à droite, pouce à droite
fingers = "".join([
    finger(150, 272, -13, -3, 24, 88, 0.00),
    finger(182, 257, -4, 0, 27, 110, 0.015, bague="fine"),
    finger(213, 252, 2, 0, 28, 120, 0.03, bague="large"),
    finger(243, 259, 10, 3, 27, 104, 0.045),
])
pouce = thumb()
paume_anim = anim([f"transform:scaleX({lerp(1, .955, p):.3f})" for p in [prog(i / N, .02) for i in range(N + 1)]])

PAUME = "M150 380C141 344 134 306 136 276C150 252 232 244 257 261C267 273 279 302 279 328C279 352 271 368 262 382Z"

svg = f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 500" width="400" height="500">
<title>Des petits mots pliés dans ma main</title>
<defs>
  <radialGradient id="fond" cx=".5" cy=".42" r=".75">
    <stop offset="0" stop-color="#FFF1E6"/><stop offset=".6" stop-color="#F9D9C9"/><stop offset="1" stop-color="#EDB9AA"/>
  </radialGradient>
  <filter id="flou" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="9"/></filter>
  <filter id="lueur" x="-100%" y="-100%" width="300%" height="300%">
    <feGaussianBlur stdDeviation="1.6" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
  </filter>
  <pattern id="toile" width="6" height="6" patternUnits="userSpaceOnUse">
    <rect width="6" height="6" fill="#5E6B3F"/><path d="M0 6L6 0" stroke="#55623A" stroke-width="1"/>
  </pattern>
  <path id="coeur" d="M0 3C0-1-6-1-6 3C-6 6 0 9 0 11C0 9 6 6 6 3C6-1 0-1 0 3Z"/>
  <path id="eclat" d="M0-5Q.8-.8 5 0Q.8 .8 0 5Q-.8 .8-5 0Q-.8-.8 0-5Z"/>
</defs>
<style>
  .hop{{animation:hop {DUREE}s ease-out infinite}}
  @keyframes hop{{0%,76%{{transform:translateY(0)}}83%{{transform:translateY(-6px)}}90%,100%{{transform:translateY(0)}}}}
  .envol{{animation:envol {DUREE}s ease-out infinite}}
  @keyframes envol{{0%,72%{{transform:translate(0,0) scale(.4);opacity:0}}80%{{opacity:1}}100%{{transform:translate(var(--dx),-100px) scale(1.1);opacity:0}}}}
  .chute{{animation:chute 9s linear infinite}}
  @keyframes chute{{from{{transform:translateY(-60px) rotate(0)}}to{{transform:translateY(560px) rotate(260deg)}}}}
  .bokeh{{animation:bokeh 7s ease-in-out infinite alternate}}
  @keyframes bokeh{{from{{transform:translate(0,0)}}to{{transform:translate(12px,-14px)}}}}
  {"".join(css)}
</style>

<rect width="400" height="500" fill="url(#fond)"/>
<g fill="#FFFFFF" opacity=".45">
  <circle cx="60" cy="90" r="26" class="bokeh"/><circle cx="340" cy="70" r="18" class="bokeh" style="animation-delay:-3s"/>
  <circle cx="360" cy="380" r="30" class="bokeh" style="animation-delay:-5s"/><circle cx="40" cy="400" r="16" class="bokeh" style="animation-delay:-2s"/>
  <circle cx="320" cy="200" r="10" class="bokeh" style="animation-delay:-4s"/><circle cx="80" cy="230" r="8" class="bokeh" style="animation-delay:-6s"/>
</g>
<g opacity=".55">
  <g transform="translate(70 0)"><g class="chute"><rect x="-8" y="-6" width="16" height="11" rx="1" fill="#FFE1E8"/><path d="M0-6V5" stroke="#000" stroke-opacity=".1"/></g></g>
  <g transform="translate(336 0)"><g class="chute" style="animation-delay:-4s;animation-duration:11s"><rect x="-8" y="-6" width="16" height="11" rx="1" fill="#FFF2B8"/><path d="M0-6V5" stroke="#000" stroke-opacity=".1"/></g></g>
  <g transform="translate(104 0)"><g class="chute" style="animation-delay:-7s;animation-duration:10s"><rect x="-7" y="-5" width="14" height="10" rx="1" fill="#DDEFFF"/></g></g>
</g>
<g fill="#F28CA6" opacity=".5">
  <g transform="translate(306 0)"><g class="chute" style="animation-delay:-2s;animation-duration:12s"><use href="#coeur"/></g></g>
  <g transform="translate(40 0)"><g class="chute" style="animation-delay:-8s;animation-duration:13s"><use href="#coeur"/></g></g>
</g>

<!-- ombre douce -->
<path d="M148 500L150 380C138 344 130 304 132 272C148 242 238 238 266 258C286 294 302 334 292 374L266 500Z" fill="#8A4A3A" opacity=".22" filter="url(#flou)" transform="translate(9 10)"/>

<!-- avant-bras + poignet de la surchemise kaki -->
<path d="M150 376L148 500H266L263 378Z" fill="{PALM}"/>
<path d="M150 386Q206 398 263 386" fill="none" stroke="{CREASE}" stroke-width="1" opacity=".5"/>
<path d="M134 500L139 418Q206 406 276 418L281 500Z" fill="url(#toile)"/>
<path d="M139 418Q206 406 276 418L277 440Q206 428 138 440Z" fill="#56633A"/>
<path d="M139 418Q206 406 276 418" fill="none" stroke="#3C4529" stroke-width="1.6"/>
<path d="M138 440Q206 428 277 440" fill="none" stroke="#3C4529" stroke-width="1" stroke-dasharray="2 2"/>
<circle cx="262" cy="428" r="3" fill="#3C4529"/>

<!-- paume (se creuse un peu quand la main se ferme) -->
<g style="transform-origin:208px 304px;{paume_anim}">
  <path d="{PAUME}" fill="{PALM}"/>
  <path d="M273 304C285 334 281 364 263 380C251 388 241 380 245 366C253 344 257 322 257 304Z" fill="#F3C9AF" opacity=".8"/>
  <g fill="none" stroke="{CREASE}" stroke-linecap="round" opacity=".5" stroke-width="1.3">
    <path d="M140 292Q196 286 254 270"/><path d="M144 310Q196 310 246 294"/><path d="M258 290Q230 324 238 376"/>
  </g>
</g>

<!-- les petits mots -->
<g class="hop">
{notes}
{big_note}
</g>

<!-- doigts articulés (auriculaire → index), puis pouce par-dessus -->
{fingers}
{pouce}

<!-- cœurs et éclats qui s'échappent quand la main s'ouvre -->
<g filter="url(#lueur)">
  <g transform="translate(202 292)" fill="#E8466E"><g class="envol" style="--dx:-30px"><use href="#coeur"/></g></g>
  <g transform="translate(224 298) scale(.8)" fill="#FF8FB0"><g class="envol" style="--dx:26px;animation-delay:.15s"><use href="#coeur"/></g></g>
  <g transform="translate(178 312)" fill="#FFD36B"><g class="envol" style="--dx:-46px;animation-delay:.25s"><use href="#eclat"/></g></g>
  <g transform="translate(242 312)" fill="#FFD36B"><g class="envol" style="--dx:44px;animation-delay:.1s"><use href="#eclat"/></g></g>
  <g transform="translate(208 302) scale(.6)" fill="#FFFFFF"><g class="envol" style="--dx:6px;animation-delay:.35s"><use href="#eclat"/></g></g>
</g>
</svg>
'''
open(out, "w").write(svg)
print("ok", len(svg), "octets,", uid[0], "animations")
