# -*- coding: utf-8 -*-
"""图 1-1　PMP 证书样本 —— 教材第 5 页

按「图内要素」逐项还原为**简化版证书示意图**（不逐字复制真实证书文本）：
· 近黑色粗边框（约图宽的 3%）＋框内白底；纸面上散布浅灰方形水印块
  （右上角一块斜置大灰块、左侧一列上下相接的方形灰块、中部与右缘淡灰折角叠影）
· ① 顶部标志区：黑色方标内白色「PM」＋右侧三行粗黑英文 Project / Management / Institute.
· ② 提称区：THIS IS TO CERTIFY THAT ／ 持证人姓名（占位，原图已打码）／ 三行递减英文说明
· ③ 资格名称区：Project Management Professional (PMP)®（证书内最大字号）＋其下一行小号说明
· ④ 签署与钢印区：左右两栏手写签名＋细横线＋署名小字；中栏齿边圆章（环形英文＋中腰横带
   CORPORATE SEAL＋中心深色圆内嵌白色 PM），印章压住左右两栏横线成骑缝效果
· ⑤ 编号与日期行：Certification Number（占位）／Original Grant Date／Expiration Date

简化处理：① 拍摄造成的梯形畸变与塑封反光不做像素级复刻，水印块只作示意；
② 姓名、证书编号按占位符处理（原照片已打码）；③ 手写签名以示意性连笔线条代替。
"""
import math
import os
import sys

import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Polygon, Rectangle

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, save, INK, NAV, ACC, FILL, LINE  # noqa: E402

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'assets',
                   '图1-1-PMP证书样本.png')

BLACK = '#15181c'      # 近黑色边框
WATER = '#eef1f6'      # 水印灰块
GREY = '#4a5568'       # 次级文字
RED = '#9b2c2c'        # 备用（本图未用，保留色板一致性）


def arc_text(ax, cx, cy, r, s, a0, a1, fs, color, top=True, z=7):
    """沿圆弧逐字排布（top=True 上弧、False 下弧）。角度为数学极角（度）。"""
    n = len(s)
    angles = [(a0 + a1) / 2.0] if n == 1 else [a0 + (a1 - a0) * i / (n - 1) for i in range(n)]
    for ch, a in zip(s, angles):
        rad = math.radians(a)
        x, y = cx + r * math.cos(rad), cy + r * math.sin(rad)
        ax.text(x, y, ch, rotation=a - 90 if top else a + 90, rotation_mode='anchor',
                ha='center', va='center', fontsize=fs, color=color, zorder=z)


def toothed_ring(ax, cx, cy, r_out, depth, n=84, fc=FILL, ec=LINE, z=4):
    """齿状／锯齿外缘圆环（正圆外沿交替凸凹）。"""
    pts = []
    for i in range(n * 2):
        a = 2 * math.pi * i / (n * 2)
        rr = r_out if i % 2 == 0 else r_out - depth
        pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a)))
    ax.add_patch(Polygon(pts, closed=True, facecolor=fc, edgecolor=ec, lw=0.9, zorder=z))


def squiggle(ax, x0, x1, y, amp, color=NAV, lw=1.1, phase=0.0, k=2.0, z=6):
    """示意性手写签名：多条正弦叠合的连笔线条。"""
    n = 240
    xs, ys = [], []
    for i in range(n):
        t = i / (n - 1)
        x = x0 + (x1 - x0) * t
        yv = (y + amp * math.sin(2 * math.pi * k * t + phase) * (0.35 + 0.65 * t)
              + 0.28 * amp * math.sin(2 * math.pi * (3 * k + 1.5) * t + phase * 1.7))
        xs.append(x)
        ys.append(yv)
    ax.plot(xs, ys, color=color, lw=lw, solid_capstyle='round', zorder=z, alpha=0.92)


def main():
    setup()
    fig, ax = canvas(11.0, 8.4, xlim=(0, 110), ylim=(0, 84))
    ax.set_aspect('equal', adjustable='box')

    # ── 黑框（宽 3.2 ≈ 图宽 3%）＋框内白底 ──
    ax.add_patch(Rectangle((3.0, 3.0), 104.0, 78.0, facecolor=BLACK,
                           edgecolor='none', zorder=1))
    ax.add_patch(Rectangle((6.2, 6.2), 97.6, 71.6, facecolor='white',
                           edgecolor='none', zorder=2))

    # ── 防伪／反光水印块（浅灰，示意）──
    ax.add_patch(Polygon([(80, 56), (86.5, 49.5), (97, 60.5), (90.5, 67)],
                         closed=True, facecolor=WATER, edgecolor='none', zorder=2.2))
    for yy in (58.6, 49.8, 41.0):                      # 左侧一列上下相接的方灰块
        ax.add_patch(Rectangle((7.2, yy), 8.4, 8.4, facecolor=WATER,
                               edgecolor='none', zorder=2.2))

    # ── ① 顶部标志区（方标＋三行英文作为一组整体居中）──
    probe = ax.text(0, 0, 'Management', fontsize=8.8, fontweight='bold', alpha=0.0)
    fig.canvas.draw()
    pw = probe.get_window_extent(fig.canvas.get_renderer())
    inv0 = ax.transData.inverted()
    text_w = abs(inv0.transform((pw.x1, pw.y1))[0] - inv0.transform((pw.x0, pw.y1))[0])
    probe.remove()
    sq = 8.8
    gap = 1.9
    x0 = 55.0 - (sq + gap + text_w) / 2.0
    ax.add_patch(Rectangle((x0, 66.0), sq, sq, facecolor=INK,
                           edgecolor='none', zorder=4))
    ax.text(x0 + sq / 2, 70.35, 'PM', ha='center', va='center', color='white',
            fontsize=9.2, fontweight='bold', zorder=5)
    for i, s in enumerate(('Project', 'Management', 'Institute.')):
        ax.text(x0 + sq + gap, 73.5 - i * 2.55, s, ha='left', va='center', color=INK,
                fontsize=8.8, fontweight='bold', zorder=5)

    # ── ② 提称区 ──
    ax.text(55, 59.6, 'THIS IS TO CERTIFY THAT', ha='center', va='center',
            color=GREY, fontsize=7.8, zorder=5)

    ax.add_patch(Rectangle((33.0, 47.2), 44.0, 5.6, facecolor='#f3f9ff',
                           edgecolor=LINE, lw=0.9, linestyle=(0, (3.2, 2.2)), zorder=4))
    ax.text(55, 50.0, '（持证人姓名）', ha='center', va='center', color=NAV,
            fontsize=14.5, zorder=5)

    DESC = [('HAS BEEN FORMALLY EVALUATED FOR DEMONSTRATED EXPERIENCE, KNOWLEDGE AND PERFORMANCE', 9.1),
            ('IN ACHIEVING AN ORGANIZATIONAL OBJECTIVE THROUGH DEFINING AND OVERSEEING PROJECTS AND', 8.9),
            ('RESOURCES AND IS HEREBY BESTOWED THE GLOBAL CREDENTIAL', 8.9)]
    for i, (s, fs) in enumerate(DESC):
        ax.text(55, 42.6 - i * 2.8, s, ha='center', va='center', color='#2d3748',
                fontsize=fs, zorder=5)

    # ── ③ 资格名称区 ──
    t = ax.text(55, 29.6, 'Project Management Professional (PMP)', ha='center',
                va='center', color=INK, fontsize=15.5, fontweight='bold', zorder=5)
    fig.canvas.draw()
    bb = t.get_window_extent(fig.canvas.get_renderer())
    inv = ax.transData.inverted()
    xr, yr = inv.transform((bb.x1, bb.y1))
    ax.text(xr + 0.35, yr - 0.15, '®', ha='left', va='top', color=INK,
            fontsize=8.0, zorder=5)
    ax.text(55, 24.4, 'IN TESTIMONY WHEREOF, WE HAVE SUBSCRIBED OUR SIGNATURES UNDER THE SEAL OF THE INSTITUTE',
            ha='center', va='center', color='#2d3748', fontsize=6.9, zorder=5)

    # ── ④ 签署与钢印区 ──
    squiggle(ax, 13.0, 38.0, 16.8, 1.35, phase=0.3, k=1.7)
    squiggle(ax, 14.5, 36.5, 16.2, 0.85, phase=1.9, k=2.6, lw=0.9)
    ax.plot([11.5, 39.0], [12.8, 12.8], color=GREY, lw=1.0, zorder=5)
    ax.text(11.0, 11.2, 'LuAnn Piccard, PMP　|　Chair, Board of Directors',
            ha='left', va='center', color=GREY, fontsize=6.2, zorder=5)

    squiggle(ax, 71.0, 97.0, 16.8, 1.35, phase=2.4, k=1.6)
    squiggle(ax, 73.5, 96.0, 16.1, 0.8, phase=0.7, k=2.4, lw=0.9)
    ax.plot([71.0, 98.5], [12.8, 12.8], color=GREY, lw=1.0, zorder=5)
    ax.text(99.0, 11.2, 'Pierre Le Manh　|　President & CEO',
            ha='right', va='center', color=GREY, fontsize=6.2, zorder=5)

    # 中栏圆形压印封条章
    cx, cy, r = 55.0, 16.4, 7.0
    toothed_ring(ax, cx, cy, r, 0.55, n=78)
    ax.add_patch(Circle((cx, cy), 5.55, facecolor='none', edgecolor=LINE, lw=1.0, zorder=5))
    arc_text(ax, cx, cy, 4.9, 'PROJECT MANAGEMENT INSTITUTE', 168, 12, 4.3, NAV, top=True)
    arc_text(ax, cx, cy, 4.9, 'PENNSYLVANIA', 214, 326, 4.3, NAV, top=False)
    ax.plot([51.4, 58.6], [15.3, 15.3], color=LINE, lw=0.8, zorder=5)
    ax.plot([51.4, 58.6], [13.95, 13.95], color=LINE, lw=0.8, zorder=5)
    ax.text(cx, 14.62, 'CORPORATE SEAL', ha='center', va='center', color=NAV,
            fontsize=3.2, zorder=6)
    ax.add_patch(Circle((cx, 17.9), 1.5, facecolor=NAV, edgecolor='none', zorder=6))
    ax.text(cx, 17.9, 'PM', ha='center', va='center', color='white',
            fontsize=3.6, fontweight='bold', zorder=7)

    # ── ⑤ 编号与日期行 ──
    ax.text(12.0, 8.2, 'Certification Number: （证书编号）', ha='left', va='center',
            color=GREY, fontsize=6.2, zorder=5)
    ax.text(55.0, 8.2, 'Original Grant Date: 01 June 2024', ha='center', va='center',
            color=GREY, fontsize=6.2, zorder=5)
    ax.text(98.0, 8.2, 'Expiration Date: 01 June 2027', ha='right', va='center',
            color=GREY, fontsize=6.2, zorder=5)

    save(fig, OUT)


if __name__ == '__main__':
    main()
