#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
W20 双版本单页简历生成器（可复用）

输入：src/resume_data.json（唯一内容源，含来源编号 src）
输出：ops.pdf / support.pdf（A4 单页）、html/ops.html / html/support.html（可编辑）

原则：
  1. 所有文案只来自 resume_data.json，脚本不生成任何新事实；
  2. 排版全部在代码内测量，任何文字块宽度/纵向位置越界都会抛异常（不裁切）；
  3. PDF 与 HTML 由同一份数据渲染，保证两版文字一致。

用法：python3 build_resume.py
"""

import json
import os
import sys

from reportlab.lib.colors import HexColor
from reportlab.lib.pagesizes import A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.dirname(HERE)          # outputs/
ROOT = os.path.dirname(OUT)          # W20/

# ---------------------------------------------------------------- 字体（系统内置，无需联网）
FONT_DIR = "/System/Library/Fonts"
F_REG = ("STHeitiSC-Light", os.path.join(FONT_DIR, "STHeiti Light.ttc"), 1)
F_MED = ("STHeitiSC-Medium", os.path.join(FONT_DIR, "STHeiti Medium.ttc"), 1)

REG, MED = "HeiL", "HeiM"

# ---------------------------------------------------------------- 版面常量
PAGE_W, PAGE_H = A4                       # 595.276 x 841.89
ML = MR = 52.0
MT = 46.0
MB = 46.0
CW = PAGE_W - ML - MR                     # 491.28

INK = HexColor("#1A1C1E")
BODY = HexColor("#2B2E32")
GRAY = HexColor("#63676D")
LGRAY = HexColor("#8A8E94")
LINE = HexColor("#D5D3CE")
ACCENT = HexColor("#2E4F47")
WARN = HexColor("#8A6428")
BG = HexColor("#F6F5F2")

BODY_SIZE, BODY_LEAD = 9.3, 14.8
BULLET_SIZE, BULLET_LEAD = 9.15, 14.2
KV_SIZE, KV_LEAD = 8.95, 13.8

NO_START = "，。、；：！？）》」』】”’,.;:!?)]}%·…"
NO_END = "（《「『【“(‘"


def register_fonts():
    for alias, (_, path, idx) in ((REG, F_REG), (MED, F_MED)):
        if not os.path.exists(path):
            raise SystemExit("缺少系统字体：%s" % path)
        pdfmetrics.registerFont(TTFont(alias, path, subfontIndex=idx))


def sw(text, font, size):
    return pdfmetrics.stringWidth(text, font, size)


def ascent(font, size):
    return pdfmetrics.getAscent(font, size)


# ---------------------------------------------------------------- 中英混排行断开
def tokenize(text):
    tokens, buf = [], ""
    for ch in text:
        if ch < "\u2e80" and (ch.isalnum() or ch in "._-+/%@&"):
            buf += ch
        else:
            if buf:
                tokens.append(buf)
                buf = ""
            tokens.append(ch)
    if buf:
        tokens.append(buf)
    return tokens


def wrap(text, font, size, maxw):
    """按中英混排规则折行；行尾禁则/行首禁则都处理，返回 [(line, width)]"""
    tokens = tokenize(text)
    lines, cur = [], ""
    for tk in tokens:
        trial = cur + tk
        if cur and sw(trial, font, size) > maxw:
            if tk in NO_START:
                cur = trial                      # 标点挤进本行，避免行首标点
                lines.append(cur)
                cur = ""
                continue
            if cur[-1] in NO_END:
                cur = cur[:-1]                   # 开引号/括号不下沉到行尾
                if cur:
                    lines.append(cur)
                cur = tk
                continue
            lines.append(cur)
            cur = tk if tk != " " else ""
        else:
            cur = trial
    if cur:
        lines.append(cur)
    out = []
    for ln in lines:
        ln = ln.replace("\u3000\u3000", "\u3000")
        out.append((ln, sw(ln, font, size)))
    return out


# ---------------------------------------------------------------- 排版单元
class Item:
    """h=高度，draw(c,y)=从 y 顶部向下绘制"""

    def __init__(self, h, draw, flex=False):
        self.h, self._draw, self.flex = h, draw, flex

    def draw(self, c, y):
        self._draw(c, y)


def hairline(c, x1, x2, y, color=LINE, w=0.6):
    c.setStrokeColor(color)
    c.setLineWidth(w)
    c.line(x1, y, x2, y)


def text_block(c, x, y, lines, font, size, lead, color, check=None):
    """lines: [(str,width)]，从 y 顶部开始逐行绘制基线"""
    c.setFillColor(color)
    c.setFont(font, size)
    base = y - ascent(font, size)
    for ln, w in lines:
        if check is not None:
            check(x, w, ln)
        c.drawString(x, base, ln)
        base -= lead
    return base


# ---------------------------------------------------------------- 组装整页
def build_page(v, profile, skills, skills_note, edu, sec_bonus=0.0, avail=None):
    items = []
    chk = []            # (kind, x, width, text)
    sec_count = [0]     # 用于给第 2 个及之后的章节加呼吸空间

    # ---- 页眉
    name_h = 30
    head_h = 69

    def draw_header(c, y):
        c.setFillColor(INK)
        c.setFont(MED, 24)
        c.drawString(ML, y - 26, profile["name"])
        nw = sw(profile["name"], MED, 24)
        c.setFillColor(LGRAY)
        c.setFont(REG, 8.2)
        c.drawString(ML + nw + 8, y - 26 + 2.5, profile["name_note"])

        # 右上：求职意向
        c.setFont(REG, 7.6)
        c.setFillColor(LGRAY)
        c.drawRightString(ML + CW, y - 13, "求职意向")
        c.setFont(MED, 11.2)
        c.setFillColor(ACCENT)
        c.drawRightString(ML + CW, y - 27, v["target"])

        c.setFont(REG, 9.4)
        c.setFillColor(BODY)
        c.drawString(ML, y - 43, profile["headline"])
        c.setFont(REG, 8.1)
        c.setFillColor(GRAY)
        c.drawString(ML, y - 54, profile["contact"])

        hairline(c, ML, ML + CW, y - 63, INK, 1.1)
        c.setFillColor(ACCENT)
        c.rect(ML, y - 63, 46, 1.1, stroke=0, fill=1)

    items.append(Item(head_h, draw_header))

    # ---- 章节
    def section(title, top_gap):
        sec_count[0] += 1
        if sec_count[0] > 1:
            top_gap += sec_bonus
        h = top_gap + 17.5
        chk.append(("section", ML, sw(title, MED, 10.6), title))

        def _d(c, y, title=title, top_gap=top_gap):
            yy = y - top_gap
            c.setFillColor(ACCENT)
            c.rect(ML, yy - 7.6, 3.4, 3.4, stroke=0, fill=1)
            c.setFillColor(INK)
            c.setFont(MED, 10.6)
            c.drawString(ML + 9, yy - 8.2, title)
            tw = sw(title, MED, 10.6)
            hairline(c, ML + 9 + tw + 9, ML + CW, yy - 6.2)

        return Item(h, _d)

    # ---- 段落
    def para(lines_text, size=BODY_SIZE, lead=BODY_LEAD, color=BODY,
             font=REG, indent=0.0, space=0):
        lines = []
        for t in lines_text:
            lines += wrap(t, font, size, CW - indent)
        for ln, w in lines:
            chk.append(("para", ML + indent, w, ln))
        h = space + len(lines) * lead
        base_off = space

        def _d(c, y, lines=lines, base_off=base_off):
            text_block(c, ML + indent, y - base_off, lines, font, size, lead, color)

        return Item(h, _d)

    # ---- 条目头（职位 + 时间）
    def entry_head(period, role, org):
        h = 13.4 + 12.4

        def _d(c, y):
            c.setFillColor(INK)
            c.setFont(MED, 10.4)
            c.drawString(ML, y - 9.6, role)
            c.setFillColor(GRAY)
            c.setFont(REG, 8.4)
            c.drawRightString(ML + CW, y - 9.4, period)
            c.setFillColor(GRAY)
            c.setFont(REG, 8.8)
            c.drawString(ML, y - 21.4, org)

        chk.append(("entry", ML, sw(role, MED, 10.4) + 120, role))
        return Item(h, _d)

    # ---- 项目符号
    def bullets(items_text, size=BULLET_SIZE, lead=BULLET_LEAD, space_top=3.0, gap=2.6):
        ind = 11.5
        rows = []
        for t in items_text:
            rows.append(wrap(t, REG, size, CW - ind))
        total = space_top
        for r in rows:
            total += len(r) * lead + gap
        total -= gap

        def _d(c, y, rows=rows, size=size, lead=lead, ind=ind, gap=gap):
            yy = y - space_top
            c.setFont(REG, size)
            for r in rows:
                first_base = yy - ascent(REG, size)
                c.setFillColor(ACCENT)
                c.rect(ML + 1.4, first_base + size * 0.30, 2.4, 2.4, stroke=0, fill=1)
                c.setFillColor(BODY)
                base = first_base
                for ln, w in r:
                    c.drawString(ML + ind, base, ln)
                    base -= lead
                yy -= len(r) * lead + gap

        for r in rows:
            for ln, w in r:
                chk.append(("bullet", ML + ind, w, ln))
        return Item(total, _d)

    # ---- 岗位匹配表
    def match_table(rows, label_w=124.0):
        gap_x = 16.0
        text_w = CW - label_w - gap_x
        prepared = []
        for r in rows:
            lab = wrap(r["label"], MED, 9.5, label_w)
            tag = r.get("tag", "")
            txt = wrap(r["text"], REG, KV_SIZE, text_w)
            h = max(len(lab) * 13.5 + 12.0, len(txt) * KV_LEAD) + 5.6
            prepared.append((lab, tag, txt, h))
            for ln, w in lab:
                chk.append(("label", ML, w, ln))
            for ln, w in txt:
                chk.append(("kvtext", ML + label_w + gap_x, w, ln))
            if w := sw(r["label"], MED, 9.5):
                if w > label_w:
                    raise AssertionError("匹配表标签超宽：%s" % r["label"])

        total = sum(p[3] for p in prepared)

        def _d(c, y, prepared=prepared):
            yy = y
            for i, (lab, tag, txt, h) in enumerate(prepared):
                base = yy - ascent(MED, 9.5)
                c.setFillColor(INK)
                c.setFont(MED, 9.5)
                for ln, w in lab:
                    c.drawString(ML, base, ln)
                    base -= 13.5
                if tag:
                    c.setFont(REG, 7.5)
                    c.setFillColor(ACCENT if tag == "直接匹配" else WARN)
                    c.drawString(ML, base - 0.5, tag)
                base = yy - ascent(REG, KV_SIZE)
                c.setFillColor(BODY)
                c.setFont(REG, KV_SIZE)
                for ln, w in txt:
                    c.drawString(ML + label_w + gap_x, base, ln)
                    base -= KV_LEAD
                yy -= h
                if i < len(prepared) - 1:
                    hairline(c, ML, ML + CW, yy + 4.5, HexColor("#E0DED8"), 0.6)

        return Item(total, _d)

    # ---- 技能行
    def skill_row(names, note):
        size, pad, gap = 9.0, 7.0, 6.0
        widths = [sw(n, REG, size) + pad * 2 for n in names]
        total_w = sum(widths) + gap * (len(names) - 1)
        if total_w > CW:
            raise AssertionError("技能行超宽")
        note_lines = wrap(note, REG, 8.0, CW)
        for ln, w in note_lines:
            chk.append(("note", ML, w, ln))
        h = 20.5 + 6 + len(note_lines) * 12.6

        def _d(c, y, names=names, widths=widths, size=size, pad=pad, gap=gap,
               note_lines=note_lines):
            x = ML
            for n, w in zip(names, widths):
                c.setFillColor(HexColor("#FBFAF8"))
                c.setStrokeColor(LINE)
                c.setLineWidth(0.6)
                c.roundRect(x, y - 19.5, w, 17.5, 3, stroke=1, fill=1)
                c.setFillColor(INK)
                c.setFont(REG, size)
                c.drawString(x + pad, y - 14.6, n)
                x += w + gap
            c.setFillColor(LGRAY)
            c.setFont(REG, 8.0)
            base = y - 22.5 - 6 - ascent(REG, 8.0)
            for ln, w in note_lines:
                c.drawString(ML, base, ln)
                base -= 12.6

        return Item(h, _d)

    # ---- 教育
    def edu_row(e):
        h = 16

        def _d(c, y, e=e):
            c.setFillColor(GRAY)
            c.setFont(REG, 9.0)
            c.drawString(ML, y - 10.5, e["period"])
            c.setFillColor(INK)
            c.setFont(MED, 9.6)
            c.drawString(ML + 74, y - 10.5, e["school"])
            c.setFillColor(BODY)
            c.setFont(REG, 9.2)
            c.drawString(ML + 74 + sw(e["school"], MED, 9.6) + 14, y - 10.5, e["major"])

        return Item(h, _d)

    # ---- 差距说明框
    def gap_box(g):
        lh = 13.9
        pad_x, pad_y = 11.0, 9.0
        lines = []
        for t in g["lines"]:
            lines += wrap(t, REG, 8.75, CW - pad_x * 2 - 2.5)
        for ln, w in lines:
            chk.append(("gap", ML + pad_x, w, ln))
        h = pad_y * 2 + 13.5 + len(lines) * lh

        def _d(c, y, lines=lines, lh=lh, pad_y=pad_y, pad_x=pad_x, g=g):
            c.setFillColor(BG)
            c.setStrokeColor(HexColor("#E6E4DE"))
            c.setLineWidth(0.5)
            c.roundRect(ML, y - h, CW, h, 2.5, stroke=1, fill=1)
            c.setFillColor(ACCENT)
            c.rect(ML, y - h, 2.6, h, stroke=0, fill=1)
            c.setFillColor(INK)
            c.setFont(MED, 9.5)
            c.drawString(ML + pad_x, y - pad_y - 8.2, g["title"])
            base = y - pad_y - 13.5 - 6.2 - ascent(REG, 8.75) + 3.4
            c.setFillColor(BODY)
            c.setFont(REG, 8.75)
            for ln, w in lines:
                c.drawString(ML + pad_x, base, ln)
                base -= lh

        return Item(h, _d)

    # ================================================== 内容顺序
    items.append(section("个人简介", 18))
    items.append(para(v["summary"], space=2))

    items.append(section("岗位要求对应关系", 14))
    items.append(match_table(v["match"]))

    items.append(section("相关经历", 14))
    for i, exp in enumerate(v["experience"]):
        items.append(entry_head(exp["period"], exp["role"], exp["org"]))
        items.append(bullets(exp["bullets"], space_top=3.0))
        if i < len(v["experience"]) - 1:
            items.append(Item(13, lambda c, y: hairline(c, ML, ML + CW, y - 7.0, HexColor("#E4E2DC"), 0.7)))

    items.append(section("技能与工具", 14))
    items.append(skill_row(skills, skills_note))

    items.append(section("教育背景", 14))
    items.append(edu_row(edu))

    items.append(section("差距与边界", 14))
    items.append(gap_box(v["gap"]))

    total = sum(it.h for it in items)
    return items, total, chk, sec_count[0]


def render_pdf(v, profile, skills, skills_note, edu, path):
    avail = PAGE_H - MT - MB - 30          # 底部 30pt 留给页脚
    items, total, chk, nsec = build_page(v, profile, skills, skills_note, edu, 0.0)
    slack = avail - total
    if slack < 0:
        raise AssertionError("内容超出单页 %.1fpt，需缩短文案" % (-slack))
    # 把剩余空间均摊到第 2 个及之后的章节间距，最多 11pt，重新测量一次
    bonus = 0.0
    if nsec > 1:
        bonus = min(slack / (nsec - 1), 11.0) * 0.95
        items, total, chk, _ = build_page(v, profile, skills, skills_note, edu, bonus)
        slack = avail - total
        if slack < 0:                    # 二次校正，保证仍在单页内
            bonus = max(0.0, bonus + slack / max(nsec - 1, 1))
            items, total, chk, _ = build_page(v, profile, skills, skills_note, edu, bonus)
            slack = avail - total
        if slack < 0:
            raise AssertionError("加入间距后超页 %.1fpt" % (-slack))

    c = canvas.Canvas(path, pagesize=A4)
    c.setTitle("%s - %s" % (profile["name"], v["target"]))
    c.setAuthor(profile["name"])
    c.setSubject("合成练习简历（虚构人物）")
    c.setCreator("W20 build_resume.py")
    c.setKeywords("resume, practice, synthetic")

    # 页脚
    c.setFillColor(LGRAY)
    c.setFont(REG, 7.4)
    c.drawString(ML, MB - 24, profile["footer"])
    hairline(c, ML, ML + CW, MB - 12, HexColor("#E8E6E1"), 0.5)

    y = PAGE_H - MT
    for it in items:
        it.draw(c, y)
        y -= it.h

    bottom_ink = y
    c.showPage()
    c.save()

    # 越界断言：所有文字块宽度不超过版心，且正文最低点高于页脚
    for kind, x, w, text in chk:
        if x + w > ML + CW + 0.9:
            raise AssertionError("[%s] 横向越界 %.1f: %s" % (kind, x + w - (ML + CW), text))
    if bottom_ink < MB + 6:
        raise AssertionError("纵向越界：内容底部 %.1f < %.1f" % (bottom_ink, MB + 6))

    return {
        "pdf": os.path.relpath(path, OUT),
        "content_height": round(total, 2),
        "available_height": round(avail, 2),
        "slack_pt": round(slack, 2),
        "gap_bonus_pt": round(bonus, 2),
        "bottom_ink_y": round(bottom_ink, 2),
        "blocks": len(items),
        "text_checks": len(chk),
    }


# ---------------------------------------------------------------- HTML（同源渲染，可编辑）
HTML_TPL = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>{name} · {target} · 单页简历（可编辑原稿）</title>
<style>
  @page {{ size: A4; margin: 0; }}
  * {{ box-sizing: border-box; }}
  html {{ background: #EDEBE6; }}
  body {{
    margin: 0; padding: 24px 0;
    font-family: "STHeitiSC-Light", "Heiti SC", "Hiragino Sans GB", "Songti SC", "Microsoft YaHei", sans-serif;
    color: #2B2E32; -webkit-font-smoothing: antialiased;
  }}
  .sheet {{
    width: 210mm; min-height: 297mm; margin: 0 auto; background: #fff;
    padding: 16.2mm 18.3mm 16.2mm 18.3mm; position: relative;
    box-shadow: 0 1px 3px rgba(0,0,0,.14), 0 8px 28px rgba(0,0,0,.10);
  }}
  header {{ border-bottom: 1.1pt solid #1A1C1E; padding-bottom: 7px; position: relative; }}
  header::after {{ content: ""; position: absolute; left: 0; bottom: -1.1pt; width: 46pt; height: 1.1pt; background: #2E4F47; }}
  h1 {{ font-family: "STHeitiSC-Medium","Heiti SC",sans-serif; font-size: 25px; font-weight: 500; margin: 0; letter-spacing: .5px; color: #1A1C1E; }}
  h1 small {{ font-size: 8.2px; color: #8A8E94; font-weight: 400; margin-left: 8px; letter-spacing: 0; }}
  .target {{ position: absolute; right: 0; top: 2px; text-align: right; }}
  .target em {{ display: block; font-style: normal; font-size: 7.6px; color: #8A8E94; }}
  .target b {{ display: block; font-size: 11.2px; color: #2E4F47; font-weight: 500; margin-top: 2px; }}
  .headline {{ font-size: 9.4px; margin-top: 9px; color: #2B2E32; }}
  .contact {{ font-size: 8.1px; color: #63676D; margin-top: 4px; }}
  h2 {{
    font-family: "STHeitiSC-Medium","Heiti SC",sans-serif; font-size: 10.6px; font-weight: 500;
    color: #1A1C1E; margin: 17px 0 8px; display: flex; align-items: center; gap: 8px;
  }}
  h2::before {{ content: ""; width: 3.4px; height: 3.4px; background: #2E4F47; flex: 0 0 auto; }}
  h2::after {{ content: ""; flex: 1; height: .6px; background: #D5D3CE; }}
  p {{ margin: 0 0 3px; font-size: 9.3px; line-height: 1.6; }}
  dl.match {{ margin: 0; }}
  .row {{ display: flex; gap: 16px; padding: 7px 0; border-bottom: .5px solid #E4E2DD; }}
  .row:last-child {{ border-bottom: 0; }}
  .row dt {{ width: 124px; flex: 0 0 124px; margin: 0; }}
  .row dt span {{ display: block; font-family: "STHeitiSC-Medium",sans-serif; font-size: 9.5px; color: #1A1C1E; }}
  .row dt i {{ display: block; font-style: normal; font-size: 7.5px; margin-top: 3px; color: #2E4F47; }}
  .row dt i.partial {{ color: #8A6428; }}
  .row dd {{ margin: 0; font-size: 8.95px; line-height: 1.54; }}
  .job {{ margin-top: 4px; }}
  .job-head {{ display: flex; justify-content: space-between; align-items: baseline; }}
  .job-head strong {{ font-family: "STHeitiSC-Medium",sans-serif; font-size: 10.4px; font-weight: 500; color: #1A1C1E; }}
  .job-head time {{ font-size: 8.4px; color: #63676D; }}
  .org {{ font-size: 8.8px; color: #63676D; margin-top: 2px; }}
  ul {{ margin: 3px 0 0; padding: 0; list-style: none; }}
  li {{ position: relative; font-size: 9.15px; line-height: 1.55; padding-left: 11.5px; margin-bottom: 2.6px; }}
  li::before {{ content: ""; position: absolute; left: 1.4px; top: .62em; width: 2.4px; height: 2.4px; background: #2E4F47; }}
  .skills {{ display: flex; gap: 6px; margin: 4px 0 6px; flex-wrap: wrap; }}
  .chip {{ font-size: 9px; padding: 3.4px 7px; border: .6px solid #D5D3CE; border-radius: 3px; background: #FBFAF8; color: #1A1C1E; }}
  .note {{ font-size: 8px; color: #8A8E94; }}
  .edu {{ display: flex; gap: 14px; font-size: 9.2px; margin-top: 4px; align-items: baseline; }}
  .edu .period {{ font-size: 9px; color: #63676D; width: 60px; }}
  .edu .school {{ font-family: "STHeitiSC-Medium",sans-serif; font-size: 9.6px; color: #1A1C1E; }}
  .gap {{ background: #F6F5F2; border: .5px solid #E6E4DE; border-left: 2.6px solid #2E4F47; border-radius: 2.5px; padding: 10px 11px; margin-top: 4px; }}
  .gap h3 {{ font-family: "STHeitiSC-Medium",sans-serif; font-size: 9.5px; font-weight: 500; color: #1A1C1E; margin: 0 0 6px; }}
  .gap p {{ font-size: 8.75px; line-height: 1.59; margin-bottom: 3px; }}
  footer {{ margin-top: 22px; border-top: .5px solid #E8E6E1; padding-top: 7px; font-size: 7.4px; color: #8A8E94; }}
  @media print {{
    html {{ background: #fff; }}
    body {{ padding: 0; }}
    .sheet {{ box-shadow: none; margin: 0; width: auto; min-height: auto; }}
  }}
</style>
</head>
<body>
<div class="sheet">
<header>
  <h1>{name}<small>{name_note}</small></h1>
  <div class="target"><em>求职意向</em><b>{target}</b></div>
  <div class="headline">{headline}</div>
  <div class="contact">{contact}</div>
</header>

<h2>个人简介</h2>
{summary}

<h2>岗位要求对应关系</h2>
<dl class="match">
{match}
</dl>

<h2>相关经历</h2>
{experience}

<h2>技能与工具</h2>
<div class="skills">{chips}</div>
<p class="note">{skills_note}</p>

<h2>教育背景</h2>
<div class="edu"><span class="period">{edu_period}</span><span class="school">{edu_school}</span><span>{edu_major}</span></div>

<h2>已知差距</h2>
<div class="gap">
  <h3>{gap_title}</h3>
  {gap_lines}
</div>

<footer>{footer}</footer>
</div>
</body>
</html>
"""


def build_html(v, profile, skills, skills_note, edu, path):
    def esc(s):
        return (s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))

    summary = "\n".join(
        '<p data-src="%s">%s</p>' % ("S%d" % (i + 1), esc(t))
        for i, t in enumerate(v["summary"])
    )

    match = []
    for i, r in enumerate(v["match"]):
        partial = " partial" if r.get("tag") == "部分匹配" else ""
        match.append(
            '  <div class="row" data-src="%s">\n'
            '    <dt><span>%s</span><i class="%s">%s</i></dt>\n'
            '    <dd>%s</dd>\n'
            '  </div>' % (
                "+".join(r["src"]), esc(r["label"]), partial.strip(), esc(r.get("tag", "")),
                esc(r["text"]))
        )

    exp = []
    for e in v["experience"]:
        lis = "\n".join(
            '      <li data-src="%s">%s</li>' % (e["src"][i] if i < len(e["src"]) else "", esc(b))
            for i, b in enumerate(e["bullets"]))
        exp.append(
            '  <section class="job" data-src="%s">\n'
            '    <div class="job-head"><strong>%s</strong><time>%s</time></div>\n'
            '    <div class="org">%s</div>\n'
            '    <ul>\n%s\n    </ul>\n'
            '  </section>' % ("+".join(e["src"]), esc(e["role"]), esc(e["period"]), esc(e["org"]), lis)
        )

    html = HTML_TPL.format(
        name=esc(profile["name"]), name_note=esc(profile["name_note"]),
        target=esc(v["target"]), headline=esc(profile["headline"]),
        contact=esc(profile["contact"]),
        summary=summary, match="\n".join(match), experience="\n".join(exp),
        chips="".join('<span class="chip">%s</span>' % esc(s) for s in skills),
        skills_note=esc(skills_note),
        edu_period=esc(edu["period"]), edu_school=esc(edu["school"]), edu_major=esc(edu["major"]),
        gap_title=esc(v["gap"]["title"]),
        gap_lines="\n  ".join("<p>%s</p>" % esc(t) for t in v["gap"]["lines"]),
        footer=esc(profile["footer"]),
    )
    with open(path, "w", encoding="utf-8") as f:
        f.write(html)


def main():
    register_fonts()
    with open(os.path.join(HERE, "resume_data.json"), encoding="utf-8") as f:
        data = json.load(f)

    profile = data["profile"]
    meta = {}
    for vid in ("ops", "support"):
        v = data["variants"][vid]
        pdf_path = os.path.join(OUT, "%s.pdf" % vid)
        html_path = os.path.join(OUT, "html", "%s.html" % vid)
        info = render_pdf(v, profile, data["skills"], data["skills_note"], data["education"], pdf_path)
        build_html(v, profile, data["skills"], data["skills_note"], data["education"], html_path)
        info["html"] = os.path.relpath(html_path, OUT)
        meta[vid] = info
        print("[ok] %s.pdf  content=%.1f/%.1f  slack=%.1f  bottom=%.1f" %
              (vid, info["content_height"], info["available_height"],
               info["slack_pt"], info["bottom_ink_y"]))
    with open(os.path.join(OUT, "checks", "build_meta.json"), "w", encoding="utf-8") as f:
        json.dump(meta, f, ensure_ascii=False, indent=2)


if __name__ == "__main__":
    main()
