# -*- coding: utf-8 -*-
"""
1fps 幻灯片测试帧生成器（2026-08-27）
=====================================
生成 200x200 黑白 EPD 帧数组（buffer 约定：1=白 0=黑，MSB 在左，25 字节/行）。
输出：firmware/inkboat/anim_frames.h（ANIM_N + ANIM_FRAMES[][5000]）
测试动画两段：①表盘+秒针 12 帧（局刷优势：只有秒针区域变）
             ②中心方块呼吸 8 帧（大面积变化，看局刷残影）

用法：.venv/Scripts/python.exe inkboat/make_slide_frames.py
"""

from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

DEST = Path(__file__).parent.parent / "firmware" / "inkboat" / "anim_frames.h"
W = H = 200
FONT = "C:/Windows/Fonts/simhei.ttf"


def new_frame():
    img = Image.new("1", (W, H), 1)          # 1=白（EPD buffer 约定）
    return img, ImageDraw.Draw(img)


def to_buf(img) -> bytes:
    # 转 25 字节/行，MSB 在左；PIL "1" 模式字节序是 LSB 在左，需翻位
    raw = img.tobytes()
    out = bytearray()
    for y in range(H):
        row = raw[y * (W // 8):(y + 1) * (W // 8)]
        flipped = bytes(int(bin(b)[2:].zfill(8)[::-1], 2) for b in row)
        out += flipped
    return bytes(out)


def frame_clock(step: int) -> bytes:
    """表盘 + 秒针。step=0..11：秒针从 12 点顺时针 12 格"""
    img, d = new_frame()
    cx = cy = 100
    d.ellipse([cx - 86, cy - 86, cx + 86, cy + 86], outline=0, width=4)   # 黑表盘环
    for i in range(12):                      # 12 点刻度
        a = i * 30 - 90
        import math
        r1, r2 = 74, 82
        x1 = cx + r1 * math.cos(math.radians(a))
        y1 = cy + r1 * math.sin(math.radians(a))
        x2 = cx + r2 * math.cos(math.radians(a))
        y2 = cy + r2 * math.sin(math.radians(a))
        d.line([x1, y1, x2, y2], fill=0, width=2)
    a = step * 30 - 90                       # 秒针（0=12 点）
    x = cx + 60 * math.cos(math.radians(a))
    y = cy + 60 * math.sin(math.radians(a))
    d.line([cx, cy, x, y], fill=0, width=6)
    d.ellipse([cx - 9, cy - 9, cx + 9, cy + 9], outline=0, width=5)  # 轴心
    return to_buf(img)


def frame_breath(step: int) -> bytes:
    """中心方块呼吸：30/70/110/150 → 缩回"""
    sizes = [30, 70, 110, 150, 150, 110, 70, 30]
    s = sizes[step]
    img, d = new_frame()
    d.rectangle([100 - s // 2, 100 - s // 2, 100 + s // 2, 100 + s // 2], outline=0, width=8)
    return to_buf(img)


def main():
    frames = [frame_clock(i) for i in range(12)] + [frame_breath(i) for i in range(8)]
    n = len(frames)
    out = ["// 本文件由 inkboat/make_slide_frames.py 自动生成（1fps 幻灯片测试帧）",
           "// 200x200 黑白，1=白 0=黑，25 字节/行，MSB 在左（EPD buffer 约定）",
           "#pragma once", "", f"#define ANIM_N {n}",
           f"const uint8_t ANIM_FRAMES[ANIM_N][5000] = {{"]
    for f in frames:
        out.append("  {" + ",".join(f"0x{b:02X}" for b in f) + "},")
    out.append("};")
    DEST.write_text("\n".join(out), encoding="utf-8")
    print(f"[OK] {DEST}  {n} 帧 x 5000 字节 = {n * 5000 // 1024}KB")


if __name__ == "__main__":
    main()