File size: 35,724 Bytes
8cf30a3
 
 
 
59461d8
 
 
8cf30a3
59461d8
 
8cf30a3
59461d8
 
 
8cf30a3
 
 
 
 
59461d8
7dffd90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf30a3
 
 
 
 
 
 
 
 
 
 
59461d8
8cf30a3
59461d8
 
 
8cf30a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59461d8
8cf30a3
59461d8
 
 
 
7dffd90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59461d8
 
8cf30a3
 
 
 
59461d8
 
8cf30a3
59461d8
 
 
8cf30a3
 
 
59461d8
8cf30a3
 
 
 
 
 
59461d8
 
 
 
8cf30a3
59461d8
 
 
8cf30a3
 
 
 
 
 
 
 
 
59461d8
8cf30a3
 
 
59461d8
8cf30a3
 
 
 
59461d8
8cf30a3
 
 
 
59461d8
 
 
 
 
 
8cf30a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
06dbd61
 
 
 
 
 
 
 
 
 
 
 
 
8cf30a3
 
 
 
 
7dffd90
 
8cf30a3
 
 
 
 
 
 
 
 
7dffd90
8cf30a3
 
 
 
 
 
 
 
7dffd90
 
8cf30a3
 
 
 
 
 
 
 
 
 
 
 
 
7dffd90
 
 
 
 
 
 
 
 
 
 
 
 
 
59461d8
 
8cf30a3
 
 
 
 
 
 
 
 
 
 
59461d8
8cf30a3
59461d8
8cf30a3
 
 
 
 
59461d8
8cf30a3
 
 
59461d8
988e3ef
8cf30a3
 
 
 
 
 
 
 
98e0107
8cf30a3
 
 
98e0107
8cf30a3
 
98e0107
 
 
8cf30a3
 
98e0107
8cf30a3
98e0107
 
 
8cf30a3
 
 
 
 
 
 
 
59461d8
8cf30a3
 
59461d8
8cf30a3
 
 
 
 
 
 
 
 
59461d8
8cf30a3
59461d8
 
 
 
8cf30a3
59461d8
8cf30a3
59461d8
98e0107
59461d8
 
8cf30a3
59461d8
 
 
 
 
 
 
 
 
 
 
8cf30a3
59461d8
 
 
 
 
 
 
e814ba8
 
 
8cf30a3
e814ba8
 
 
13b1da5
e814ba8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d275eab
 
06dbd61
d275eab
 
 
06dbd61
d275eab
 
 
e814ba8
 
 
 
 
 
 
59461d8
 
8cf30a3
34158ed
 
 
 
 
06f8709
06dbd61
06f8709
06dbd61
06f8709
 
59461d8
34158ed
39941ec
 
 
 
59461d8
 
8cf30a3
59461d8
 
 
81285b7
 
8cf30a3
 
 
 
 
 
 
 
 
 
 
 
 
81285b7
 
 
 
 
 
 
6efc5f4
 
8cf30a3
 
81285b7
 
 
6c814fb
 
 
 
d275eab
 
 
6c814fb
06dbd61
 
6c814fb
 
 
 
 
 
 
 
 
 
 
 
 
 
8cf30a3
6c814fb
 
 
 
 
8cf30a3
6c814fb
 
 
 
 
 
 
 
 
 
 
 
 
8cf30a3
6c814fb
 
 
 
d275eab
 
 
 
 
 
8cf30a3
 
 
 
 
98e0107
 
 
8cf30a3
98e0107
 
 
06dbd61
98e0107
06dbd61
81285b7
59461d8
 
8cf30a3
59461d8
 
 
 
 
 
 
 
 
 
 
 
98e0107
 
8cf30a3
98e0107
 
 
 
 
 
59461d8
 
98e0107
 
 
 
 
8cf30a3
98e0107
 
 
 
 
 
59461d8
e814ba8
 
 
8cf30a3
e814ba8
 
 
 
 
 
 
 
06dbd61
e814ba8
06dbd61
e814ba8
 
8cf30a3
 
 
 
 
 
 
 
59461d8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
"""Vitals PDF report — typeset with reportlab in the EmergentSignals design system: the navy
ground, Inter / Newsreader / IBM Plex Mono (the same files the web app serves), hairline rules,
numbered mono section heads and the three signal states. Built directly from the result payload;
tolerates missing sections (no LLM, no target)."""
from __future__ import annotations

import io
from pathlib import Path

from reportlab.lib import colors
from reportlab.lib.fonts import addMapping
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.units import mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Flowable
from reportlab.platypus import Paragraph as _RLParagraph
from reportlab.platypus import SimpleDocTemplate, Spacer, Table, TableStyle

# ── EmergentSignals tokens. Two themes share one layout: "dark" mirrors the site (rules are its
#    white-at-9%/16% flattened onto the navy); "print" is the same system on white paper with
#    navy ink and the state colours deepened for legibility in print. The logo keeps its exact
#    brand colours in both. ──
_THEMES = {
    "dark": {"BG": "#08111c", "TEXT": "#f3f7fb", "TEXT2": "#a8b4c3", "MUTED": "#748399",
             "RULE": "#1e2630", "RULE_STRONG": "#303740",
             "GOOD": "#20c997", "WARN": "#f2c14e", "BAD": "#e76f6f"},
    "print": {"BG": None, "TEXT": "#08111c", "TEXT2": "#3b4757", "MUTED": "#6b778a",
              "RULE": "#dde3ea", "RULE_STRONG": "#aeb8c5",
              "GOOD": "#0f8a66", "WARN": "#9a6d08", "BAD": "#c0453f"},
}
BRAND_REJECTED = colors.HexColor("#e76f6f")
BRAND_CANDIDATE = colors.HexColor("#f2c14e")
BRAND_VALIDATED = colors.HexColor("#20c997")
_THEME = "dark"
BG = colors.HexColor("#08111c")
TEXT = colors.HexColor("#f3f7fb")
TEXT2 = colors.HexColor("#a8b4c3")
MUTED = colors.HexColor("#748399")
RULE = colors.HexColor("#1e2630")
RULE_STRONG = colors.HexColor("#303740")
GOOD = colors.HexColor("#20c997")      # state: validated
WARN = colors.HexColor("#f2c14e")      # state: candidate
BAD = colors.HexColor("#e76f6f")       # state: rejected
# legacy names used further down
INK, BRASS, DIM, LINE = TEXT2, TEXT, MUTED, RULE

_ACTION_COLOR = {"Buy More": GOOD, "Keep": TEXT2, "Trim": WARN, "Sell": BAD}
_SEV_COLOR = {"good": GOOD, "warn": WARN, "bad": BAD, "OK": GOOD, "WATCH": WARN, "ALERT": BAD}


def _hex(c) -> str:
    return "#" + c.hexval()[2:]


_FONT_DIR = Path(__file__).resolve().parent.parent / "static" / "fonts"


def _register_fonts() -> bool:
    try:
        for name, fn in (("Inter", "Inter-400"), ("Inter-Light", "Inter-300"), ("Inter-Medium", "Inter-500"),
                         ("Inter-SemiBold", "Inter-600"), ("Newsreader", "Newsreader-400"),
                         ("Newsreader-Italic", "Newsreader-400-italic"), ("Newsreader-Medium", "Newsreader-500"),
                         ("PlexMono", "IBMPlexMono-400"), ("PlexMono-Medium", "IBMPlexMono-500")):
            pdfmetrics.registerFont(TTFont(name, str(_FONT_DIR / f"{fn}.ttf")))
        # <b> is Inter Medium, as on the site (500, never a heavy bold)
        for fam, reg, bold, ital in (("Inter", "Inter", "Inter-Medium", "Inter"),
                                     ("Newsreader", "Newsreader", "Newsreader-Medium", "Newsreader-Italic"),
                                     ("PlexMono", "PlexMono", "PlexMono-Medium", "PlexMono")):
            addMapping(fam, 0, 0, reg); addMapping(fam, 1, 0, bold)
            addMapping(fam, 0, 1, ital); addMapping(fam, 1, 1, bold if fam != "Newsreader" else ital)
        return True
    except Exception:
        return False


_FONTS_OK = _register_fonts()
SANS = "Inter" if _FONTS_OK else "Helvetica"
SANS_LIGHT = "Inter-Light" if _FONTS_OK else "Helvetica"
SANS_MED = "Inter-Medium" if _FONTS_OK else "Helvetica-Bold"
SANS_SEMI = "Inter-SemiBold" if _FONTS_OK else "Helvetica-Bold"
SERIF = "Newsreader" if _FONTS_OK else "Times-Roman"
MONO = "PlexMono" if _FONTS_OK else "Courier"


def Paragraph(text, style, *a, **k):   # noqa: N802 — bold runs are the site's white, body stays secondary
    t = str(text).replace("<b>", f"<font color='{_hex(TEXT)}'><b>").replace("</b>", "</b></font>")
    return _RLParagraph(t, style, *a, **k)


def _sty(name, **kw):
    base = dict(fontName=SANS, fontSize=8.8, leading=13.2, textColor=TEXT2)
    base.update(kw)
    return ParagraphStyle(name, **base)  # type: ignore[arg-type]


def _build_styles():
    global S_TITLE, S_TAG, S_LABEL, S_H2, S_SUB, S_BODY, S_VERDICT, S_LEAD, S_DIM, S_CELL
    S_TITLE = _sty("t", fontName=SERIF, fontSize=30, leading=32, textColor=TEXT)
    S_TAG = _sty("tag", fontName=MONO, fontSize=6.8, leading=10, textColor=MUTED)
    S_LABEL = _sty("lab", fontName=MONO, fontSize=6.5, leading=9, textColor=MUTED)
    S_H2 = _sty("h2", fontName=MONO, fontSize=7, leading=10, textColor=TEXT, spaceBefore=12, spaceAfter=5)
    S_SUB = _sty("sub", fontName=MONO, fontSize=6.8, leading=10, textColor=TEXT, spaceBefore=8, spaceAfter=3)
    S_BODY = _sty("b")
    S_VERDICT = _sty("v", fontName=SERIF, fontSize=14, leading=18, textColor=TEXT)
    S_LEAD = _sty("lead", fontName=SANS, fontSize=12.5, leading=17, textColor=TEXT)
    S_DIM = _sty("d", fontSize=7.4, leading=10.5, textColor=MUTED)
    S_CELL = _sty("c", fontSize=7.8, leading=10.8)


def _apply_theme(name: str) -> None:
    """Swap the palette (and the styles built from it) for 'dark' or 'print'."""
    global _THEME, INK, BRASS, DIM, LINE, _ACTION_COLOR, _SEV_COLOR
    name = name if name in _THEMES else "dark"
    g = globals()
    for k, v in _THEMES[name].items():
        g[k] = colors.HexColor(v) if v else None
    _THEME = name
    INK, BRASS, DIM, LINE = TEXT2, TEXT, MUTED, RULE
    _ACTION_COLOR = {"Buy More": GOOD, "Keep": TEXT2, "Trim": WARN, "Sell": BAD}
    _SEV_COLOR = {"good": GOOD, "warn": WARN, "bad": BAD, "OK": GOOD, "WATCH": WARN, "ALERT": BAD}
    _build_styles()


_build_styles()


_UNI = {"✕": "×", "✗": "×", "⚠": "!", "✓": "+", "🟢": "", "🔁": "", "🔻": "", "⏸": "", "👁": ""}
_UNI_FALLBACK = {"—": "-", "–": "-", "→": "->", "←": "<-", "≈": "~", "≥": ">=", "≤": "<=",
                 "↑": "up", "↓": "down", "•": "-", "‘": "'", "’": "'", "“": '"', "”": '"',
                 "₹": "Rs ", "…": "...", "●": "*", "×": "x", "−": "-"}


def _txt(x, serif: bool = False) -> str:
    s = str(x if x is not None else "")
    for u, a in _UNI.items():
        s = s.replace(u, a)
    if not _FONTS_OK:                       # core-font fallback: latin-1 only
        for u, a in _UNI_FALLBACK.items():
            s = s.replace(u, a)
    s = s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
    if not _FONTS_OK:
        return s.encode("latin-1", "replace").decode("latin-1")
    if serif:                               # Newsreader has no arrows: borrow Inter's
        for ch in "→←↑↓":
            s = s.replace(ch, f"<font name='{SANS}'>{ch}</font>")
    return s


def _pct(x, signed=True):
    if not isinstance(x, (int, float)):
        return "–"
    return f"{x * 100:+.1f}%" if signed else f"{x * 100:.1f}%"


def _mono(text, color=None, size=6.6) -> str:
    """Inline mono label (uppercase, the site's .label)."""
    return f"<font name='{MONO}' size='{size}' color='{_hex(color or MUTED)}'>{_txt(str(text).upper())}</font>"


def _dot(color) -> str:
    return f"<font name='{SANS}' color='{_hex(color)}'>●</font>"


def _table(data, widths, header=True, aligns=None):
    if header:                               # uppercase BEFORE the table copies its cells
        data[0] = [str(c).upper() if isinstance(c, str) else c for c in data[0]]
    t = Table(data, colWidths=widths, repeatRows=1 if header else 0, hAlign="LEFT")
    style = [("VALIGN", (0, 0), (-1, -1), "TOP"),
             ("FONT", (0, 0), (-1, -1), SANS, 7.8), ("TEXTCOLOR", (0, 0), (-1, -1), TEXT2),
             ("LINEBELOW", (0, 1 if header else 0), (-1, -1), 0.45, RULE),
             ("LEFTPADDING", (0, 0), (-1, -1), 0), ("RIGHTPADDING", (0, 0), (-1, -1), 6),
             ("TOPPADDING", (0, 0), (-1, -1), 5), ("BOTTOMPADDING", (0, 0), (-1, -1), 5)]
    if header:
        style += [("FONT", (0, 0), (-1, 0), MONO, 6.4),
                  ("TEXTCOLOR", (0, 0), (-1, 0), MUTED),
                  ("BOTTOMPADDING", (0, 0), (-1, 0), 6),
                  ("LINEBELOW", (0, 0), (-1, 0), 0.6, RULE_STRONG)]
    for i, a in enumerate(aligns or []):
        style.append(("ALIGN", (i, 0), (i, -1), a))
    t.setStyle(TableStyle(style))
    return t


class _Head(Flowable):
    """Numbered mono section head under a hairline — the site's '01  Where the risk sits'."""
    def __init__(self, n: int, title: str):
        super().__init__()
        self.n, self.title = n, str(title)
        self.keepWithNext = True

    def wrap(self, aw, ah):
        self.aw = aw
        return aw, 34

    def draw(self):
        c = self.canv
        c.setStrokeColor(RULE); c.setLineWidth(0.5); c.line(0, 30, self.aw, 30)
        c.setFont(MONO, 7); c.setFillColor(MUTED)
        c.drawString(0, 12, f"{self.n:02d}", charSpace=0.4)
        c.setFillColor(TEXT)
        c.drawString(20, 12, self.title.upper().replace("—", "·"), charSpace=0.45)


class _HealthBlock(Flowable):
    """Large light numeral + rail with a state-coloured knob + the six pillars."""
    def __init__(self, score, pillars, width):
        super().__init__()
        self.score = score if isinstance(score, (int, float)) else None
        self.pillars = pillars or []
        self.w = width

    def wrap(self, aw, ah):
        return self.w, 86 + 13.5 * len(self.pillars)

    def draw(self):
        c, w = self.canv, self.w
        h = 86 + 13.5 * len(self.pillars)
        y = h
        c.setFont(MONO, 6.5); c.setFillColor(MUTED); c.drawString(0, y - 8, "PORTFOLIO HEALTH", charSpace=0.5)
        num = "–" if self.score is None else f"{self.score:.0f}"
        c.setFont(SANS_LIGHT, 40); c.setFillColor(TEXT); c.drawString(0, y - 50, num)
        nw = pdfmetrics.stringWidth(num, SANS_LIGHT, 40)
        c.setFont(MONO, 6.8); c.setFillColor(MUTED); c.drawString(nw + 6, y - 50, "/ 100")
        ry = y - 64
        c.setStrokeColor(RULE_STRONG); c.setLineWidth(0.6); c.line(0, ry, w, ry)
        if self.score is not None:
            at = max(0.0, min(100.0, float(self.score))) / 100 * w
            c.setStrokeColor(TEXT); c.setLineWidth(1.4); c.line(0, ry, at, ry)
            kc = GOOD if self.score >= 70 else WARN if self.score >= 45 else BAD
            c.setFillColor(kc); c.circle(at, ry, 3.2, stroke=0, fill=1)
        c.setFont(MONO, 5.6); c.setFillColor(MUTED)
        c.drawString(0, ry - 8, "0"); c.drawRightString(w, ry - 8, "100")
        py = ry - 22
        for p in self.pillars:
            sc = float(p.get("score") or 0)
            col = GOOD if sc >= 65 else TEXT2 if sc >= 45 else WARN if sc >= 30 else BAD
            c.setStrokeColor(RULE); c.setLineWidth(0.4); c.line(0, py + 9.5, w, py + 9.5)
            c.setFont(SANS, 7.2); c.setFillColor(TEXT2)
            c.drawString(0, py, f"{p.get('label')}")
            c.setFont(MONO, 5.8); c.setFillColor(MUTED)
            c.drawString(pdfmetrics.stringWidth(str(p.get("label")), SANS, 7.2) + 4, py, f"{(p.get('weight') or 0) * 100:.0f}%")
            bx, bw = w * 0.56, w * 0.30
            c.setStrokeColor(RULE_STRONG); c.setLineWidth(0.5); c.line(bx, py + 2.5, bx + bw, py + 2.5)
            c.setStrokeColor(col); c.setLineWidth(1.6); c.line(bx, py + 2.5, bx + bw * max(0.02, sc / 100), py + 2.5)
            c.setFont(MONO, 6.6); c.setFillColor(TEXT); c.drawRightString(w, py, f"{sc:.0f}")
            py -= 13.5


def br_text(br: dict) -> str:
    """Benchmark-relative stats in words: 'active return +9.1%/yr', never 'active return ann 0.0908'."""
    lab = {"upside_capture": "upside capture", "downside_capture": "downside capture", "sortino": "Sortino",
           "calmar": "Calmar", "active_return_ann": "active return", "information_ratio": "information ratio"}
    out = []
    for k, v in br.items():
        if not isinstance(v, (int, float)):
            continue
        out.append(f"{lab.get(k, k.replace('_', ' '))} {v * 100:+.1f}%/yr" if k.endswith("_ann") or "return" in k
                   else f"{lab.get(k, k.replace('_', ' '))} {v:.2f}")
    return ", ".join(out)


def _wordmark(c, x, y, size=11.5):
    """Vitals, set like the EmergentSignals wordmark: the three state circles, then the name in Inter
    600 with the green-dot i."""
    mw, mh = 0.705 * size, 0.581 * size
    sx, sy = mw / 61.3, mh / 50.5
    for cx, cy, r, col in ((8.3, 42.2, 8.3, BRAND_REJECTED), (27.75, 27.81, 9.9, BRAND_CANDIDATE),
                           (49.78, 11.51, 11.5, BRAND_VALIDATED)):
        c.setFillColor(col); c.circle(x + cx * sx, y + (50.5 - cy) * sy, r * sx, stroke=0, fill=1)
    tx = x + mw + 0.22 * size
    c.setFillColor(TEXT)
    c.setFont(SANS_SEMI, size); c.drawString(tx, y, "V")
    tx += pdfmetrics.stringWidth("V", SANS_SEMI, size)
    dotless = "ı" if _FONTS_OK else "i"
    c.drawString(tx, y, dotless)
    iw = pdfmetrics.stringWidth(dotless, SANS_SEMI, size)
    if _FONTS_OK:
        c.setFillColor(BRAND_VALIDATED); c.circle(tx + iw / 2 + 0.01 * size, y + 0.70 * size, 0.09 * size, stroke=0, fill=1)
        c.setFillColor(TEXT)
    tx += iw
    c.drawString(tx, y, "tals")


def _page(c, doc):
    w, h = A4
    c.saveState()
    if BG is not None:                   # the print theme leaves the paper white — no ink flood
        c.setFillColor(BG); c.rect(0, 0, w, h, stroke=0, fill=1)
    _wordmark(c, 16 * mm, h - 11.5 * mm)
    c.setFont(MONO, 6.4); c.setFillColor(TEXT)
    right = "YOUR PORTFOLIO'S AI HEALTH CHECK"
    rw = pdfmetrics.stringWidth(right, MONO, 6.4) + 0.4 * len(right)
    c.setFillColor(MUTED); c.drawString(w - 16 * mm - rw, h - 11.2 * mm, right, charSpace=0.4)
    c.setStrokeColor(RULE); c.setLineWidth(0.5); c.line(0, h - 16 * mm, w, h - 16 * mm)
    c.line(16 * mm, 12 * mm, w - 16 * mm, 12 * mm)
    c.setFont(MONO, 5.8); c.setFillColor(MUTED)
    c.drawString(16 * mm, 8 * mm, "VITALS · EDUCATIONAL ANALYSIS, NOT INVESTMENT ADVICE", charSpace=0.3)
    c.drawRightString(w - 16 * mm, 8 * mm, f"{doc.page:02d}")
    c.restoreState()


_BUILD_LOCK = __import__("threading").Lock()


def build_pdf(res: dict, theme: str = "dark") -> bytes:
    """theme: 'dark' (matches the app and emergentsignals.ai) or 'print' (white paper, navy ink)."""
    with _BUILD_LOCK:                    # the palette is module state: one build at a time
        _apply_theme(theme)
        try:
            return _build_pdf(res)
        finally:
            _apply_theme("dark")


def _build_pdf(res: dict) -> bytes:
    buf = io.BytesIO()
    doc = SimpleDocTemplate(buf, pagesize=A4, leftMargin=16 * mm, rightMargin=16 * mm,
                            topMargin=24 * mm, bottomMargin=18 * mm, title="Vitals — Portfolio Verdict",
                            author="Vitals")
    n_head = [0]

    def _head(title):
        n_head[0] += 1
        return _Head(n_head[0], title)

    def _sub(title):
        return Paragraph(_txt(str(title).upper()), S_SUB)

    E = []
    meta = f"Generated {res.get('generated_at')}"
    ctx = res.get("context") or {}
    E.append(Paragraph(_txt(meta).upper(), S_TAG))
    E.append(Spacer(1, 6))
    E.append(Paragraph("Vitals", S_TITLE))
    E.append(Spacer(1, 2))
    E.append(Paragraph("<i>Five analysts. One verdict.</i>", _sty("tagl", fontName=SERIF, fontSize=14, leading=18, textColor=TEXT2)))
    if ctx:
        E.append(Spacer(1, 4))
        E.append(Paragraph(_txt("Context: " + ", ".join(f"{k} {v}" for k, v in ctx.items())), S_DIM))
    E.append(Spacer(1, 12))

    hb = res.get("health_breakdown") or {}
    left = [_HealthBlock(res.get("health_score"), hb.get("pillars") or [], 58 * mm)]
    if hb.get("tolerance_penalty"):
        left += [Spacer(1, 4), Paragraph(_txt(f"−{abs(hb['tolerance_penalty']):.0f} for breaching the stated loss tolerance"), S_DIM)]
    verdict = Table([[Paragraph(_txt(res.get("verdict", "")), S_LEAD)], [Paragraph("VITALS VERDICT", S_LABEL)]],
                    colWidths=[100 * mm], hAlign="LEFT")
    verdict.setStyle(TableStyle([("LINEBEFORE", (0, 0), (0, -1), 0.6, RULE_STRONG),
                                 ("LEFTPADDING", (0, 0), (-1, -1), 11), ("RIGHTPADDING", (0, 0), (-1, -1), 0),
                                 ("TOPPADDING", (0, 0), (-1, -1), 1), ("BOTTOMPADDING", (0, 0), (-1, -1), 4)]))
    ac = res.get("action_counts") or {}
    acol = {"Buy More": GOOD, "Keep": TEXT2, "Trim": WARN, "Sell": BAD}
    strip = "&nbsp;&nbsp;&nbsp;".join(f"{_dot(acol[a])} {_mono(f'{ac[a]} {a}', TEXT, 6.8)}"
                                      for a in ("Buy More", "Keep", "Trim", "Sell") if ac.get(a))
    if res.get("total_pl_pct") is not None:
        strip += "&nbsp;&nbsp;&nbsp;" + _mono(f"Portfolio P/L {_pct(res['total_pl_pct'])}", TEXT, 6.8)
    right = [verdict, Spacer(1, 10), Paragraph(strip, _sty("strip", leading=12))]
    ol0 = (res.get("plan") or {}).get("outlook") or {}
    cur0, pl0 = ol0.get("current") or {}, ol0.get("planned") or {}
    if cur0 and pl0:   # the payoff line belongs on page 1, not buried mid-report
        right += [Spacer(1, 8), Paragraph(
            f"<b>If you follow the plan:</b> health {cur0.get('est_health')} → "
            f"<b>{pl0.get('est_health')}</b>"
            + (f", model 12-month edge {_pct(cur0.get('expected_excess_12m'))} → "
               f"<b>{_pct(pl0.get('expected_excess_12m'))}</b>"
               if cur0.get("expected_excess_12m") is not None
               and pl0.get("expected_excess_12m") is not None else "")
            + (f", beta {cur0.get('beta')} → <b>{pl0.get('beta')}</b>" if pl0.get("beta") else "")
            + (f", effective positions {cur0.get('effective_n')} → <b>{pl0.get('effective_n')}</b>"
               if pl0.get("effective_n") else ""),
            S_BODY)]
    hero = Table([[left, right]], colWidths=[66 * mm, 112 * mm], hAlign="LEFT")
    hero.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP"), ("LEFTPADDING", (0, 0), (-1, -1), 0),
                              ("RIGHTPADDING", (0, 0), (-1, -1), 0), ("TOPPADDING", (0, 0), (-1, -1), 0)]))
    E.append(hero)

    E.append(_head("Key findings"))
    hl_rows = []
    for h in res.get("highlights", []):
        c = _SEV_COLOR.get(str(h.get("severity")), MUTED)
        hl_rows.append([Paragraph(
            f'{_dot(c)}&nbsp;&nbsp;<b>{_txt(h.get("title"))}</b><br/>{_txt(h.get("detail"))}<br/>'
            + _mono(f'{h.get("lens", "portfolio")} lens', MUTED, 6.2), S_BODY)])
    if hl_rows:
        th = Table(hl_rows, colWidths=[178 * mm], hAlign="LEFT")
        th.setStyle(TableStyle([("LINEBELOW", (0, 0), (-1, -2), 0.45, RULE), ("LEFTPADDING", (0, 0), (-1, -1), 0),
                                ("TOPPADDING", (0, 0), (-1, -1), 5), ("BOTTOMPADDING", (0, 0), (-1, -1), 7)]))
        E.append(th)

    E.append(_head("Recommendations"))
    rows: list[list] = [["Holding", "Weight", "P/L", "vs intrinsic", "Action", "Why"]]
    for r in res.get("holdings", []):
        c = _ACTION_COLOR.get(r.get("action"), DIM)
        rows.append([
            Paragraph(f"<b>{_txt(r['ticker'])}</b><br/><font size='6.6' color='{_hex(MUTED)}'>{_txt(r.get('name'))}</font>", S_CELL),
            _pct(r.get("weight"), signed=False), _pct(r.get("pl_pct")), _pct(r.get("upside")),
            Paragraph(_mono(r.get("action"), c, 6.4) + ("<br/>" + _mono("watch", WARN, 5.8) if r.get("watch") else ""), S_CELL),
            Paragraph(_txt(r.get("rationale")), S_CELL)])
    E.append(_table(rows, [26 * mm, 14 * mm, 18 * mm, 18 * mm, 16 * mm, 84 * mm],
                    aligns=["LEFT", "RIGHT", "RIGHT", "RIGHT", "LEFT", "LEFT"]))

    E.append(_head("Portfolio review"))
    st = res.get("strategist") or {}
    if st.get("strategy_read"):
        E.append(Paragraph(f"<b>Strategy read:</b> {_txt(st['strategy_read'])}", S_BODY))
    if st.get("style_tilt"):
        E.append(Paragraph(f"<b>Style tilt:</b> {_txt(st['style_tilt'])}", S_BODY))
    if st.get("gaps"):
        E.append(Paragraph("<b>Missing exposures:</b> " + _txt(", ".join(map(str, st["gaps"]))), S_BODY))
    E.append(Spacer(1, 5))
    for c0 in res.get("risk_scorecard", []):
        c = _SEV_COLOR.get(str(c0.get("status")), DIM)
        E.append(Paragraph(
            _mono(c0.get("status"), c, 6.4) + f"&nbsp;&nbsp;<b>{_txt(c0.get('check'))}</b> · {_txt(c0.get('detail'))}", S_BODY))
        E.append(Spacer(1, 2))
    sa = res.get("sector_allocation") or {}
    if sa:
        E.append(Spacer(1, 4))
        E.append(Paragraph("<b>Sector mix:</b> " + _txt(" · ".join(
            f"{s} {w * 100:.0f}%" for s, w in sa.items())), S_BODY))

    rk = res.get("risk") or {}
    if rk:
        bn = (res.get("benchmark") or {}).get("name") or "benchmark"
        E.append(_head("Risk analytics"))
        if rk.get("stress"):
            rows_s: list[list] = [["Stress replay (today's weights)", "Window", "Portfolio", bn]]
            for s in rk["stress"]:
                rows_s.append([_txt(s["name"]), _txt(str(s["window"]).replace("→", "to").replace("->", "to")), _pct(s["portfolio"]),
                               _pct(s["benchmark"]) if s.get("benchmark") is not None else "—"])
            E.append(_table(rows_s, [55 * mm, 55 * mm, 25 * mm, 25 * mm],
                            aligns=["LEFT", "LEFT", "RIGHT", "RIGHT"]))
            E.append(Spacer(1, 4))
        bits = []
        if rk.get("var_1d_95") is not None:
            bits.append(f"<b>VaR (95%):</b> 1-day {rk['var_1d_95'] * 100:.1f}%, 1-month {rk['var_1m_95'] * 100:.1f}%"
                        + (f", expected shortfall {rk['cvar_1d_95'] * 100:.1f}%" if rk.get("cvar_1d_95") else ""))
        if rk.get("tracking_error"):
            bits.append(f"<b>Tracking error vs {_txt(bn)}:</b> {rk['tracking_error'] * 100:.1f}%")
        if rk.get("currency_exposure"):
            bits.append("<b>Currency:</b> " + _txt(", ".join(f"{c} {w * 100:.0f}%" for c, w in rk["currency_exposure"].items())))
        lt = rk.get("lookthrough") or {}
        if lt.get("top_names"):
            bits.append("<b>Fund look-through (top effective names):</b> " + _txt(", ".join(
                f"{n} {tot * 100:.1f}%" for n, _, _, tot in lt["top_names"][:6])))
        ft = rk.get("factor_tilts") or {}
        if ft.get("tilts"):
            bits.append("<b>Style tilts:</b> " + _txt(", ".join(f"{k} {v:+.2f}" for k, v in ft["tilts"].items())))
        fb = rk.get("factor_betas") or {}
        if fb.get("betas"):
            bits.append(f"<b>Measured factor betas (factor-model market beta {fb['market_beta']}):</b> "
                        + _txt(", ".join(f"{k} {v:+.2f}" for k, v in fb["betas"].items())))
        br = rk.get("benchmark_relative") or {}
        if br:
            bits.append(f"<b>Vs {_txt(bn)}:</b> " + _txt(br_text(br)))
        if rk.get("active_sectors"):
            bits.append("<b>Active sector bets:</b> " + _txt(", ".join(
                f"{x['sector']} {x['active'] * 100:+.0f}pp" for x in rk["active_sectors"][:6])))
        if rk.get("liquidity"):
            bits.append("<b>Liquidity:</b> " + _txt("; ".join(
                f"{x['ticker']} ~{x['days_to_liquidate']} days to exit" for x in rk["liquidity"][:4])))
        for b in bits:
            E.append(Paragraph(b, S_BODY))
            E.append(Spacer(1, 2))

    alts = res.get("alternatives") or []
    if alts:
        E.append(_head("Worth a look · gap fillers"))
        needs = res.get("portfolio_needs") or {}
        if needs:
            E.append(Paragraph("<b>What this portfolio needs:</b> " + _txt(
                "; ".join(v["label"] for v in needs.values() if v.get("label"))), S_BODY))
            E.append(Spacer(1, 3))
        for g in (res.get("plan") or {}).get("gap_search") or []:
            line = (f"<b>{_txt(g['sector'])}:</b> {g['screened']} name{'' if g['screened'] == 1 else 's'} screened — "
                    + (f"buyable today: {_txt(', '.join(g['buyable']))}" if g.get("buyable") else "none buyable today")
                    + (f"; {'the rest' if g.get('buyable') else 'all'} passed over — {_txt(g['why_not'])}" if g.get("why_not") else "")
                    + (f"; on the bench with entry conditions: {_txt(', '.join(g['bench']))}" if g.get("bench") else ""))
            E.append(Paragraph(line, S_DIM)); E.append(Spacer(1, 2))
        for a in alts:
            fit = a.get("fit") or {}
            com = a.get("committee") or {}
            sig = " · ".join((fit.get("fixes") or []) + [f"CAUTION: {x}" for x in (fit.get("cautions") or [])]
                             + ([f"committee {com['conviction']}/100 on adding"] if com.get("conviction") else [])
                             + (a.get("signals") or []))
            E.append(Paragraph(
                f"<b>{_txt(a.get('ticker'))}</b> — {_txt(a.get('reason'))}"
                + ("<br/>" + _mono(sig, MUTED, 5.9) if sig else ""),
                S_BODY))
            E.append(Spacer(1, 3))

    plan = res.get("plan") or {}
    if plan:
        E.append(_head("Revival plan" if plan.get("mode") == "revival" else "Enhancement plan"))
        E.append(Paragraph(_txt(plan.get("pitch"), serif=True), S_VERDICT))
        E.append(Spacer(1, 8))
        mv = [[Paragraph(_mono(f"{i:02d}"), S_CELL),
               Paragraph(f"<b>{_txt(m.get('title'))}</b><br/>{_txt(m.get('detail'))}", S_BODY)]
              for i, m in enumerate(plan.get("moves") or [], 1)]
        if mv:
            tm = Table(mv, colWidths=[12 * mm, 166 * mm], hAlign="LEFT")
            tm.setStyle(TableStyle([("VALIGN", (0, 0), (-1, -1), "TOP"), ("LINEABOVE", (0, 0), (-1, -1), 0.45, RULE),
                                    ("LINEBELOW", (0, -1), (-1, -1), 0.45, RULE),
                                    ("LEFTPADDING", (0, 0), (-1, -1), 0), ("TOPPADDING", (0, 0), (-1, -1), 6),
                                    ("BOTTOMPADDING", (0, 0), (-1, -1), 7)]))
            E.append(tm)
        orders = plan.get("orders") or []
        if orders:
            E.append(Spacer(1, 5))
            rows2: list[list] = [["", "Holding", "Size", "Approx."]]
            for o in orders:
                amt = (f"${o['amount_usd']:,.0f}" + (f" · ~{o['shares']} sh" if o.get("shares") else "")
                       ) if o.get("amount_usd") else "-"
                if o.get("cost_note"):
                    amt += f" (+{o['cost_note']})"
                rows2.append([Paragraph(_mono(o["side"], GOOD if o["side"] == "BUY" else BAD, 6.4), S_CELL),
                              o["ticker"] + (" (new)" if o.get("is_new") else ""),
                              f"{abs(o['delta_pct']) * 100:.1f}% of book", amt])
            E.append(_table(rows2, [18 * mm, 42 * mm, 40 * mm, 45 * mm],
                            aligns=["LEFT", "LEFT", "RIGHT", "RIGHT"]))
        if plan.get("cash"):
            E.append(Spacer(1, 3))
            E.append(Paragraph(f"<b>Unallocated cash:</b> {plan['cash'] * 100:.1f}% of the book kept as dry powder for the "
                               f"watchlist — the committee's ideas could not absorb every sale at sensible sizes.", S_BODY))
        if plan.get("do_nothing"):
            E.append(Spacer(1, 4))
            E.append(Paragraph("<b>Do nothing.</b> Nothing clears the hurdle for a trade; inactivity is the recommendation until a sell trigger fires.", S_BODY))
        desk = []
        if plan.get("tax_summary"):
            desk.append(f"<b>Tax, net:</b> {_txt(plan['tax_summary'])}")
        for x in plan.get("tax_plan") or []:
            desk.append(f"<b>Tax plan {_txt(x['ticker'])}:</b> {_txt(x['note'])}")
        ra, rb = plan.get("risk_contributions_after") or {}, plan.get("risk_contributions") or {}
        if ra.get("top"):
            desk.append("<b>Where the risk sits after the trade:</b> " + _txt(", ".join(f"{t} {p * 100:.0f}%" for t, p in ra["top"][:5]))
                        + (" <font size='7'>(today: " + _txt(", ".join(f"{t} {p * 100:.0f}%" for t, p in rb["top"][:5])) + ")</font>" if rb.get("top") else ""))
        s12 = plan.get("scenarios_12m") or {}
        if (s12.get("current") or {}).get("base") is not None:
            c, pl = s12["current"], s12.get("planned") or {}
            desk.append(f"<b>Valuation risk/reward</b> (where the book would trade if every holding converged to its bear / base / bull value, probability-weighted, {c['coverage'] * 100:.0f}% of the book): "
                        f"today bear {c['bear'] * 100:+.0f}% / base {c['base'] * 100:+.0f}% / bull {c['bull'] * 100:+.0f}%"
                        + (f"; after the plan bear {pl['bear'] * 100:+.0f}% / base {pl['base'] * 100:+.0f}% / bull {pl['bull'] * 100:+.0f}%" if pl.get("base") is not None else ""))
        if desk:
            E.append(Spacer(1, 5))
            E.append(_sub("Execution · the manager's desk"))
            for b in desk:
                E.append(Paragraph(b, S_BODY)); E.append(Spacer(1, 2))
        wl = plan.get("watchlist") or []
        if wl:
            E.append(Spacer(1, 4))
            E.append(_sub("Watchlist · the bench, with entry conditions"))
            rows_w: list[list] = [["Ticker", "Entry condition", "Why it is on the bench"]]
            for x in wl:
                rows_w.append([_txt(x["ticker"]), Paragraph(_txt(x["condition"]), S_CELL), Paragraph(_txt(x.get("why")), S_CELL)])
            E.append(_table(rows_w, [22 * mm, 75 * mm, 75 * mm]))
        cats = plan.get("catalysts") or []
        if cats:
            E.append(Spacer(1, 4))
            E.append(Paragraph("<b>Catalysts — next 90 days:</b> " + _txt(", ".join(
                f"{x['ticker']} {x['event']} {x['date']}" for x in cats)), S_BODY))
        trip = [(r["ticker"], (r.get("us") or {}).get("sell_triggers")) for r in res.get("holdings", [])
                if r.get("action") != "Sell" and (r.get("us") or {}).get("sell_triggers")]
        if trip:
            E.append(Spacer(1, 4))
            E.append(_sub("Tripwires · what would make us sell"))
            rows_t: list[list] = [["Holding", "Tripwire"]]
            for t, tr in trip[:14]:
                rows_t.append([_txt(t), Paragraph(_txt(tr[0]), S_CELL)])
            E.append(_table(rows_t, [22 * mm, 150 * mm]))
        for hp in plan.get("harvest_pairs") or []:
            E.append(Spacer(1, 3))
            E.append(Paragraph(f"<b>Tax-loss harvest:</b> sell {_txt(hp['sell'])}, buy {_txt(hp['buy'])} ({_txt(hp['buy_name'])}, correlation {hp['correlation']}) - {_txt(hp['note'])}", S_BODY))
        pmx = res.get("premortem")
        if pmx and pmx.get("story"):
            E.append(Spacer(1, 4))
            pmt = Table([[Paragraph(_mono(f"Pre-mortem · {pmx['ticker']}", BAD, 6.4) + "<br/>" + _txt(pmx["story"]), S_BODY)]],
                        colWidths=[178 * mm], hAlign="LEFT")
            pmt.setStyle(TableStyle([("LINEBEFORE", (0, 0), (0, -1), 0.8, BAD), ("LEFTPADDING", (0, 0), (-1, -1), 10),
                                     ("TOPPADDING", (0, 0), (-1, -1), 2), ("BOTTOMPADDING", (0, 0), (-1, -1), 2)]))
            E.append(pmt)
        tri = plan.get("triage") or []
        if tri:
            E.append(Spacer(1, 6))
            E.append(_sub("Losing-position triage"))
            E.append(Spacer(1, 2))
            rows3: list[list] = [["Holding", "Call", "Why"]]
            for t in tri:
                rows3.append([_txt(t.get("ticker")), Paragraph(_txt(t.get("disposition")), S_CELL),
                              Paragraph(_txt(t.get("note")), S_CELL)])
            E.append(_table(rows3, [22 * mm, 34 * mm, 116 * mm]))

    target = res.get("target_portfolio") or []
    if target:
        E.append(_head("Recommended target portfolio"))
        E.append(Paragraph("Committee conviction sizes positions under risk-profile caps. "
                           "Educational illustration, not advice.", S_DIM))
        E.append(Spacer(1, 4))
        rows = [["Holding", "Sector", "Current", "Target", "Change"]]
        for r in target:
            name = r["ticker"] + ("  (new)" if r.get("is_new") else "")
            rows.append([_txt(name), _txt(r.get("sector")), _pct(r["current_w"], signed=False),
                         _pct(r["target_w"], signed=False), f"{r['delta'] * 100:+.1f}pp"])
        E.append(_table(rows, [38 * mm, 55 * mm, 22 * mm, 22 * mm, 22 * mm],
                        aligns=["LEFT", "LEFT", "RIGHT", "RIGHT", "RIGHT"]))

    if res.get("llm_used"):
        # one line per holding — the old prose dump ran ~7 pages on a 47-name book and
        # nobody reads it; the full reasoning stays on screen in the expandable rows
        E.append(_head("Appendix · committee scores at a glance"))
        E.append(Paragraph("Conviction 0-100 per lens (50 = neutral). Full reasoning and the "
                           "headlines weighed are in the app under each holding's row.", S_DIM))
        E.append(Spacer(1, 4))
        lens_order = ("value", "growth", "macro", "technical", "risk")
        rows4: list[list] = [["Holding", "Action", "Val", "Gro", "Mac", "Tec", "Rsk",
                              "vs intr.", "Committee's top concern"]]
        for r in res.get("holdings", []):
            scores = r.get("lens_scores") or {}
            cells = [f"{scores[k]:.0f}" if k in scores else "-" for k in lens_order]
            concern = (r.get("risks") or [""])[0]
            c = _ACTION_COLOR.get(r.get("action"), DIM)
            rows4.append([
                _txt(r["ticker"]),
                Paragraph(_mono(r.get("action"), c, 6.2), S_CELL),
                *cells, _pct(r.get("upside")),
                Paragraph(_txt(concern)[:140], S_CELL)])
        E.append(_table(rows4, [18 * mm, 17 * mm, 9 * mm, 9 * mm, 9 * mm, 9 * mm, 9 * mm,
                                15 * mm, 77 * mm],
                        aligns=["LEFT", "LEFT", "RIGHT", "RIGHT", "RIGHT", "RIGHT", "RIGHT",
                                "RIGHT", "LEFT"]))

    ds = res.get("data_sources") or []
    if ds:
        diag = res.get("diagnostics") or {}
        E.append(_head("Data sources and methodology"))
        E.append(Paragraph(_txt(
            f"Benchmark {(res.get('benchmark') or {}).get('name', 'S&P 500')} · base currency "
            f"{res.get('base_currency', 'USD')} · methodology {res.get('methodology_version', '?')} · "
            f"prompt {diag.get('prompt_version', '?')} · models "
            + ", ".join(f"{k} {v}" for k, v in (diag.get("models") or {}).items() if v)), S_DIM))
        E.append(Spacer(1, 3))
        rows_d: list[list] = [["Holding", "Fundamentals", "As of", "Price as of"]]
        for d in ds:
            rows_d.append([_txt(d["ticker"]), Paragraph(_txt(d.get("fundamentals") or "?"), S_CELL),
                           _txt(d.get("fund_asof") or "—"), _txt(d.get("price_asof") or "—")])
        E.append(_table(rows_d, [24 * mm, 66 * mm, 30 * mm, 42 * mm],
                        aligns=["LEFT", "LEFT", "LEFT", "LEFT"]))

    E.append(Spacer(1, 14))
    disc = Table([[Paragraph(_txt(res.get("disclaimer", "")), _sty("disc", fontSize=7.4, leading=10.8, textColor=TEXT2))]],
                 colWidths=[178 * mm], hAlign="LEFT")
    disc.setStyle(TableStyle([("BOX", (0, 0), (-1, -1), 0.6, RULE_STRONG, None, (2, 2)),
                              ("LEFTPADDING", (0, 0), (-1, -1), 9), ("RIGHTPADDING", (0, 0), (-1, -1), 9),
                              ("TOPPADDING", (0, 0), (-1, -1), 7), ("BOTTOMPADDING", (0, 0), (-1, -1), 8)]))
    E.append(disc)
    doc.build(E, onFirstPage=_page, onLaterPages=_page)
    return buf.getvalue()