# -*- coding: utf-8 -*-
"""第 5 章教材插图 · Python 绘制工具库（matplotlib）
用法：
    from _draw import setup, canvas, box, arrow, tree, save
    setup()
所有图统一：白底、深蓝主色（#1a365d / #2b6cb0）、浅蓝填充（#ebf8ff）、2x DPI。
"""
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch, Rectangle

# 中文字体候选（本机实测有用）
CJK = ['Noto Sans CJK SC', 'Source Han Sans SC', 'WenQuanYi Zen Hei', 'DejaVu Sans']
INK, NAV, ACC, FILL, LINE = '#1a202c', '#1a365d', '#2b6cb0', '#ebf8ff', '#90cdf4'


def setup():
    plt.rcParams['font.sans-serif'] = CJK
    plt.rcParams['axes.unicode_minus'] = False
    plt.rcParams['figure.dpi'] = 200
    plt.rcParams['savefig.dpi'] = 200
    plt.rcParams['savefig.bbox'] = 'tight'
    plt.rcParams['savefig.pad_inches'] = 0.3      # 四周留白（防贴边/裁切观感）
    plt.rcParams['savefig.facecolor'] = 'white'


def canvas(w=10.0, h=6.0, xlim=(0, 100), ylim=(0, 100)):
    """返回 (fig, ax)：坐标系用 0–100 的相对单位，便于按比例布局。
    画布范围会记录到 ax._lims，供 box()/arrow() 做越界自检（越界=保存后被裁切）。"""
    fig, ax = plt.subplots(figsize=(w, h))
    ax.set_xlim(*xlim); ax.set_ylim(*ylim); ax.axis('off')
    ax._lims = (xlim, ylim)
    return fig, ax


def _check_bounds(ax, x0, y0, x1, y1, what):
    """越界自检：任何元素超出画布范围都会在保存后被 matplotlib 裁掉，这里立即告警。"""
    lims = getattr(ax, '_lims', None)
    if not lims:
        return
    (xl, xr), (yl, yb) = lims
    tol = 0.5
    out = []
    if x0 < xl - tol: out.append(f'左越界 {x0:.1f}<{xl}')
    if x1 > xr + tol: out.append(f'右越界 {x1:.1f}>{xr}')
    if y0 < yl - tol: out.append(f'下越界 {y0:.1f}<{yl}')
    if y1 > yb + tol: out.append(f'上越界 {y1:.1f}>{yb}')
    if out:
        print(f'  ⚠️ 越界告警（{what}）：' + '、'.join(out) + ' → 保存后会被裁切，请调整布局')


def box(ax, x, y, w, h, text, fc=FILL, ec=LINE, tc=NAV, fs=11, bold=False, radius=1.6, lw=1.4):
    """以 (x, y) 为左上角画圆角矩形＋居中文字；返回中心点。"""
    _check_bounds(ax, x, y - h, x + w, y, f'box「{str(text)[:12]}」')
    p = FancyBboxPatch((x, y - h), w, h, boxstyle=f'round,pad=0,rounding_size={radius}',
                       linewidth=lw, edgecolor=ec, facecolor=fc, mutation_aspect=1)
    ax.add_patch(p)
    ax.text(x + w / 2, y - h / 2, text, ha='center', va='center', color=tc,
            fontsize=fs, fontweight='bold' if bold else 'normal', linespacing=1.45, wrap=True)
    return (x + w / 2, y - h / 2)


def arrow(ax, p1, p2, color=ACC, lw=1.6, style='-|>', rad=0.0, ls='-'):
    a = FancyArrowPatch(p1, p2, arrowstyle=style, mutation_scale=14, linewidth=lw,
                        color=color, linestyle=ls,
                        connectionstyle=f'arc3,rad={rad}', shrinkA=1, shrinkB=1)
    ax.add_patch(a)


def line(ax, p1, p2, color=LINE, lw=1.3, ls='-'):
    ax.plot([p1[0], p2[0]], [p1[1], p2[1]], color=color, linewidth=lw, linestyle=ls, zorder=1)


def title(ax, text, fs=14, y=None, x=50):
    ax.text(x, y if y is not None else 98, text, ha='center', va='top',
            color=NAV, fontsize=fs, fontweight='bold')


def caption(ax, text, fs=10, y=1.5):
    ax.text(50, y, text, ha='center', va='bottom', color='#4a5568', fontsize=fs)


def tree(ax, root, children, x=50, y=90, dy=18, box_w=22, box_h=8, child_gap=None,
         root_fc=NAV, root_tc='white'):
    """根节点 + 一行子节点（子节点带连线），返回子节点中心列表。
    root: 根节点文字；children: [子节点文字, ...]"""
    box(ax, x - box_w / 2, y, box_w, box_h, root, fc=root_fc, ec=root_fc, tc=root_tc, bold=True, fs=11)
    n = len(children)
    gap = child_gap if child_gap else 100.0 / (n + 1)
    centers = []
    for i, c in enumerate(children, start=1):
        cx = gap * i
        cy = y - dy
        box(ax, cx - box_w / 2, cy, box_w, box_h, c, fs=10)
        line(ax, (x, y - box_h), (cx, cy))
        centers.append((cx, cy - box_h / 2))
    return centers


def rows(ax, items, x=4, y=88, w=92, h=7, gap=2.6, fs=11, label_w=26):
    """左标签右内容的横向条带（用于表格式图示）：items=[(标签, 内容), ...]"""
    for lab, val in items:
        box(ax, x, y, label_w, h, lab, fc=NAV, ec=NAV, tc='white', fs=fs - 1, bold=True)
        box(ax, x + label_w + 1, y, w - label_w - 1, h, val, fs=fs - 1)
        y -= (h + gap)
    return y


def save(fig, path, pad=1.6):
    """保存前**自动扩展画布**以容纳所有图元（含被画到 0–100 之外的元素），
    从根本上避免"内容被坐标轴裁掉"（历史缺陷：WBS 树状图右侧框被切）。"""
    os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
    try:
        for ax in fig.axes:
            x0, x1 = ax.get_xlim(); y0, y1 = ax.get_ylim()
            x0 = min(x0, 0.0); x1 = max(x1, 100.0)
            y0 = min(y0, 0.0); y1 = max(y1, 100.0)
            dl = getattr(ax, 'dataLim', None)
            changed = False
            if dl is not None:
                bb = dl.extents  # x0,y0,x1,y1
                if all(v == v for v in bb) and abs(bb[2] - bb[0]) < 1e6:
                    if bb[0] < x0: x0 = bb[0] - pad; changed = True
                    if bb[2] > x1: x1 = bb[2] + pad; changed = True
                    if bb[1] < y0: y0 = bb[1] - pad; changed = True
                    if bb[3] > y1: y1 = bb[3] + pad; changed = True
            if changed:
                ax.set_xlim(x0, x1); ax.set_ylim(y0, y1)
                print(f'  ℹ️ 画布已自动扩展以容纳超界图元 → x({x0:.1f}~{x1:.1f}) y({y0:.1f}~{y1:.1f})')
    except Exception as e:
        print('  （画布自适应跳过：', e, '）')
    fig.savefig(path)
    plt.close(fig)
    print('✅ 已绘制', os.path.basename(path), f'({os.path.getsize(path)//1024} KB)')
    print('   ↳ 建议跑裁切质检：~/Downloads/.tools/pyvenv/bin/python scripts/_check_figs.py')
