# -*- coding: utf-8 -*-
"""为《软件测试方法和技术（第4版）》第 4 章绘制全部插图（图 4-1 ~ 图 4-11）。

用 matplotlib 重绘，输出 PNG（200 dpi）到 ./figures/，供 Markdown 引用。
图形依据：教材书页 76–99 的原图（逐页拍照识别 + 人工核对结构）。
运行：.venv-draw/bin/python draw_figures.py
"""
import os

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch, Polygon, Rectangle, Circle, Arc, Wedge
import matplotlib.font_manager as fm

# ---- 字体与配色 -------------------------------------------------------------
CJK = next((n for n in ['Source Han Sans SC', 'Noto Sans CJK SC', 'WenQuanYi Zen Hei']
            if any(f.name == n for f in fm.fontManager.ttflist)), 'DejaVu Sans')
plt.rcParams['font.family'] = CJK
plt.rcParams['axes.unicode_minus'] = False

INK, NAVY, LINE = '#1a202c', '#1F4E79', '#2b6cb0'
FILL, FILL2, FILL3 = '#EEF3F9', '#FFFFFF', '#D9E4F0'
GRAY = '#4A5568'
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'figures')
os.makedirs(OUT, exist_ok=True)


_LIM = {}


def canvas(w=9, h=4.2, xmax=100, ymax=50):
    fig, ax = plt.subplots(figsize=(w, h))
    ax.set_xlim(0, xmax); ax.set_ylim(0, ymax)
    ax.axis('off')
    _LIM[ax] = (xmax, ymax)
    return fig, ax


def save(fig, name):

    fig.savefig(os.path.join(OUT, name), bbox_inches='tight', dpi=200)
    plt.close(fig)


def box(ax, x, y, w, h, text, fs=9, fill=FILL, ec=NAVY, bold=False, lw=1.2, ha='center', pad=0.35):
    ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle='round,pad=%s,rounding_size=0.6' % pad,
                                linewidth=lw, edgecolor=ec, facecolor=fill, zorder=2))
    ax.text(x + w / 2, y + h / 2, text, ha='center', va='center', fontsize=fs, color=INK,
            fontweight='bold' if bold else 'normal', zorder=3, linespacing=1.35)
    return (x, y, w, h)


def arrow(ax, p1, p2, style='-|>', ls='-', color=NAVY, lw=1.3, rad=0.0, label=None, lfs=8, lpos=0.5, ldy=1.2):
    ax.add_patch(FancyArrowPatch(p1, p2, arrowstyle=style, mutation_scale=12, linewidth=lw,
                                 color=color, linestyle=ls, shrinkA=1, shrinkB=1,
                                 connectionstyle='arc3,rad=%s' % rad, zorder=1))
    if label:
        x = p1[0] + (p2[0] - p1[0]) * lpos
        y = p1[1] + (p2[1] - p1[1]) * lpos + ldy
        ax.text(x, y, label, ha='center', va='bottom', fontsize=lfs, color=GRAY, zorder=4)


def chevron(ax, x, y, w, h, text, fs=8.5, notch=1.4):
    pts = [(x, y), (x + w - notch, y), (x + w, y + h / 2), (x + w - notch, y + h), (x, y + h), (x + notch, y + h / 2)]
    ax.add_patch(Polygon(pts, closed=True, facecolor=FILL, edgecolor=NAVY, linewidth=1.1, zorder=2))
    ax.text(x + w / 2 + notch / 2, y + h / 2, text, ha='center', va='center', fontsize=fs, color=INK, zorder=3)


_TITLE = {}


def title(ax, t, sub=None):
    """标题画在画布顶部（数据坐标），画布已为标题预留顶部空间。"""
    xmax, ymax = _LIM[ax]
    ax.text(xmax / 2, ymax - 1.5, t, ha='center', va='top', fontsize=12,
            color=NAVY, fontweight='bold', zorder=10)


def legend_line(ax, x, y, dashed=False, text=''):
    ax.plot([x, x + 5], [y, y], color=NAVY, lw=1.3, ls='--' if dashed else '-')
    ax.text(x + 6, y, text, va='center', fontsize=8, color=GRAY)


# ---- 图 4-1 软件测试的基本过程 ---------------------------------------------
def fig4_1():
    fig, ax = canvas(10, 3.7, 100, 46)
    title(ax, '图 4-1　软件测试的基本过程')
    r1 = ['需求评审', '设计评审', '单元测试', '集成测试', '系统测试', '验收测试']
    r2 = ['测试计划', '测试设计', '执行与监控', '结果分析与评估', '项目总结']
    w, h, gap = 15.2, 5.4, 0.6
    for i, t in enumerate(r1):
        chevron(ax, 6 + i * (w + gap), 25, w, h, t)
    for i, t in enumerate(r2):
        chevron(ax, 6 + i * (w + gap), 14, w, h, t)
    ax.text(2.2, 27.7, '软件工程\n过程线', ha='center', va='center', fontsize=7.5, color=GRAY, rotation=90)
    ax.text(2.2, 16.7, '项目管理\n过程线', ha='center', va='center', fontsize=7.5, color=GRAY, rotation=90)
    save(fig, 'fig4-1.png')


# ---- 图 4-2 测试过程和开发过程的同步关系 -----------------------------------
def fig4_2():
    fig, ax = canvas(11.5, 5.8, 118, 66)
    title(ax, '图 4-2　测试过程和开发过程的同步关系')
    dev = ['需求分析\n定义', '系统设计\n结构设计', '详细设计或\n程序设计', '编码及\n单元测试']
    tst = ['测试目标', '测试计划及系统\n测试用例设计与环境', '功能测试\n用例设计', '代码审查\n单元测试']
    right = ['验收测试', '系统测试', '功能测试', None]
    ys = [36, 26, 16, 6]
    for i, (d, tt, r) in enumerate(zip(dev, tst, right)):
        box(ax, 4, ys[i], 17, 6.6, d, fs=8)
        if i < 3:
            arrow(ax, (12.5, ys[i]), (12.5, ys[i + 1] + 6.6))
        box(ax, 44, ys[i], 21, 6.6, tt, fs=7.4, fill=FILL2)
        arrow(ax, (21, ys[i] + 3.3), (44, ys[i] + 3.3), ls='--', label='同步', lfs=7, ldy=0.5)
        if r:
            box(ax, 96, ys[i], 17, 6.6, r, fs=8, fill=FILL3)
            arrow(ax, (65, ys[i] + 3.3), (96, ys[i] + 3.3), ls='--')
            arrow(ax, (96, ys[i] + 5.0), (65, ys[i] + 5.0), ls=':', lw=1.0, color='#9E1F24')
            if i == 0:
                ax.text(80.5, ys[i] + 5.4, '缺陷修正', ha='center', fontsize=6.8, color='#9E1F24')
    ax.text(32.5, 38.6, '需求\n评审', ha='center', va='bottom', fontsize=6.8, color=GRAY)
    ax.text(32.5, 28.6, '设计\n评审', ha='center', va='bottom', fontsize=6.8, color=GRAY)
    legend_line(ax, 6, 2.0, False, '开发过程')
    legend_line(ax, 28, 2.0, True, '测试过程')
    save(fig, 'fig4-2.png')

# ---- 图 4-3 TMap 描述的生命周期模型 ----------------------------------------
def fig4_3():
    fig, ax = canvas(12, 7.4, 120, 96)
    title(ax, '图 4-3　TMap 描述的生命周期模型')
    def band(x, y, w, h, text='', fs=8.5, fill=FILL, dy=0.0):
        ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle='round,pad=0.3,rounding_size=0.5',
                                    facecolor=fill, edgecolor=NAVY, lw=1.1, zorder=2))
        if text:
            ax.text(x + w / 2, y + h / 2 + dy, text, ha='center', va='center', fontsize=fs, zorder=3)
    band(40, 40, 40, 4.6, 'Ctrl')
    band(40, 26, 40, 14, '', fill=FILL3)
    for i, ch in enumerate(['P', 'S', 'E', 'C']):
        ax.text(56 + i * 6.4, 33, ch, ha='center', va='center', fontsize=11, color=NAVY, zorder=4)
    ax.text(48, 23.4, 'Plan', ha='center', fontsize=8.5, color=GRAY, zorder=4)
    band(40, 16, 40, 4.6, 'Infra')
    def note(x, y, w, h, txt, to, fs=6.6):
        ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle='round,pad=0.3,rounding_size=0.5',
                                    facecolor='white', edgecolor=GRAY, lw=0.9, zorder=5))
        ax.text(x + w / 2, y + h / 2, txt, ha='center', va='center', fontsize=fs, color=INK,
                zorder=6, linespacing=1.35)
        arrow(ax, (x + w / 2, y + (h if y < to[1] else 0)), to, lw=0.8, color=GRAY)
    note(3, 44, 29, 9, 'Preparation（准备）\n包括可测试性评审、确定技术方法', (45, 48.6))
    note(88, 44, 29, 9, 'Control（控制）\n对测试执行过程进行监督与控制', (75, 48.6))
    note(2, 30, 30, 12, 'Planning（计划）\n包括评审和研究、开发测试策略\n（风险分析、测试估算等）、\n建立测试组织、准备计划等', (40, 35))
    note(88, 31, 30, 10, 'Specification（说明）\n包括测试需求分析、\n详细设计测试用例', (80, 35))
    note(88, 20, 30, 9, 'Execution（执行）\n包括预测试、测试、重新测试、\n检查、评估等活动', (80, 30))
    note(88, 8, 30, 9, 'Completed（完成）\n包括维护测试件、评估测试过程', (80, 18))
    note(36, 4, 48, 8, 'Infrastructure（基础设施）\n建立测试执行、测试件管理、缺陷管理等所需的环境，包括自动化测试框架', (60, 16))
    save(fig, 'fig4-3.png')

# ---- 图 4-4 TMap 测试方法模型的基石 ----------------------------------------
def fig4_4():
    fig, ax = canvas(6, 4.9, 60, 54)
    title(ax, '图 4-4　TMap 测试方法模型的基石')
    T, I, O = (30, 38), (10, 12), (50, 12)
    L = (30, 22)
    for a, b in [(T, I), (T, O), (I, O), (L, T), (L, I), (L, O)]:
        ax.plot([a[0], b[0]], [a[1], b[1]], color=NAVY, lw=1.3, zorder=1)
    for p, t in [(T, 'T'), (I, 'I'), (O, 'O')]:
        ax.add_patch(Circle(p, 3.1, facecolor=FILL2, edgecolor=NAVY, lw=1.2, zorder=3))
        ax.text(p[0], p[1], t, ha='center', va='center', fontsize=11, fontweight='bold', color=NAVY, zorder=4)
    ax.add_patch(Circle(L, 3.1, facecolor=FILL3, edgecolor=NAVY, lw=1.2, zorder=3))
    ax.text(L[0], L[1], 'L', ha='center', va='center', fontsize=11, fontweight='bold', color=NAVY, zorder=4)
    ax.text(30, 43, 'T＝技术　I＝基础设施和工具　O＝组织融合　L＝生命周期', ha='center', fontsize=7.5, color=GRAY)
    save(fig, 'fig4-4.png')


# ---- 图 4-5 敏捷测试过程示意图 ---------------------------------------------
def fig4_5():
    fig, ax = canvas(10.5, 4.8, 106, 54)
    title(ax, '图 4-5　敏捷测试过程示意图')
    xs, w, y, h = 18, 13, 22, 6.6
    nodes = ['需求', '设计', '代码', '功能', '非功能特性']
    for i, t in enumerate(nodes):
        x = xs + i * (w + 2.4)
        box(ax, x, y, w, h, t, fs=9)
        if i:
            arrow(ax, (x - 2.4, y + h / 2), (x, y + h / 2))
    ax.text(53, 36.2, '产品经理', ha='center', fontsize=8.5, color=GRAY)
    ax.text(53, 6.4, '开发人员', ha='center', fontsize=8.5, color=GRAY)
    x0, x1 = xs + 1, xs + 4 * (w + 2.4) + w - 1
    arrow(ax, (x1, 31.5), (x0, 31.5), ls='--', lw=1.1)
    arrow(ax, (x1, 17.0), (x0, 17.0), ls='--', lw=1.1)
    ax.text(53, 33.4, '质量问题持续反馈', ha='center', va='bottom', fontsize=7.5, color=GRAY)
    ax.text(53, 14.2, '质量问题持续反馈', ha='center', va='top', fontsize=7.5, color=GRAY)
    ax.text(9, 25.3, '敏捷\n测试', ha='center', va='center', fontsize=8.5, color=NAVY, fontweight='bold')
    ax.text(99, 25.3, '敏捷\n测试', ha='center', va='center', fontsize=8.5, color=NAVY, fontweight='bold')
    save(fig, 'fig4-5.png')

# ---- 图 4-6 Scrum 流程示意图 ------------------------------------------------
def fig4_6():
    fig, ax = canvas(9.6, 4.7, 96, 52)
    title(ax, '图 4-6　Scrum 流程示意图')
    # Product Backlog：一叠薄片
    for i in range(6):
        ax.add_patch(Rectangle((10, 12 + i * 2.1), 16, 1.8, facecolor=FILL3, edgecolor=NAVY, lw=0.8, zorder=2))
    ax.text(18, 8.5, 'Product Backlog', ha='center', fontsize=8.5, color=INK)
    # Sprint 循环
    ax.add_patch(Arc((46, 25), 22, 22, theta1=45, theta2=300, color=NAVY, lw=6, zorder=2))
    ax.add_patch(FancyArrowPatch((52.5, 15.5), (57.5, 12.8), arrowstyle='-|>', mutation_scale=18,
                                 color=NAVY, lw=6, zorder=2))
    ax.text(46, 27, '1~4周迭代\nSprint', ha='center', va='center', fontsize=8, color=INK, zorder=4)
    ax.add_patch(Arc((40, 36), 6, 6, theta1=200, theta2=20, color=GRAY, lw=1.4, zorder=2))
    ax.add_patch(FancyArrowPatch((43, 37.8), (44.4, 35.6), arrowstyle='-|>', mutation_scale=9, color=GRAY, lw=1.4))
    ax.text(38, 39.5, '每日会议', ha='center', fontsize=7.5, color=GRAY)
    arrow(ax, (26, 22), (34, 22))
    # Sprint Backlog
    for i in range(3):
        ax.add_patch(Rectangle((40, 10 + i * 2.0), 7, 1.7, facecolor=FILL, edgecolor=NAVY, lw=0.8, zorder=2))
    ax.text(43.5, 6.5, 'Sprint Backlog', ha='center', fontsize=8.5, color=INK)
    arrow(ax, (57, 14), (66, 14))
    ax.text(61.5, 15.8, '验收测试', ha='center', fontsize=7.5, color=GRAY)
    box(ax, 68, 10.5, 16, 7, '产品交付', fs=9)
    save(fig, 'fig4-6.png')


# ---- 图 4-7 SBTM 框架示意图 -------------------------------------------------
def fig4_7():
    fig, ax = canvas(10, 5.7, 100, 64)
    title(ax, '图 4-7　SBTM 框架示意图')
    ax.add_patch(FancyBboxPatch((18, 12), 52, 30, boxstyle='round,pad=0.4,rounding_size=1',
                                facecolor='none', edgecolor=GRAY, lw=1.2, linestyle='--', zorder=1))
    ax.text(66.5, 39.5, 'SBTM', fontsize=9, color=GRAY, fontweight='bold')
    box(ax, 34, 47, 20, 5.4, '测试计划', fs=8.5, fill=FILL3)
    box(ax, 34, 37, 20, 5.4, '测试任务设计', fs=8.5)
    box(ax, 32, 25, 24, 6.4, '测试设计与执行', fs=9, fill=FILL2, bold=True)
    box(ax, 20, 24, 10, 8.4, 'Session\n设置', fs=7.5)
    box(ax, 58, 24, 12, 8.4, '缺陷分析\n与报告', fs=7.5)
    box(ax, 33, 14, 22, 6.0, '任务汇报', fs=8.5)
    box(ax, 76, 25, 14, 6.4, '监控', fs=8.5, fill=FILL3)
    box(ax, 33, 4, 22, 6.0, '测试完成', fs=8.5, fill=FILL3)
    arrow(ax, (44, 47), (44, 42.4))
    arrow(ax, (44, 37), (44, 31.4))
    ax.text(50, 34.6, '测试Charters', fontsize=7, color=GRAY)
    arrow(ax, (30, 28.2), (32, 28.2))
    ax.text(24, 21.6, 'Session Sheet', fontsize=7, color=GRAY)
    arrow(ax, (52, 31), (52, 31.4), lw=0)
    arrow(ax, (56, 28.2), (58, 28.2), style='<|-|>')
    arrow(ax, (44, 25), (44, 20.0))
    arrow(ax, (55, 17), (55, 14), lw=0)
    arrow(ax, (44, 14), (44, 10.0))
    arrow(ax, (70, 28.2), (76, 28.2), style='<|-|>')
    arrow(ax, (83, 31.4), (54, 47.0), ls='--', rad=0.25, lw=1.0)
    ax.text(70, 45.5, '计划与监控', fontsize=7, color=GRAY)
    save(fig, 'fig4-7.png')


# ---- 图 4-8 探索式测试主要元素之间的关系 -----------------------------------
def fig4_8():
    fig, ax = canvas(9.6, 4.8, 96, 54)
    title(ax, '图 4-8　探索式测试主要元素之间的关系')
    box(ax, 38, 38, 20, 5.6, '测试计划', fs=8.5, fill=FILL3)
    ms = ['测试Mission 1', '测试Mission 2', '…', '测试Mission n']
    for i, t in enumerate(ms):
        box(ax, 8 + i * 21, 28, 18, 5.4, t, fs=7.5)
    arrow(ax, (48, 38), (48, 33.4))
    cs = ['Charter 1', 'Charter 2', '…', 'Charter m']
    for i, t in enumerate(cs):
        box(ax, 18 + i * 20, 18, 16, 5.2, t, fs=7.5, fill=FILL2)
    arrow(ax, (48, 28), (48, 23.2))
    box(ax, 34, 9, 28, 5.6, 'Time-Box＝Session', fs=8.5, fill=FILL3)
    arrow(ax, (48, 18), (48, 14.6))
    box(ax, 40, 1.4, 16, 5.2, '追加Session', fs=7.5)
    arrow(ax, (48, 9), (48, 6.6))
    save(fig, 'fig4-8.png')


# ---- 图 4-9 软件测试 5 大学派示意图 ----------------------------------------
def fig4_9():
    fig, ax = canvas(8.4, 5.0, 84, 54)
    title(ax, '图 4-9　软件测试 5 大学派示意图')
    box(ax, 36, 20, 18, 7, '②\n标准学派', fs=8.5, fill=FILL3, bold=True)
    corners = [
        (10, 34, '分析学派', '①'), (58, 34, '质量学派', '③'),
        (6, 6, '上下文\n驱动学派', '④'), (58, 6, '敏捷学派', '⑤'),
    ]
    for x, y, t, num in corners:
        box(ax, x, y, 18, 8 if '\n' in t else 6.6, t, fs=8)
        cx, cy = x + 9, y + (4 if '\n' in t else 3.3)
        tx, ty = 45, 24
        arrow(ax, (cx, cy + (4 if '\n' in t else 3.3)), (tx, ty + 3.5), lw=1.1)
        ax.text(cx + 6.5, cy + (5.4 if '\n' in t else 4.6), num, fontsize=10, color=NAVY, fontweight='bold')
    save(fig, 'fig4-9.png')


# ---- 图 4-10 TMM 5 个级别的简要描述 ----------------------------------------
def fig4_10():
    fig, ax = canvas(11.5, 7.2, 115, 74)
    title(ax, '图 4-10　TMM 5 个级别的简要描述')
    levels = [
        ('1. 初始级', ['没有正式的文档化和结构化', '测试在编码后执行，与调试没有区别', '测试的目的是证明软件正常工作']),
        ('2. 阶段定义级', ['组织已设定测试方针和目标', '引进了测试计划过程', '具有基本的测试技术和方法']),
        ('3. 集成级', ['测试过程和软件开发周期集成在一起', '标准、步骤和方法的文档化', '相应的监督和控制措施']),
        ('4. 管理和度量级', ['测试过程可有效地度量、管理']),
        ('5. 优化级', ['测试过程的数据可以用于防止错误', '注意力集中在优化已建立的过程']),
    ]
    x, y, w, h = 4, 3, 34, 10.2
    for i, (t, bullets) in enumerate(levels):
        bx, by = x + i * 18.6, y + i * 11.6
        ax.add_patch(FancyBboxPatch((bx, by), w, h, boxstyle='round,pad=0.3,rounding_size=0.6',
                                    facecolor=FILL if i % 2 == 0 else FILL3, edgecolor=NAVY, lw=1.2, zorder=3))
        ax.text(bx + 1.4, by + h - 1.4, t, fontsize=8.8, color=NAVY, fontweight='bold', va='top', zorder=4)
        ax.text(bx + 1.4, by + h - 3.6, '\n'.join('· ' + b for b in bullets), fontsize=7.2,
                color=INK, va='top', linespacing=1.45, zorder=4)
        if i:
            ax.add_patch(FancyArrowPatch((bx - 3.0, by + h * 0.45), (bx - 0.4, by + h * 0.45),
                                         arrowstyle='-|>', mutation_scale=15, color=NAVY, lw=2.4, zorder=2))
    save(fig, 'fig4-10.png')

# ---- 图 4-11 TPI 模型的构成 -------------------------------------------------
def fig4_11():
    fig, ax = canvas(9, 4.8, 90, 54)
    title(ax, '图 4-11　TPI 模型的构成')
    ax.add_patch(FancyBboxPatch((16, 16), 46, 26, boxstyle='round,pad=0.4,rounding_size=1',
                                facecolor='none', edgecolor=GRAY, lw=1.2, linestyle='--', zorder=1))
    box(ax, 24, 34, 30, 6, '关键域（Key Areas）', fs=8.5)
    box(ax, 24, 22, 30, 6, '级别（Levels）', fs=8.5)
    arrow(ax, (39, 34), (39, 28))
    ax.text(56, 24.6, '测试成熟度矩阵', fontsize=7.5, color=GRAY)
    box(ax, 10, 4, 26, 6, '检查点（Checkpoints）', fs=8)
    box(ax, 46, 4, 34, 6, '改进建议（Improvement Suggestions）', fs=8, fill=FILL3)
    arrow(ax, (30, 22), (23, 10), lw=1.2)
    arrow(ax, (36, 7), (46, 7), lw=1.4)
    save(fig, 'fig4-11.png')


if __name__ == '__main__':
    for f in [fig4_1, fig4_2, fig4_3, fig4_4, fig4_5, fig4_6,
              fig4_7, fig4_8, fig4_9, fig4_10, fig4_11]:
        f()
        print('  ✓ %s' % f.__name__)
    print('输出目录：%s' % OUT)
