# -*- coding: utf-8 -*-
"""WBS 树形图排版引擎（可靠版，替代失效的 `_wbs.py`）。

背景（2026-10-15，主 agent 复盘）：
    旧引擎 `_wbs.py::draw_wbs_stack` 在"节点多、两列分组"的实际输入下**坐标塌缩**——
    输出表现为文字全部叠在一起、根节点被画布顶边裁掉、画布大面积空白（图 4-4、图 4-5 均如此）。
    本引擎改为**先算高度、再逐行定位**，绝不重叠，并在写图后由 `_check_figs.py` 兜底校验。

用法：
    from _wbs_layout import draw_wbs
    draw_wbs(GROUPS, '教务管理系统', '图 4-5　按可交付成果创建 WBS', OUT)
    # GROUPS = [(组名, [(一级条目, [二级条目, ...]), ...]), ...]  共 6 组 → 分两列各 3 组
"""
import os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _draw import setup, canvas, box, line, save, NAV, ACC, LINE, FILL

AREA_TOP, AREA_BOT = 88.0, 3.2
GAP_GROUP = 2.6
HEAD_H = 3.4
ROW_H_UNIT = 2.55


def _rows(g):
    return sum(1 + len(subs) for _, subs in g[1])


def _col_units(col):
    return sum(HEAD_H + _rows(g) * ROW_H_UNIT + GAP_GROUP for g in col)


def draw_wbs(groups, root, caption, out, cols=2):
    assert len(groups) >= 2, '至少两组'
    per = (len(groups) + cols - 1) // cols
    columns = [groups[i * per:(i + 1) * per] for i in range(cols)]

    need = max(_col_units(c) for c in columns)
    avail = AREA_TOP - AREA_BOT
    scale = min(1.0, avail / need)
    ROW_H = ROW_H_UNIT * scale
    HEAD = HEAD_H * scale
    GAP = GAP_GROUP * scale
    FS_L1 = max(7.4, 9.6 * scale)
    FS_L2 = max(6.6, 8.6 * scale)
    FS_G = FS_L1 + 1.3

    setup()
    fig, ax = canvas(w=13.2, h=10.6)

    box(ax, 34, 99, 32, 7.5, root, fc=NAV, ec=NAV, tc='white', bold=True, fs=12.5)
    line(ax, (50, 91.5), (50, 88.8), color=ACC, lw=1.5)

    span = 100.0 / cols
    xs = [(i * span + 2.0, (i + 1) * span - 1.5) for i in range(cols)]
    line(ax, (xs[0][0] + 1.0, 88.8), (xs[-1][1] - 1.0, 88.8), color=ACC, lw=1.5)
    for x0, x1 in xs:
        cx = (x0 + x1) / 2
        line(ax, (cx, 88.8), (cx, AREA_TOP), color=ACC, lw=1.5)

    def draw_column(col, x0, x1):
        w = x1 - x0
        ind1, ind2 = w * 0.15, w * 0.33
        y = AREA_TOP
        for gname, items in col:
            gtop = y
            ax.text(x0, y - HEAD / 2, gname, ha='left', va='center',
                    color=NAV, fontsize=FS_G, fontweight='bold')
            y -= HEAD
            for l1, subs in items:
                # 肘形连线：横线 + 短竖线
                ax.plot([x0 + 0.8, x0 + ind1 - 1.2], [y - ROW_H / 2, y - ROW_H / 2],
                        color=LINE, lw=1.0)
                ax.plot([x0 + 0.8, x0 + 0.8], [gtop - HEAD + 0.3, y - ROW_H / 2],
                        color=LINE, lw=0.9)
                ax.text(x0 + ind1, y - ROW_H / 2, l1, ha='left', va='center',
                        color='#1a202c', fontsize=FS_L1)
                y -= ROW_H
                for s in subs:
                    ax.plot([x0 + ind1 + 1.0, x0 + ind2 - 1.2], [y - ROW_H / 2, y - ROW_H / 2],
                            color=LINE, lw=0.9)
                    ax.plot([x0 + ind1 + 1.0, x0 + ind1 + 1.0], [y - ROW_H / 2 + ROW_H, y - ROW_H / 2],
                            color=LINE, lw=0.8)
                    ax.text(x0 + ind2, y - ROW_H / 2, s, ha='left', va='center',
                            color='#2d3748', fontsize=FS_L2)
                    y -= ROW_H
            y -= GAP
        return y

    for (x0, x1), col in zip(xs, columns):
        draw_column(col, x0, x1)

    ax.text(50, 1.0, caption, ha='center', va='bottom', color=NAV,
            fontsize=12, fontweight='bold')
    return save(fig, out)
