"""Remplace le chien de illustrations/05-chien-rose.svg par un gros chien blanc tout fluffy
(façon samoyède) : oreilles pointues, museau, sourire de chien, fourrure en touffes.
Le décor (ciel, prairie) et les pétales sont repris du fichier existant."""
import math, random, re, sys

path = sys.argv[1]
src = open(path).read()
random.seed(7)

FUR = "#FBF8F3"; FUR_SH = "#E2D9CC"; FUR_DK = "#CFC4B4"; RIM = "#FFB86B"

def tufts(cx, cy, rx_fn, ry, n, spike, jitter=.35, start=0, end=2 * math.pi):
    """contour fermé en touffes de poils autour d'une forme ovale."""
    pts = []
    for i in range(n + 1):
        t = start + (end - start) * i / n
        rx = rx_fn(t)
        pts.append((cx + rx * math.cos(t), cy + ry * math.sin(t), t))
    d = f"M{pts[0][0]:.1f} {pts[0][1]:.1f}"
    for (x0, y0, t0), (x1, y1, t1) in zip(pts, pts[1:]):
        tm = (t0 + t1) / 2
        s = spike * (1 + random.uniform(-jitter, jitter))
        # pointe de la touffe : vers l'extérieur et un peu « peignée » vers le bas
        mx, my = (x0 + x1) / 2, (y0 + y1) / 2
        nx, ny = math.cos(tm), math.sin(tm)
        tx, ty = mx + nx * s + random.uniform(-2, 2), my + ny * s + s * .35
        d += f"Q{tx:.1f} {ty:.1f} {x1:.1f} {y1:.1f}"
    return d + "Z"

def fur_strokes(cx, cy, rx, ry, n, length, color, width=1.3, inner=.55, outer=.95):
    """petites mèches dessinées à l'intérieur de la fourrure."""
    out = []
    for _ in range(n):
        t = random.uniform(0, 2 * math.pi)
        k = random.uniform(inner, outer)
        x, y = cx + rx * k * math.cos(t), cy + ry * k * math.sin(t)
        L = length * random.uniform(.6, 1.2)
        ex, ey = x + math.cos(t) * L, y + math.sin(t) * L + L * .4
        bx, by = (x + ex) / 2 + random.uniform(-3, 3), (y + ey) / 2
        out.append(f"M{x:.1f} {y:.1f}Q{bx:.1f} {by:.1f} {ex:.1f} {ey:.1f}")
    return f'<path d="{"".join(out)}" fill="none" stroke="{color}" stroke-width="{width}" stroke-linecap="round"/>'

# --- formes ---
ruff = tufts(200, 452, lambda t: 190, 150, 70, 13)
head_rx = lambda t: 112 + 18 * max(0, math.sin(t)) ** 1.5   # joues plus larges en bas
head = tufts(200, 214, head_rx, 112, 64, 10)
cheekL = tufts(118, 300, lambda t: 46, 40, 22, 9)
cheekR = tufts(282, 300, lambda t: 46, 40, 22, 9)

def ear(sx):
    """oreille pointue et duveteuse ; sx = -1 gauche, 1 droite."""
    bx0, bx1, by = 200 + sx * 44, 200 + sx * 108, 150
    tip = (200 + sx * 98, 52)
    pts = [(bx0, by), tip, (bx1, by + 10)]
    # bord extérieur en touffes
    outer = f"M{bx0:.1f} {by:.1f}Q{200 + sx * 62:.1f} {80:.1f} {tip[0]:.1f} {tip[1]:.1f}"
    n = 7
    for i in range(1, n + 1):
        t = i / n
        x = tip[0] + (bx1 - tip[0]) * t
        y = tip[1] + (by + 10 - tip[1]) * t
        px = (tip[0] + (bx1 - tip[0]) * (t - .5 / n)) + sx * 7
        py = (tip[1] + (by + 10 - tip[1]) * (t - .5 / n)) - 2
        outer += f"Q{px:.1f} {py:.1f} {x:.1f} {y:.1f}"
    outer += "Z"
    inner = (f"M{200 + sx * 56:.1f} {by - 2:.1f}Q{200 + sx * 70:.1f} {96:.1f} {200 + sx * 94:.1f} {70:.1f}"
             f"Q{200 + sx * 100:.1f} {110:.1f} {200 + sx * 96:.1f} {by - 4:.1f}Z")
    fuzz = "".join(f"M{200 + sx * (62 + 6 * k):.1f} {by - 8 - 4 * k:.1f}q{sx * 4:.1f} -10 {sx * 2:.1f} -18" for k in range(4))
    cls = "oreilleG" if sx < 0 else "oreilleD"
    return (f'<g class="{cls}"><path d="{outer}" fill="{FUR}"/>'
            f'<path d="{outer}" fill="none" stroke="{RIM}" stroke-width="3" opacity=".55" filter="url(#flou)"/>'
            f'<path d="{inner}" fill="#F2B8B0"/><path d="{fuzz}" fill="none" stroke="{FUR}" stroke-width="2" stroke-linecap="round"/></g>')

muzzle = ("M156 214C146 240 132 278 138 306C146 334 254 334 262 306C268 278 254 240 244 214"
          "Q222 204 200 206Q178 204 156 214Z")

dog = f'''<!-- ====== LE CHIEN (tout fluffy) ====== -->
<g class="fluff" style="transform-origin:200px 500px">
  <path d="{ruff}" fill="url(#poil)"/>
  <path d="{ruff}" fill="none" stroke="{RIM}" stroke-width="4" opacity=".5" filter="url(#flou)"/>
  {fur_strokes(200, 452, 190, 150, 70, 14, FUR_SH, 1.4, .3, .92)}
  <path d="M168 488Q200 498 232 488L236 500H164Z" fill="#2B8FB0"/>
</g>

<g class="tete">
  {ear(-1)}{ear(1)}

  <!-- tête et joues en touffes -->
  <path d="{head}" fill="url(#poil)"/>
  <path d="{head}" fill="none" stroke="{RIM}" stroke-width="4" opacity=".55" filter="url(#flou)"/>
  <path d="{cheekL}" fill="{FUR}"/><path d="{cheekR}" fill="{FUR}"/>
  {fur_strokes(200, 214, 120, 112, 60, 11, FUR_SH, 1.3, .62, .96)}
  {fur_strokes(118, 300, 46, 40, 14, 9, FUR_SH, 1.2, .3, .9)}
  {fur_strokes(282, 300, 46, 40, 14, 9, FUR_SH, 1.2, .3, .9)}
  <path d="M150 140q10-8 22-4M228 136q12-4 22 4M186 128q14-6 28 0" fill="none" stroke="{FUR_SH}" stroke-width="1.4" stroke-linecap="round"/>

  <!-- yeux en amande, cerclés de noir -->
  <ellipse cx="152" cy="188" rx="24" ry="16" fill="{FUR_SH}" opacity=".55"/>
  <ellipse cx="248" cy="188" rx="24" ry="16" fill="{FUR_SH}" opacity=".55"/>
  <g class="cligne" style="transform-origin:154px 190px">
    <path d="M136 194Q150 176 172 186Q164 200 136 194Z" fill="#1A1210" stroke="#3A2A26" stroke-width="2" stroke-linejoin="round"/>
    <circle cx="159" cy="187" r="2.6" fill="#FFFFFF"/><circle cx="153" cy="191" r="1" fill="#FFFFFF" opacity=".7"/>
  </g>
  <g class="cligne" style="transform-origin:246px 190px">
    <path d="M264 194Q250 176 228 186Q236 200 264 194Z" fill="#1A1210" stroke="#3A2A26" stroke-width="2" stroke-linejoin="round"/>
    <circle cx="241" cy="187" r="2.6" fill="#FFFFFF"/><circle cx="247" cy="191" r="1" fill="#FFFFFF" opacity=".7"/>
  </g>

  <!-- museau qui avance -->
  <path d="{muzzle}" fill="#FFFFFF"/>
  <path d="M156 214C146 240 132 278 138 306M244 214C254 240 268 278 262 306" fill="none" stroke="{FUR_SH}" stroke-width="2.4" stroke-linecap="round"/>
  <g fill="#8A7A70" opacity=".5"><circle cx="160" cy="276" r="1.1"/><circle cx="168" cy="284" r="1.1"/><circle cx="158" cy="290" r="1.1"/><circle cx="240" cy="276" r="1.1"/><circle cx="232" cy="284" r="1.1"/><circle cx="242" cy="290" r="1.1"/></g>

  <!-- grosse truffe de chien -->
  <g class="renifle">
    <path d="M158 238C156 218 244 218 242 238C244 262 222 282 200 284C178 282 156 262 158 238Z" fill="url(#truffe)"/>
    <ellipse cx="192" cy="228" rx="22" ry="7" fill="#B88078" opacity=".5"/>
    <path d="M170 256Q178 244 191 255Q186 263 177 262Q170 261 170 256Z" fill="#1E1010"/>
    <path d="M230 256Q222 244 209 255Q214 263 223 262Q230 261 230 256Z" fill="#1E1010"/>
    <path d="M200 262V284" stroke="#2A1614" stroke-width="1.6"/>
    <g transform="translate(182 226)" fill="#FFFFFF"><use href="#eclat" class="tw"/></g>
  </g>

  <!-- sourire de chien (forme de Y), langue rose -->
  <path d="M162 304Q200 334 238 304Q232 338 200 346Q168 338 162 304Z" fill="#3A1A1A"/>
  <path d="M182 322Q200 318 218 322Q224 348 210 360Q200 366 190 360Q176 348 182 322Z" fill="#E8828C"/>
  <path d="M200 326V352" stroke="#C9646E" stroke-width="1.4" stroke-linecap="round"/>
  <path d="M170 310l3 7 3-6ZM230 310l-3 7-3-6Z" fill="#FFFFFF"/>
  <path d="M200 284V300M200 300Q182 318 156 300M200 300Q218 318 244 300" fill="none" stroke="#2A1414" stroke-width="2.6" stroke-linecap="round"/>
  <path d="M156 300q-6-3-8-9M244 300q6-3 8-9" fill="none" stroke="#2A1414" stroke-width="2" stroke-linecap="round"/>
  <!-- la rose tenue entre les dents -->
  __ROSE__
</g>
'''

# reprend la rose existante et la recale sur la nouvelle bouche
rose = re.search(r'<!-- la rose tenue entre les dents -->\s*(<g class="rose">.*?</g>\s*</g>)', src, re.S).group(1)
rose = rose.replace('M104 320Q200 306 292 298', 'M112 314Q200 300 292 296')
dog = dog.replace("__ROSE__", rose)

a = src.index("<!-- ====== LE CHIEN ====== -->") if "<!-- ====== LE CHIEN ====== -->" in src else src.index("<!-- ====== LE CHIEN (tout fluffy) ====== -->")
b = src.index("<!-- pétales qui s'envolent")
src = src[:a] + dog + "\n" + src[b:]

# oreilles : nouveaux points de pivot + respiration de la fourrure
src = src.replace("transform-origin:110px 150px", "transform-origin:140px 150px").replace("transform-origin:290px 150px", "transform-origin:260px 150px")
if ".fluff{" not in src:
    src = src.replace("</style>", "  .fluff{animation:fluff 3s ease-in-out infinite}\n  @keyframes fluff{0%,100%{transform:scale(1)}50%{transform:scale(1.015,1.025)}}\n</style>")
open(path, "w").write(src)
print("ok", len(src))
