"""Génère illustrations/04-coupes.svg : mosaïque de 12 coupes de cheveux pour elle
(longueurs x styles, comme sa planche de référence), avec une roulette lumineuse qui
saute de case en case puis un cercle rouge dessiné à la main autour de ses 2 favorites."""
import math, sys

out = sys.argv[1]
CYCLE = 9  # s

SKIN = "#D9A283"; SKIN_SH = "#C48A6C"; HAIR = "#3A2419"; HAIR_HI = "#6E4630"; HAIR_DK = "#2A1810"
FONT_L = "Georgia,'Times New Roman',serif"

COLS = ["Demi-attaché", "Frange rideau ouverte", "Frange rideau fine", "Frange rideau fournie"]
COLS_SHORT = ["Demi-attaché souple", "Rideau ouverte", "Rideau fine", "Rideau fournie"]
ROWS = [  # (libellé, longueur des cheveux en px sous le haut du crâne)
    [("Longs", 118)] * 4,
    [("Mi-longs", 92)] * 4,
    [("Carré long", 70), ("Carré long", 70), ("Carré court", 56), ("Carré court", 56)],
]
STYLES = ["demi", "ouverte", "fine", "fournie"]
FAVS = {(2, 0), (2, 1)}

X0, Y0, TW, TH, GAP = 8, 40, 91.5, 148, 6

def wavy_side(x_top, y_top, x_bot, y_bot, amp, waves, sign):
    """points d'un bord ondulé de haut en bas."""
    pts = []
    n = 24
    for i in range(n + 1):
        t = i / n
        x = x_top + (x_bot - x_top) * (t ** .8) + sign * amp * math.sin(t * waves * 2 * math.pi) * min(1, t * 3)
        y = y_top + (y_bot - y_top) * t
        pts.append((x, y))
    return pts

def path_from(pts):
    d = f"M{pts[0][0]:.1f} {pts[0][1]:.1f}"
    for x, y in pts[1:]:
        d += f"L{x:.1f} {y:.1f}"
    return d

def back_hair(cx, top, length):
    bottom = top + length
    spread = 22 + length * .1
    left = wavy_side(cx - 19, top + 14, cx - spread, bottom, 2.6, length / 34, -1)
    right = wavy_side(cx + 19, top + 14, cx + spread, bottom, 2.6, length / 34, 1)
    # bas en festons
    scallops = ""
    xs = [right[-1][0] - (right[-1][0] - left[-1][0]) * k / 5 for k in range(6)]
    for a, b in zip(xs, xs[1:]):
        mid = (a + b) / 2
        scallops += f"Q{mid:.1f} {bottom + 6:.1f} {b:.1f} {bottom - 1:.1f}"
    d = (f"M{cx - 19:.1f} {top + 14:.1f}C{cx - 20:.1f} {top - 2:.1f} {cx + 20:.1f} {top - 2:.1f} {cx + 19:.1f} {top + 14:.1f}"
         + path_from(right)[path_from(right).index("L"):] + scallops
         + "".join(f"L{x:.1f} {y:.1f}" for x, y in reversed(left)) + "Z")
    return d

def front_locks(cx, top, length):
    """mèches qui tombent devant les épaules."""
    out_ = []
    for s in (-1, 1):
        x0 = cx + s * 15
        bottom = top + length - 4
        pts_o = wavy_side(x0 + s * 3, top + 26, cx + s * (24 + length * .06), bottom, 2.4, length / 30, s)
        pts_i = wavy_side(x0 - s * 1, top + 30, cx + s * (14 + length * .05), bottom - 3, 2.0, length / 30, s)
        d = path_from(pts_o) + f"Q{(pts_o[-1][0] + pts_i[-1][0]) / 2:.1f} {bottom + 5:.1f} {pts_i[-1][0]:.1f} {pts_i[-1][1]:.1f}"
        d += "".join(f"L{x:.1f} {y:.1f}" for x, y in reversed(pts_i)) + "Z"
        out_.append(f'<path d="{d}" fill="{HAIR}"/>')
        # reflets
        hl = wavy_side(cx + s * 19, top + 40, cx + s * (20 + length * .055), bottom - 6, 2, length / 30, s)
        out_.append(f'<path d="{path_from(hl)}" fill="none" stroke="{HAIR_HI}" stroke-width="1.1" stroke-linecap="round" opacity=".8"/>')
    return "".join(out_)

def top_and_bangs(cx, top, style):
    hl = top + 13   # ligne d'implantation
    g = []
    # dessus du crâne (raie au milieu)
    g.append(f'<path d="M{cx - 18.5:.1f} {hl + 6:.1f}C{cx - 20:.1f} {top - 1:.1f} {cx + 20:.1f} {top - 1:.1f} {cx + 18.5:.1f} {hl + 6:.1f}'
             f'C{cx + 14:.1f} {hl - 2:.1f} {cx + 5:.1f} {hl - 3:.1f} {cx:.1f} {hl - 2:.1f}C{cx - 5:.1f} {hl - 3:.1f} {cx - 14:.1f} {hl - 2:.1f} {cx - 18.5:.1f} {hl + 6:.1f}Z" fill="{HAIR}"/>')
    g.append(f'<path d="M{cx:.1f} {top + 1:.1f}L{cx:.1f} {hl - 2:.1f}" stroke="{HAIR_DK}" stroke-width=".9"/>')
    if style == "demi":
        # cheveux tirés vers l'arrière + petites mèches libres qui encadrent le visage
        g.append(f'<path d="M{cx - 12:.1f} {top + 6:.1f}Q{cx - 6:.1f} {top + 2:.1f} {cx - 1:.1f} {top + 4:.1f}M{cx + 12:.1f} {top + 6:.1f}Q{cx + 6:.1f} {top + 2:.1f} {cx + 1:.1f} {top + 4:.1f}" '
                 f'fill="none" stroke="{HAIR_HI}" stroke-width="1" stroke-linecap="round"/>')
        for s in (-1, 1):
            g.append(f'<path d="M{cx + s * 9:.1f} {hl:.1f}Q{cx + s * 16:.1f} {hl + 12:.1f} {cx + s * 14:.1f} {hl + 24:.1f}Q{cx + s * 12:.1f} {hl + 32:.1f} {cx + s * 16:.1f} {hl + 38:.1f}" '
                     f'fill="none" stroke="{HAIR}" stroke-width="1.6" stroke-linecap="round"/>')
    else:
        thick = {"ouverte": 6.5, "fine": 4, "fournie": 9.5}[style]
        reach = {"ouverte": 24, "fine": 18, "fournie": 25}[style]
        gap = {"ouverte": 7, "fine": 5, "fournie": 2.5}[style]
        for s in (-1, 1):
            x_in = cx + s * gap
            d = (f"M{cx:.1f} {hl - 2:.1f}C{x_in:.1f} {hl + 4:.1f} {cx + s * (gap + 4):.1f} {hl + thick + 2:.1f} {cx + s * (gap + 9):.1f} {hl + thick + 5:.1f}"
                 f"C{cx + s * 15:.1f} {hl + reach - 6:.1f} {cx + s * 17:.1f} {hl + reach:.1f} {cx + s * 19.5:.1f} {hl + reach + 4:.1f}"
                 f"L{cx + s * 20:.1f} {hl + 4:.1f}C{cx + s * 14:.1f} {hl - 2:.1f} {cx + s * 6:.1f} {hl - 3:.1f} {cx:.1f} {hl - 2:.1f}Z")
            g.append(f'<path d="{d}" fill="{HAIR}"/>')
            g.append(f'<path d="M{cx + s * 3:.1f} {hl:.1f}C{cx + s * (gap + 5):.1f} {hl + thick:.1f} {cx + s * 14:.1f} {hl + reach - 8:.1f} {cx + s * 18:.1f} {hl + reach:.1f}" '
                     f'fill="none" stroke="{HAIR_HI}" stroke-width=".9" stroke-linecap="round" opacity=".85"/>')
            if style == "fine":
                g.append(f'<path d="M{cx + s * 4:.1f} {hl:.1f}Q{cx + s * 6:.1f} {hl + 7:.1f} {cx + s * 5:.1f} {hl + 10:.1f}" fill="none" stroke="{HAIR}" stroke-width="1" stroke-linecap="round"/>')
    return "".join(g)

def face(cx, top, i):
    fy = top + 30
    blink = f"animation:cligne {CYCLE/2:.1f}s linear infinite;animation-delay:{-(i * 0.37) % 4:.2f}s;transform-origin:{cx}px {fy - 1:.1f}px"
    return f'''
    <path d="M{cx - 6:.1f} {fy + 16:.1f}L{cx - 6.5:.1f} {fy + 30:.1f}H{cx + 6.5:.1f}L{cx + 6:.1f} {fy + 16:.1f}Z" fill="{SKIN_SH}"/>
    <ellipse cx="{cx}" cy="{fy}" rx="16.5" ry="21" fill="{SKIN}"/>
    <ellipse cx="{cx - 16.5:.1f}" cy="{fy + 2:.1f}" rx="2.5" ry="4" fill="{SKIN_SH}"/>
    <ellipse cx="{cx + 16.5:.1f}" cy="{fy + 2:.1f}" rx="2.5" ry="4" fill="{SKIN_SH}"/>
    <path d="M{cx - 11:.1f} {fy - 7:.1f}Q{cx - 7:.1f} {fy - 9.5:.1f} {cx - 3:.1f} {fy - 7.6:.1f}M{cx + 3:.1f} {fy - 7.6:.1f}Q{cx + 7:.1f} {fy - 9.5:.1f} {cx + 11:.1f} {fy - 7:.1f}" fill="none" stroke="{HAIR_DK}" stroke-width="1.9" stroke-linecap="round"/>
    <g style="{blink}">
      <ellipse cx="{cx - 7:.1f}" cy="{fy - 1:.1f}" rx="3.3" ry="2" fill="#F6EEE8"/><ellipse cx="{cx + 7:.1f}" cy="{fy - 1:.1f}" rx="3.3" ry="2" fill="#F6EEE8"/>
      <circle cx="{cx - 7:.1f}" cy="{fy - 1:.1f}" r="1.6" fill="#3B2316"/><circle cx="{cx + 7:.1f}" cy="{fy - 1:.1f}" r="1.6" fill="#3B2316"/>
    </g>
    <path d="M{cx - 10.5:.1f} {fy - 2.6:.1f}Q{cx - 7:.1f} {fy - 4.4:.1f} {cx - 3.5:.1f} {fy - 2.6:.1f}M{cx + 3.5:.1f} {fy - 2.6:.1f}Q{cx + 7:.1f} {fy - 4.4:.1f} {cx + 10.5:.1f} {fy - 2.6:.1f}" fill="none" stroke="{HAIR_DK}" stroke-width=".9" stroke-linecap="round"/>
    <path d="M{cx - 2.2:.1f} {fy + 6.5:.1f}Q{cx:.1f} {fy + 8:.1f} {cx + 2.2:.1f} {fy + 6.5:.1f}" fill="none" stroke="{SKIN_SH}" stroke-width="1" stroke-linecap="round"/>
    <path d="M{cx - 6:.1f} {fy + 10.5:.1f}Q{cx:.1f} {fy + 17:.1f} {cx + 6:.1f} {fy + 10.5:.1f}Q{cx:.1f} {fy + 12:.1f} {cx - 6:.1f} {fy + 10.5:.1f}Z" fill="#FFF8F4" stroke="#B9646E" stroke-width=".9" stroke-linejoin="round"/>
    <ellipse cx="{cx - 9.5:.1f}" cy="{fy + 6:.1f}" rx="3" ry="1.7" fill="#E07A7A" opacity=".3"/>
    <ellipse cx="{cx + 9.5:.1f}" cy="{fy + 6:.1f}" rx="3" ry="1.7" fill="#E07A7A" opacity=".3"/>
    <g fill="#A8705A" opacity=".45"><circle cx="{cx - 5:.1f}" cy="{fy + 3.5:.1f}" r=".5"/><circle cx="{cx - 3:.1f}" cy="{fy + 4.5:.1f}" r=".45"/><circle cx="{cx + 4:.1f}" cy="{fy + 3.8:.1f}" r=".5"/><circle cx="{cx + 6:.1f}" cy="{fy + 4.6:.1f}" r=".45"/></g>'''

def tile(r, c, i):
    x, y = X0 + c * (TW + GAP), Y0 + r * (TH + GAP)
    label, length = ROWS[r][c]
    style = STYLES[c]
    cx, top = x + TW / 2, y + 22
    clip = f"t{i}"
    sway = f"animation:balance 3.2s ease-in-out infinite alternate;animation-delay:{-(i * .53) % 3.2:.2f}s;transform-origin:{cx:.1f}px {top + 10:.1f}px"
    lab_w = TW - 14
    return f'''
<clipPath id="{clip}"><rect x="{x}" y="{y}" width="{TW}" height="{TH}" rx="8"/></clipPath>
<g clip-path="url(#{clip})">
  <rect x="{x}" y="{y}" width="{TW}" height="{TH}" fill="url(#cafe)"/>
  <g opacity=".35"><rect x="{x + 6}" y="{y + 18}" width="{TW - 12}" height="2.5" fill="#F3D9B8"/><rect x="{x + 6}" y="{y + 44}" width="{TW - 12}" height="2.5" fill="#F3D9B8"/>
  <circle cx="{x + 12}" cy="{y + 30}" r="4" fill="#FFE7C2"/><circle cx="{x + TW - 14}" cy="{y + 34}" r="5" fill="#FFE7C2"/></g>
  <rect x="{x}" y="{y + 104}" width="{TW}" height="{TH - 104}" fill="#3F7F8C" opacity=".55"/>
  <g style="{sway}"><path d="{back_hair(cx, top, length)}" fill="{HAIR}"/>
    <path d="M{cx - 24:.1f} {top + 50:.1f}Q{cx - 28:.1f} {top + length * .6:.1f} {cx - 22:.1f} {top + length - 8:.1f}M{cx + 24:.1f} {top + 50:.1f}Q{cx + 28:.1f} {top + length * .6:.1f} {cx + 22:.1f} {top + length - 8:.1f}" fill="none" stroke="{HAIR_HI}" stroke-width="1.2" opacity=".7"/></g>
  <path d="M{cx - 40:.1f} {y + TH}C{cx - 38:.1f} {top + 74:.1f} {cx - 22:.1f} {top + 64:.1f} {cx - 8:.1f} {top + 62:.1f}H{cx + 8:.1f}C{cx + 22:.1f} {top + 64:.1f} {cx + 38:.1f} {top + 74:.1f} {cx + 40:.1f} {y + TH}Z" fill="{SKIN}"/>
  <path d="M{cx - 30:.1f} {y + TH}C{cx - 28:.1f} {top + 92:.1f} {cx - 20:.1f} {top + 86:.1f} {cx:.1f} {top + 90:.1f}C{cx + 20:.1f} {top + 86:.1f} {cx + 28:.1f} {top + 92:.1f} {cx + 30:.1f} {y + TH}Z" fill="#F4EFE8"/>
  <path d="M{cx - 26:.1f} {top + 96:.1f}H{cx + 26:.1f}M{cx - 28:.1f} {top + 103:.1f}H{cx + 28:.1f}M{cx - 29:.1f} {top + 110:.1f}H{cx + 29:.1f}" stroke="#D9D0C4" stroke-width="1" stroke-dasharray="2 1.5"/>
  <path d="M{cx - 24:.1f} {top + 88:.1f}L{cx - 21:.1f} {top + 66:.1f}M{cx + 24:.1f} {top + 88:.1f}L{cx + 21:.1f} {top + 66:.1f}" stroke="#C4567A" stroke-width="2.4" stroke-linecap="round"/>
  {face(cx, top, i)}
  <g style="{sway}">{top_and_bangs(cx, top, style)}{front_locks(cx, top, length)}</g>
  <rect x="{x + 7}" y="{y + TH - 27}" width="{lab_w}" height="21" rx="4" fill="#F7EEE2" opacity=".95"/>
  <text x="{cx:.1f}" y="{y + TH - 18:.1f}" text-anchor="middle" font-family="{FONT_L}" font-size="7.4" fill="#4A3426">{label}</text>
  <text x="{cx:.1f}" y="{y + TH - 9.5:.1f}" text-anchor="middle" font-family="{FONT_L}" font-size="6.6" fill="#7A5E4A">{COLS_SHORT[c]}</text>
</g>
<rect x="{x}" y="{y}" width="{TW}" height="{TH}" rx="8" fill="none" stroke="#FFFFFF" stroke-width="3" style="animation:spot{i} {CYCLE}s linear infinite" opacity="0"/>'''

# roulette : 12 cases en 0-55 %, puis 2 tours rapides... on reste simple : un passage + arrêt
order = [0, 1, 2, 3, 7, 6, 5, 4, 8, 9, 10, 11, 8]
spot_css = []
step = 4.2
for i in range(12):
    slots = [k for k, t in enumerate(order) if t == i]
    frames = ["0%{opacity:0}"]
    for k in slots:
        a, b = k * step, k * step + step
        frames.append(f"{a:.1f}%{{opacity:0}}{a + .1:.1f}%{{opacity:1}}{b:.1f}%{{opacity:1}}{b + .1:.1f}%{{opacity:0}}")
    frames.append("100%{opacity:0}")
    spot_css.append(f"@keyframes spot{i}{{{''.join(frames)}}}")

tiles = "".join(tile(r, c, r * 4 + c) for r in range(3) for c in range(4))

# cercle rouge autour des deux favorites (ligne du bas, 2 premières colonnes)
fx0, fy0 = X0 - 3, Y0 + 2 * (TH + GAP) - 4
fx1, fy1 = X0 + 2 * TW + GAP + 4, Y0 + 3 * TH + 2 * GAP + 4
loop = (f"M{fx0 + 6:.1f} {fy0 + 6:.1f}C{fx0 + 60:.1f} {fy0 - 6:.1f} {fx1 - 50:.1f} {fy0 - 2:.1f} {fx1 + 1:.1f} {fy0 + 3:.1f}"
        f"C{fx1 + 4:.1f} {fy0 + 50:.1f} {fx1 + 2:.1f} {fy1 - 40:.1f} {fx1 - 2:.1f} {fy1 + 1:.1f}"
        f"C{fx1 - 60:.1f} {fy1 + 4:.1f} {fx0 + 50:.1f} {fy1 + 3:.1f} {fx0 + 1:.1f} {fy1 - 1:.1f}"
        f"C{fx0 - 3:.1f} {fy1 - 50:.1f} {fx0 - 2:.1f} {fy0 + 50:.1f} {fx0 + 2:.1f} {fy0 + 2:.1f}"
        f"C{fx0 + 4:.1f} {fy0 - 4:.1f} {fx0 + 14:.1f} {fy0 - 3:.1f} {fx0 + 24:.1f} {fy0 + 1:.1f}")
hx, hy = fx1 - 4, fy0 + 8

svg = f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 500" width="400" height="500">
<title>Toutes ses coupes de cheveux</title>
<defs>
  <linearGradient id="cafe" x1="0" y1="0" x2="0" y2="1">
    <stop offset="0" stop-color="#8A5A3A"/><stop offset=".45" stop-color="#5E3F2C"/><stop offset=".7" stop-color="#7A6A5A"/><stop offset="1" stop-color="#4E7F88"/>
  </linearGradient>
  <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>
  <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="ciseaux" d="M-6 6A3 3 0 1 0-6 6.01M6 6A3 3 0 1 0 6 6.01M-4 4L4-8M4 4L-4-8" />
</defs>
<style>
  @keyframes balance{{from{{transform:rotate(-1.6deg)}}to{{transform:rotate(1.8deg)}}}}
  @keyframes cligne{{0%,94%,100%{{transform:scaleY(1)}}97%{{transform:scaleY(.1)}}}}
  {"".join(spot_css)}
  .boucle{{stroke-dasharray:1;stroke-dashoffset:1;animation:boucle {CYCLE}s ease-in-out infinite}}
  @keyframes boucle{{0%,58%{{stroke-dashoffset:1;opacity:1}}72%,94%{{stroke-dashoffset:0;opacity:1}}100%{{stroke-dashoffset:0;opacity:0}}}}
  .pop{{animation:pop {CYCLE}s ease-out infinite;transform-box:fill-box;transform-origin:center}}
  @keyframes pop{{0%,70%{{transform:scale(0);opacity:0}}76%{{transform:scale(1.3);opacity:1}}80%,92%{{transform:scale(1);opacity:1}}100%{{transform:scale(1);opacity:0}}}}
  .clic{{animation:clic 1.2s ease-in-out infinite alternate;transform-origin:0 0}}
  @keyframes clic{{from{{transform:rotate(-10deg)}}to{{transform:rotate(10deg)}}}}
</style>

<rect width="400" height="500" fill="#F7EFE6"/>
<text x="200" y="27" text-anchor="middle" font-family="{FONT_L}" font-style="italic" font-size="19" fill="#4A3426">Laquelle, mon amour ?</text>
<g transform="translate(58 20)" fill="none" stroke="#C4567A" stroke-width="1.4" stroke-linecap="round"><g class="clic"><use href="#ciseaux"/></g></g>
<g transform="translate(342 20) scale(-1 1)" fill="none" stroke="#C4567A" stroke-width="1.4" stroke-linecap="round"><g class="clic" style="animation-delay:-.6s"><use href="#ciseaux"/></g></g>
{tiles}

<!-- le cercle rouge autour de ses deux préférées -->
<path d="{loop}" pathLength="1" class="boucle" fill="none" stroke="#E5483E" stroke-width="4.5" stroke-linecap="round" stroke-linejoin="round"/>
<g filter="url(#lueur)" fill="#E5483E">
  <g transform="translate({hx:.1f} {hy:.1f}) scale(1.6)"><use href="#coeur" class="pop"/></g>
  <g transform="translate({hx - 18:.1f} {hy - 8:.1f})"><use href="#coeur" class="pop" style="animation-delay:.15s"/></g>
</g>
</svg>
'''
open(out, "w").write(svg)
print("ok", len(svg))
