"""
powpow_logo.py — PowPow 标志的 SDF（有向距离场）参数化引擎。

这是 cis/index.html 里「参数化标志 Parametric Logo」小节所展示字标的**唯一生成源**。
页面上的内联 SVG 全部由本文件 + params.json 算出，禁止手改 SVG 数字。

核心思想：整幅标志是一个标量函数

    L(x, y) = min( d_ring, d_P1, d_o1, d_w1, d_P2, d_o2, d_w2 )
    着色条件：L(x, y) <= 0

每个 d_g 是部件的有向距离（内部为负、外部为正），min() 对应几何并集。

四个原语（都有闭式解析解）：
    sd_segment  点到线段的距离
    sd_capsule  胶囊 = 圆头笔画            d = dist(点,线段) - r
    sd_arc      圆弧笔画                    d = |ρ - R| - h
    sd_ellipse_band 椭圆环                  d = max(外椭圆SDF, -内椭圆SDF)

坐标约定：画布像素坐标，原点在左上角，X 向右、Y 向下（与 SVG 一致）。
"""

from __future__ import annotations

import json
import math
import os
from typing import Dict

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
PARAMS_FILE = os.path.join(HERE, "params.json")

# 画布与标志外接框（与 logo-brand-pw9k.svg 的 viewBox 对齐）
CANVAS = [2048, 768]
WORDMARK_VIEWBOX = "180 205 1688 358"
BRAND_RED = "#B22222"        # 页面品牌红（与 CSS 变量 --red 一致）


# --------------------------------------------------------------------------------------
# 参数
# --------------------------------------------------------------------------------------

def load_params(path: str | None = None) -> Dict:
    """读取 params.json —— 全站唯一的参数真源。"""
    with open(path or PARAMS_FILE, encoding="utf-8") as f:
        p = json.load(f)
    p.setdefault("canvas", CANVAS)
    p.setdefault("color", BRAND_RED)
    return p


# --------------------------------------------------------------------------------------
# 一、基础 SDF 原语
# --------------------------------------------------------------------------------------

def sd_segment(X: np.ndarray, Y: np.ndarray,
               ax: float, ay: float, bx: float, by: float) -> np.ndarray:
    """点到线段的最短距离。"""
    pax, pay = X - ax, Y - ay
    bax, bay = bx - ax, by - ay
    h = np.clip((pax * bax + pay * bay) / (bax * bax + bay * bay), 0.0, 1.0)
    return np.hypot(pax - bax * h, pay - bay * h)


def sd_capsule(X: np.ndarray, Y: np.ndarray,
               ax: float, ay: float, bx: float, by: float, r: float) -> np.ndarray:
    """胶囊体（圆头线段）的 SDF：dist(点, 线段) - r。内部为负。"""
    return sd_segment(X, Y, ax, ay, bx, by) - r


def sd_arc(X: np.ndarray, Y: np.ndarray,
           cx: float, cy: float, R: float, th0: float, th1: float, h: float) -> np.ndarray:
    """圆弧笔画的 SDF：圆心 (cx,cy)、骨架半径 R、角域 [th0,th1]、半线宽 h。

        ρ = |p-c|, θ = atan2(p-c)
        θ∈[th0,th1] 时：d = |ρ-R| - h        （到圆弧带的最短距离）
        否则：          d = min(|p-e0|,|p-e1|) - h  （到弧端点的胶囊距离）
    """
    dx, dy = X - cx, Y - cy
    rho = np.hypot(dx, dy)
    th = np.arctan2(dy, dx)
    d_band = np.abs(rho - R) - h
    e0 = (cx + R * math.cos(th0), cy + R * math.sin(th0))
    e1 = (cx + R * math.cos(th1), cy + R * math.sin(th1))
    d_end = np.minimum(np.hypot(X - e0[0], Y - e0[1]),
                       np.hypot(X - e1[0], Y - e1[1])) - h
    inside = (th >= th0) & (th <= th1)
    return np.where(inside, np.minimum(d_band, d_end), d_end)


def sd_ellipse_band(X: np.ndarray, Y: np.ndarray,
                    cx: float, cy: float,
                    rxo: float, ryo: float, rxi: float, ryi: float) -> np.ndarray:
    """椭圆环的 SDF：max(外椭圆SDF, -内椭圆SDF)。"""
    s_out = (np.hypot((X - cx) / rxo, (Y - cy) / ryo) - 1.0) * min(rxo, ryo)
    s_in = (np.hypot((X - cx) / rxi, (Y - cy) / ryi) - 1.0) * min(rxi, ryi)
    return np.maximum(s_out, -s_in)


# --------------------------------------------------------------------------------------
# 二、字形 → SDF
# --------------------------------------------------------------------------------------

def glyph_sdf(g: Dict, X: np.ndarray, Y: np.ndarray) -> np.ndarray:
    """单个字形的有向距离场（内部为负）。"""
    t = g["type"]
    if t == "P":
        # 竖笔画（胶囊）
        d = sd_capsule(X, Y, g["sx"], g["y0"], g["sx"], g["y1"], g["rs"])
        # 碗形笔画：上横线 + 右半圆弧 + 下横线，圆头连接
        bx, by, R, h = g["bx"], g["by"], g["R"], g["h"]
        d = np.minimum(d, sd_capsule(X, Y, g["sx"], by - R, bx, by - R, h))
        d = np.minimum(d, sd_arc(X, Y, bx, by, R, -math.pi / 2, math.pi / 2, h))
        d = np.minimum(d, sd_capsule(X, Y, bx, by + R, g["sx"], by + R, h))
        return d
    if t == "o":
        rho = np.hypot(X - g["cx"], Y - g["cy"])
        return np.abs(rho - g["R"]) - g["h"]
    if t == "w":
        pts = g["pts"]
        d = np.full(X.shape, 1e9)
        for (ax, ay), (bx, by) in zip(pts[:-1], pts[1:]):
            d = np.minimum(d, sd_capsule(X, Y, ax, ay, bx, by, g["r"]))
        return d
    raise ValueError(f"unknown glyph type: {t}")


def logo_sdf(params: Dict, X: np.ndarray, Y: np.ndarray) -> np.ndarray:
    """整幅标志的 SDF：所有部件取 min（几何并集）。"""
    r = params["ring"]
    d = sd_ellipse_band(X, Y, r["cx"], r["cy"], r["rxo"], r["ryo"], r["rxi"], r["ryi"])
    for g in params["glyphs"]:
        d = np.minimum(d, glyph_sdf(g, X, Y))
    return d


# --------------------------------------------------------------------------------------
# 三、等比缩放
# --------------------------------------------------------------------------------------

def scale_params(params: Dict, s: float, canvas: bool = True) -> Dict:
    """返回等比放大/缩小 s 倍的参数字典。

    SDF 满足一次齐次性  d(s·p; s·a, s·b, s·r) = s·d(p; a, b, r)
    因此  L_s(p) = s · L(p / s)，
    即任意尺寸的 logo 都是同一条公式的不同 s 值，比例严格不变。
    """
    import copy
    p = copy.deepcopy(params)
    if canvas:
        p["canvas"] = [int(round(params["canvas"][0] * s)),
                       int(round(params["canvas"][1] * s))]
    r = p["ring"]
    for k in ("cx", "cy", "rxo", "ryo", "rxi", "ryi"):
        r[k] *= s
    for g in p["glyphs"]:
        if g["type"] == "P":
            for k in ("sx", "y0", "y1", "rs", "bx", "by", "R", "h"):
                g[k] *= s
        elif g["type"] == "o":
            for k in ("cx", "cy", "R", "h"):
                g[k] *= s
        elif g["type"] == "w":
            g["pts"] = [[x * s, y * s] for x, y in g["pts"]]
            g["r"] *= s
    return p


# --------------------------------------------------------------------------------------
# 四、渲染与导出
# --------------------------------------------------------------------------------------

def render_mask(params: Dict, W: int | None = None, H: int | None = None,
                supersample: int = 2) -> np.ndarray:
    """在画布上渲染成布尔掩码（SS×SS 超采样抗锯齿）。"""
    W = W or params["canvas"][0]
    H = H or params["canvas"][1]
    s = supersample
    xs = (np.arange(W * s) + 0.5) / s
    ys = (np.arange(H * s) + 0.5) / s
    X, Y = np.meshgrid(xs, ys)
    d = logo_sdf(params, X, Y)
    cov = (d <= 0).astype(np.float32).reshape(H, s, W, s).mean(axis=(1, 3))
    return cov


def hex_to_rgb(h: str):
    h = h.lstrip("#")
    return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))


def save_png(params: Dict, path: str, supersample: int = 2) -> None:
    from PIL import Image
    W, H = params["canvas"]
    cov = render_mask(params, W, H, supersample)
    rgb = np.array(hex_to_rgb(params["color"]), dtype=np.float32) / 255.0
    img = 1.0 - cov[..., None] * (1.0 - rgb)
    Image.fromarray((img * 255 + 0.5).astype(np.uint8)).save(path)


def save_svg(params: Dict, path: str, viewbox: str = WORDMARK_VIEWBOX) -> None:
    """导出与页面一致的描边式 SVG（胶囊=圆头直线，弧=圆弧路径，环=椭圆描边）。"""
    W, H = params["canvas"]
    parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{viewbox}" '
             f'width="{W}" height="{H}">',
             f'<g fill="none" stroke="{params["color"]}" stroke-linecap="round" '
             f'stroke-linejoin="round">']
    r = params["ring"]
    parts.append(f'  <ellipse cx="{r["cx"]:.2f}" cy="{r["cy"]:.2f}" '
                 f'rx="{(r["rxo"]+r["rxi"])/2:.2f}" ry="{(r["ryo"]+r["ryi"])/2:.2f}" '
                 f'stroke-width="{r["rxo"]-r["rxi"]:.2f}"/>')
    for g in params["glyphs"]:
        if g["type"] == "P":
            parts.append(f'  <line x1="{g["sx"]:.2f}" y1="{g["y0"]:.2f}" '
                         f'x2="{g["sx"]:.2f}" y2="{g["y1"]:.2f}" '
                         f'stroke-width="{2*g["rs"]:.2f}"/>')
            parts.append(f'  <path d="M {g["sx"]:.2f} {g["by"]-g["R"]:.2f} '
                         f'L {g["bx"]:.2f} {g["by"]-g["R"]:.2f} '
                         f'A {g["R"]:.2f} {g["R"]:.2f} 0 0 1 {g["bx"]:.2f} {g["by"]+g["R"]:.2f} '
                         f'L {g["sx"]:.2f} {g["by"]+g["R"]:.2f}" stroke-width="{2*g["h"]:.2f}"/>')
        elif g["type"] == "o":
            parts.append(f'  <circle cx="{g["cx"]:.2f}" cy="{g["cy"]:.2f}" r="{g["R"]:.2f}" '
                         f'stroke-width="{2*g["h"]:.2f}"/>')
        elif g["type"] == "w":
            pts = g["pts"]
            d = "M " + " L ".join(f'{x:.2f} {y:.2f}' for x, y in pts)
            parts.append(f'  <path d="{d}" stroke-width="{2*g["r"]:.2f}"/>')
    parts.append('</g></svg>')
    with open(path, "w", encoding="utf-8") as f:
        f.write("\n".join(parts))


if __name__ == "__main__":
    import sys
    p = load_params()
    out = sys.argv[1] if len(sys.argv) > 1 else HERE
    save_png(p, os.path.join(out, "powpow-logo.png"))
    save_svg(p, os.path.join(out, "powpow-logo.svg"))
    print("written to", out)
