#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""渚神护佑 · 良渚耳环背贴卡 三色版 SVG 生成器
几何同源，仅色彩映射不同。坐标单位 mm，viewBox 0 0 75 98。
"""
import math
import pathlib

ROOT = pathlib.Path("/Users/bot1/Volumes/root_for_ai/AI工作区/良渚_耳环背贴_渚神护佑三色版_20260611_2149")
OUT = ROOT / "deliverables" / "claude_v01"
OUT.mkdir(parents=True, exist_ok=True)
B64 = (ROOT / "work" / "claude_v01_build" / "nss.b64").read_text().strip().replace("\n", "")

CX, CY = 37.5, 56.0          # 环带圆心
OUTER = (32.0, 36.0)          # 外弦纹 rx/ry
INNER = (22.0, 26.0)          # 内弦纹 rx/ry
FONT = "'Noto Serif SC','Songti SC','STSong',serif"

VARIANTS = {
    "A": dict(name="抱玉朱", bg="#A94033", line="#F7F6F2", accent="#DDCCAC",
              engraved=0.30, huang_fill=True, bird_tip=False),
    "B": dict(name="璧青",   bg="#58695D", line="#F7F6F2", accent="#BD8537",
              engraved=0.30, huang_fill=False, bird_tip=True),
    "C": dict(name="鸡骨白", bg="#F7F6F2", line="#302F2E", accent="#A94033",
              engraved=0.25, huang_fill=False, bird_tip=False),
}


def f(x):
    return f"{x:.2f}".rstrip("0").rstrip(".")


def ept(rx, ry, deg):
    r = math.radians(deg)
    return (CX + rx * math.cos(r), CY + ry * math.sin(r))


def spiral_path(cx, cy, r0, mirror=1):
    """小卷云：半圆弧链螺线"""
    radii = [r0, r0 * 0.66, r0 * 0.44, r0 * 0.27]
    d = f"M{f(cx + mirror * radii[0])},{f(cy)}"
    sign, prev = -1, radii[0]
    sweep = 1 if mirror > 0 else 0
    for r in radii[1:]:
        R = (prev + r) / 2
        d += f" A{f(R)},{f(R)} 0 0 {sweep} {f(cx + mirror * sign * r)},{f(cy)}"
        prev = r
        sign *= -1
    return d


def station(rx, ry, deg, jitter=0.0, rot_override=None):
    x, y = ept(rx, ry, deg)
    rot = (deg - 270 + jitter) if rot_override is None else rot_override
    return f'transform="translate({f(x)},{f(y)}) rotate({f(rot)})"'


# ──────────────────────────── 母题 ────────────────────────────

def motif_face(v):
    """一级 · 神人兽面（羽冠+重圈眼+阔嘴）· 12点位 · 压弦纹之上"""
    L, A, BG, E = v["line"], v["accent"], v["bg"], v["engraved"]
    el = [f'<ellipse cx="0" cy="-0.3" rx="6.7" ry="5.7" fill="{BG}"/>']
    # 羽冠：放射阴刻线 + 冠底弧
    ccx, ccy, r_in, r_out = 0.0, 1.2, 4.6, 6.9
    for i in range(7):
        a = math.radians(-125 + i * (70 / 6))
        x1, y1 = ccx + r_in * math.cos(a), ccy + r_in * math.sin(a)
        x2, y2 = ccx + r_out * math.cos(a), ccy + r_out * math.sin(a)
        el.append(f'<path d="M{f(x1)},{f(y1)} L{f(x2)},{f(y2)}" stroke="{L}" stroke-width="0.35" stroke-linecap="round"/>')
    a0, a1 = math.radians(-127), math.radians(-53)
    p0 = (ccx + r_in * math.cos(a0), ccy + r_in * math.sin(a0))
    p1 = (ccx + r_in * math.cos(a1), ccy + r_in * math.sin(a1))
    el.append(f'<path d="M{f(p0[0])},{f(p0[1])} A{f(r_in)},{f(r_in)} 0 0 1 {f(p1[0])},{f(p1[1])}" stroke="{L}" stroke-width="0.35" fill="none"/>')
    # 面廓
    el.append(f'<path d="M-5.2,-2 L5.2,-2 L4.3,4.5 Q0,5.7 -4.3,4.5 Z" stroke="{L}" stroke-width="0.5" fill="none" stroke-linejoin="round"/>')
    # 重圈眼 + 眼角线
    for s in (-1, 1):
        el.append(f'<circle cx="{f(2.3*s)}" cy="0.4" r="1.55" stroke="{L}" stroke-width="0.35" fill="none"/>')
        el.append(f'<circle cx="{f(2.3*s)}" cy="0.4" r="0.85" stroke="{L}" stroke-width="{E}" fill="none"/>')
        el.append(f'<circle cx="{f(2.3*s)}" cy="0.4" r="0.5" fill="{A}"/>')
        el.append(f'<path d="M{f(3.9*s)},0.2 L{f(4.85*s)},-0.25" stroke="{L}" stroke-width="{E}" stroke-linecap="round"/>')
        el.append(f'<path d="M{f(3.3*s)},2.6 Q{f(4.4*s)},3.4 {f(3.5*s)},4.4" stroke="{L}" stroke-width="{E}" fill="none" stroke-linecap="round"/>')
    # 鼻梁 + 阔嘴 + 獠牙
    el.append(f'<path d="M-1,2.1 L1,2.1" stroke="{L}" stroke-width="0.35" stroke-linecap="round"/>')
    el.append(f'<rect x="-2.7" y="3.1" width="5.4" height="1.3" rx="0.65" stroke="{L}" stroke-width="0.35" fill="none"/>')
    el.append(f'<path d="M-1.5,3.1 L-1.5,4.4 M1.5,3.1 L1.5,4.4" stroke="{L}" stroke-width="{E}"/>')
    return f'<g {station(27, 31, 270)}>' + "".join(el) + "</g>"


def motif_cong(v, deg, jitter):
    """二级 · 玉琮节角 · 3/9点位 · 压弦纹之上"""
    L, A, BG, E = v["line"], v["accent"], v["bg"], v["engraved"]
    el = [f'<rect x="-4" y="-6.1" width="8" height="12.2" rx="1" fill="{BG}"/>']
    el.append(f'<rect x="-3.6" y="-5.8" width="7.2" height="11.6" rx="0.9" stroke="{L}" stroke-width="0.5" fill="none"/>')
    for y in (-4.1, -3.4, -2.3, -1.6):
        el.append(f'<path d="M-2.7,{f(y)} L2.7,{f(y)}" stroke="{L}" stroke-width="{E}" stroke-linecap="round"/>')
    for s in (-1, 1):
        el.append(f'<circle cx="{f(1.55*s)}" cy="1" r="1.05" stroke="{L}" stroke-width="0.35" fill="none"/>')
        el.append(f'<circle cx="{f(1.55*s)}" cy="1" r="0.55" stroke="{L}" stroke-width="{E}" fill="none"/>')
        el.append(f'<circle cx="{f(1.55*s)}" cy="1" r="0.3" fill="{A}"/>')
    el.append(f'<path d="M-0.9,3 L0.9,3" stroke="{L}" stroke-width="0.35" stroke-linecap="round"/>')
    el.append(f'<path d="M-0.6,4 L0.6,4" stroke="{L}" stroke-width="{E}" stroke-linecap="round"/>')
    return f'<g {station(27, 31, deg, jitter)}>' + "".join(el) + "</g>"


def motif_huang(v, deg, jitter):
    """二级 · 玉璜弧线 · 4:30/7:30点位 · 穿弦纹之下（外弦纹压其上）"""
    L, A, E = v["line"], v["accent"], v["engraved"]
    fill = A if v["huang_fill"] else "none"
    ccx, ccy, ro, ri = 0.0, 2.2, 6.4, 3.9
    a_out0, a_out1 = math.radians(215), math.radians(325)
    o0 = (ccx + ro * math.cos(a_out0), ccy + ro * math.sin(a_out0))
    o1 = (ccx + ro * math.cos(a_out1), ccy + ro * math.sin(a_out1))
    i0 = (ccx + ri * math.cos(a_out0), ccy + ri * math.sin(a_out0))
    i1 = (ccx + ri * math.cos(a_out1), ccy + ri * math.sin(a_out1))
    d = (f"M{f(o0[0])},{f(o0[1])} A{f(ro)},{f(ro)} 0 0 1 {f(o1[0])},{f(o1[1])} "
         f"L{f(i1[0])},{f(i1[1])} A{f(ri)},{f(ri)} 0 0 0 {f(i0[0])},{f(i0[1])} Z")
    el = [f'<path d="{d}" stroke="{L}" stroke-width="0.5" fill="{fill}" stroke-linejoin="round"/>']
    for r_mid in (4.7, 5.5):
        m0 = (ccx + r_mid * math.cos(math.radians(230)), ccy + r_mid * math.sin(math.radians(230)))
        m1 = (ccx + r_mid * math.cos(math.radians(310)), ccy + r_mid * math.sin(math.radians(310)))
        el.append(f'<path d="M{f(m0[0])},{f(m0[1])} A{f(r_mid)},{f(r_mid)} 0 0 1 {f(m1[0])},{f(m1[1])}" stroke="{L}" stroke-width="{E}" fill="none"/>')
    for s in (-1, 1):
        el.append(f'<circle cx="{f(4.1*s)}" cy="-0.6" r="0.42" stroke="{L}" stroke-width="{E}" fill="none"/>')
    return f'<g {station(29.5, 33.5, deg, jitter)}>' + "".join(el) + "</g>"


def motif_connector(v, deg, jitter):
    """三级 · 重圈眼+小卷云 · 1:30/10:30点位 · 穿弦纹之下"""
    L, A, E = v["line"], v["accent"], v["engraved"]
    el = [f'<circle cx="0" cy="0" r="1.7" stroke="{L}" stroke-width="0.35" fill="none"/>',
          f'<circle cx="0" cy="0" r="0.95" stroke="{L}" stroke-width="{E}" fill="none"/>',
          f'<circle cx="0" cy="0" r="0.52" fill="{A}"/>']
    for s in (-1, 1):
        el.append(f'<path d="{spiral_path(3.5*s, 0.3, 1.3, mirror=s)}" stroke="{L}" stroke-width="{E}" fill="none" stroke-linecap="round"/>')
    return f'<g {station(30.8, 34.8, deg, jitter)}>' + "".join(el) + "</g>"


def motif_birds(v):
    """二级 · 神鸟一对 · 6点位 · 尾羽交叉收口 · 压内弦纹之上"""
    L, A, BG, E = v["line"], v["accent"], v["bg"], v["engraved"]
    bird = [
        f'<circle cx="-5.8" cy="-1.6" r="1.7" fill="{BG}"/>',
        f'<ellipse cx="-3" cy="-0.2" rx="2.9" ry="2" fill="{BG}" transform="rotate(-14 -3 -0.2)"/>',
        f'<circle cx="-5.8" cy="-1.6" r="1.05" stroke="{L}" stroke-width="0.35" fill="none"/>',
        f'<circle cx="-5.65" cy="-1.75" r="0.3" fill="{L}"/>',
        f'<path d="M-6.8,-1.9 L-7.75,-1.55 M-6.85,-1.45 L-7.75,-1.55" stroke="{L}" stroke-width="{E}" stroke-linecap="round" fill="none"/>',
        f'<ellipse cx="-3" cy="-0.2" rx="2.35" ry="1.45" stroke="{L}" stroke-width="0.35" fill="none" transform="rotate(-14 -3 -0.2)"/>',
        f'<path d="M-4.7,-0.7 Q-3.1,-1.75 -1.5,-0.85" stroke="{L}" stroke-width="{E}" fill="none" stroke-linecap="round"/>',
        f'<path d="M-4.5,-0.15 Q-3,-1.1 -1.6,-0.3" stroke="{L}" stroke-width="{E}" fill="none" stroke-linecap="round"/>',
        f'<path d="M-1,0.5 C0.6,1.3 2.4,2.1 4.5,2.45" stroke="{L}" stroke-width="0.35" fill="none" stroke-linecap="round"/>',
        f'<path d="M-1.3,1 C0.3,1.75 2,2.5 4.1,2.95" stroke="{L}" stroke-width="{E}" fill="none" stroke-linecap="round"/>',
    ]
    if v["bird_tip"]:
        bird.append(f'<circle cx="4.75" cy="2.6" r="0.38" fill="{A}"/>')
    b = "".join(bird)
    return (f'<g transform="translate(37.5,82.5)">'
            f'<g>{b}</g><g transform="scale(-1,1)">{b}</g></g>')


def motif_filler(v, deg, jitter, mirror=1):
    """三级 · 小卷云填充"""
    L, E = v["line"], v["engraved"]
    return (f'<g {station(27, 31, deg, jitter)}>'
            f'<path d="{spiral_path(0, 0, 1.25, mirror=mirror)}" stroke="{L}" stroke-width="{E}" fill="none" stroke-linecap="round"/>'
            f"</g>")


def motif_arcgroup(v, deg, half=6.5):
    """三级 · 细密平行阴刻短弧组（沿带向三道）"""
    L, E = v["line"], v["engraved"]
    el = []
    for dr in (-2.2, 0.0, 2.2):
        rx, ry = 27 + dr, 31 + dr
        p0, p1 = ept(rx, ry, deg - half), ept(rx, ry, deg + half)
        el.append(f'<path d="M{f(p0[0])},{f(p0[1])} A{f(rx)},{f(ry)} 0 0 1 {f(p1[0])},{f(p1[1])}" stroke="{L}" stroke-width="{E}" fill="none" stroke-linecap="round"/>')
    return "".join(el)


# ──────────────────────────── 弦纹 ────────────────────────────

def chords(v):
    L = v["line"]
    el = [f'<ellipse cx="{f(CX)}" cy="{f(CY)}" rx="{f(OUTER[0])}" ry="{f(OUTER[1])}" stroke="{L}" stroke-width="0.35" fill="none"/>']
    # 内弦纹分四段（留白区四角处断开），断口圆头收尾
    for d0, d1 in ((46.8, 133.2), (158.4, 201.6), (226.8, 313.2), (338.4, 381.6)):
        p0, p1 = ept(*INNER, d0), ept(*INNER, d1)
        el.append(f'<path d="M{f(p0[0])},{f(p0[1])} A{f(INNER[0])},{f(INNER[1])} 0 0 1 {f(p1[0])},{f(p1[1])}" stroke="{L}" stroke-width="0.35" fill="none" stroke-linecap="round"/>')
    return "".join(el)


# ──────────────────────────── 整卡 ────────────────────────────

def build(vid):
    v = VARIANTS[vid]
    L, A, BG = v["line"], v["accent"], v["bg"]

    under = (motif_connector(v, 315, 7) + motif_connector(v, 225, -7)
             + motif_huang(v, 45, 5) + motif_huang(v, 135, -5)
             + motif_filler(v, 329, 5) + motif_filler(v, 211, -5, mirror=-1)
             + motif_filler(v, 29, -6) + motif_filler(v, 151, 6, mirror=-1)
             + motif_filler(v, 67, 4) + motif_filler(v, 113, -4, mirror=-1)
             + motif_arcgroup(v, 17) + motif_arcgroup(v, 163)
             + motif_arcgroup(v, 197) + motif_arcgroup(v, 343)
             + motif_arcgroup(v, 292, half=5) + motif_arcgroup(v, 248, half=5))
    over = (motif_face(v) + motif_cong(v, 0, 4) + motif_cong(v, 180, -4)
            + motif_birds(v))

    svg = f'''<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="75mm" height="98mm" viewBox="0 0 75 98">
<title>渚神护佑</title>
<style>
@font-face{{font-family:'Noto Serif SC';src:url(data:font/woff2;base64,{B64}) format('woff2');font-weight:400 900;}}
text{{font-family:{FONT};}}
</style>
<defs>
<mask id="safe-zone">
<rect x="-1" y="-1" width="77" height="100" fill="#fff"/>
<rect x="17.5" y="38" width="40" height="36" fill="#000"/>
</mask>
</defs>
<rect id="card-bg" x="0" y="0" width="75" height="98" fill="{BG}"/>
<g id="ring-band" mask="url(#safe-zone)">
{under}
{chords(v)}
{over}
</g>
<text id="card-title" x="38.08" y="18.2" font-size="9" font-weight="900" letter-spacing="1.15" text-anchor="middle" fill="{L}">渚神护佑</text>
<g id="seal">
<rect x="59.2" y="14.7" width="3.5" height="3.5" rx="0.3" fill="{A}"/>
<text x="60.95" y="17.55" font-size="2.55" font-weight="900" text-anchor="middle" fill="{BG}">渚</text>
</g>
<g id="footer">
<rect x="16.6" y="90.2" width="41.8" height="3.8" fill="{BG}"/>
<text x="37.72" y="92.9" font-size="2.2" font-weight="400" letter-spacing="0.45" text-anchor="middle" fill="{L}">良渚文化 · LIANGZHU CULTURE</text>
</g>
<g id="earring-holes" fill="none" stroke="{L}" stroke-width="0.2">
<circle cx="27.5" cy="50" r="0.75"/>
<circle cx="47.5" cy="50" r="0.75"/>
</g>
</svg>
'''
    (OUT / f"{vid}.svg").write_text(svg, encoding="utf-8")
    print(f"{vid}.svg  written  ({len(svg)} bytes)")


for vid in "ABC":
    build(vid)
