zcode-app-cli 3.3.5-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +642 -0
  3. package/bin/zcode.js +848 -0
  4. package/config.example.json +110 -0
  5. package/package.json +81 -0
  6. package/vendor/.node-bundle-meta.json +6 -0
  7. package/vendor/extraction.json +11 -0
  8. package/vendor/node_modules/@zcode/tui/dist/index.js +161875 -0
  9. package/vendor/node_modules/@zcode/tui/package.json +14 -0
  10. package/vendor/packages/android-emulator-plugin/.mcp.json +19 -0
  11. package/vendor/packages/android-emulator-plugin/.zcode-plugin/plugin.json +63 -0
  12. package/vendor/packages/android-emulator-plugin/README.md +134 -0
  13. package/vendor/packages/android-emulator-plugin/commands/android-dev.md +11 -0
  14. package/vendor/packages/android-emulator-plugin/dist/lib/path.d.ts +4 -0
  15. package/vendor/packages/android-emulator-plugin/dist/lib/path.js +17 -0
  16. package/vendor/packages/android-emulator-plugin/dist/lib/result.d.ts +5 -0
  17. package/vendor/packages/android-emulator-plugin/dist/lib/result.js +22 -0
  18. package/vendor/packages/android-emulator-plugin/dist/lib/run.d.ts +18 -0
  19. package/vendor/packages/android-emulator-plugin/dist/lib/run.js +99 -0
  20. package/vendor/packages/android-emulator-plugin/dist/mcp/server.d.ts +3 -0
  21. package/vendor/packages/android-emulator-plugin/dist/mcp/server.js +47607 -0
  22. package/vendor/packages/android-emulator-plugin/dist/providers/app.d.ts +39 -0
  23. package/vendor/packages/android-emulator-plugin/dist/providers/app.js +50 -0
  24. package/vendor/packages/android-emulator-plugin/dist/providers/avd.d.ts +37 -0
  25. package/vendor/packages/android-emulator-plugin/dist/providers/avd.js +185 -0
  26. package/vendor/packages/android-emulator-plugin/dist/providers/build.d.ts +68 -0
  27. package/vendor/packages/android-emulator-plugin/dist/providers/build.js +131 -0
  28. package/vendor/packages/android-emulator-plugin/dist/providers/config.d.ts +7 -0
  29. package/vendor/packages/android-emulator-plugin/dist/providers/config.js +29 -0
  30. package/vendor/packages/android-emulator-plugin/dist/providers/device.d.ts +20 -0
  31. package/vendor/packages/android-emulator-plugin/dist/providers/device.js +91 -0
  32. package/vendor/packages/android-emulator-plugin/dist/providers/logs.d.ts +15 -0
  33. package/vendor/packages/android-emulator-plugin/dist/providers/logs.js +31 -0
  34. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.d.ts +15 -0
  35. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.js +123 -0
  36. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.d.ts +13 -0
  37. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.js +211 -0
  38. package/vendor/packages/android-emulator-plugin/dist/providers/project.d.ts +33 -0
  39. package/vendor/packages/android-emulator-plugin/dist/providers/project.js +195 -0
  40. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.d.ts +14 -0
  41. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.js +73 -0
  42. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.d.ts +14 -0
  43. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.js +185 -0
  44. package/vendor/packages/android-emulator-plugin/dist/providers/ui.d.ts +92 -0
  45. package/vendor/packages/android-emulator-plugin/dist/providers/ui.js +146 -0
  46. package/vendor/packages/android-emulator-plugin/hooks/hooks.json +3 -0
  47. package/vendor/packages/android-emulator-plugin/package.json +35 -0
  48. package/vendor/packages/android-emulator-plugin/skills/android-dev/INSTALL_ENVIRONMENT.md +357 -0
  49. package/vendor/packages/android-emulator-plugin/skills/android-dev/SKILL.md +73 -0
  50. package/vendor/packages/android-emulator-plugin/templates/compose-app/README.md +5 -0
  51. package/vendor/packages/document-skills-plugin/.zcode-plugin/plugin.json +8 -0
  52. package/vendor/packages/document-skills-plugin/package.json +8 -0
  53. package/vendor/packages/document-skills-plugin/skills/docx/LICENSE.txt +13 -0
  54. package/vendor/packages/document-skills-plugin/skills/docx/SKILL.md +201 -0
  55. package/vendor/packages/document-skills-plugin/skills/docx/references/chart-templates.md +386 -0
  56. package/vendor/packages/document-skills-plugin/skills/docx/references/common-rules.md +419 -0
  57. package/vendor/packages/document-skills-plugin/skills/docx/references/decorations.md +537 -0
  58. package/vendor/packages/document-skills-plugin/skills/docx/references/design-system.md +1797 -0
  59. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-advanced.md +257 -0
  60. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-core.md +332 -0
  61. package/vendor/packages/document-skills-plugin/skills/docx/references/faq.md +323 -0
  62. package/vendor/packages/document-skills-plugin/skills/docx/references/math-formulas.md +276 -0
  63. package/vendor/packages/document-skills-plugin/skills/docx/references/ooxml.md +222 -0
  64. package/vendor/packages/document-skills-plugin/skills/docx/references/toc.md +264 -0
  65. package/vendor/packages/document-skills-plugin/skills/docx/routes/comment.md +88 -0
  66. package/vendor/packages/document-skills-plugin/skills/docx/routes/create.md +207 -0
  67. package/vendor/packages/document-skills-plugin/skills/docx/routes/edit.md +115 -0
  68. package/vendor/packages/document-skills-plugin/skills/docx/routes/format.md +120 -0
  69. package/vendor/packages/document-skills-plugin/skills/docx/routes/read.md +114 -0
  70. package/vendor/packages/document-skills-plugin/skills/docx/scenes/academic.md +783 -0
  71. package/vendor/packages/document-skills-plugin/skills/docx/scenes/contract.md +463 -0
  72. package/vendor/packages/document-skills-plugin/skills/docx/scenes/copywriting.md +139 -0
  73. package/vendor/packages/document-skills-plugin/skills/docx/scenes/exam.md +698 -0
  74. package/vendor/packages/document-skills-plugin/skills/docx/scenes/official-doc.md +411 -0
  75. package/vendor/packages/document-skills-plugin/skills/docx/scenes/report.md +340 -0
  76. package/vendor/packages/document-skills-plugin/skills/docx/scenes/resume.md +534 -0
  77. package/vendor/packages/document-skills-plugin/skills/docx/scripts/__init__.py +1 -0
  78. package/vendor/packages/document-skills-plugin/skills/docx/scripts/add_toc_placeholders.py +749 -0
  79. package/vendor/packages/document-skills-plugin/skills/docx/scripts/document.py +1333 -0
  80. package/vendor/packages/document-skills-plugin/skills/docx/scripts/postcheck.py +807 -0
  81. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/comments.xml +3 -0
  82. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtended.xml +3 -0
  83. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtensible.xml +3 -0
  84. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsIds.xml +3 -0
  85. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/people.xml +3 -0
  86. package/vendor/packages/document-skills-plugin/skills/docx/scripts/utilities.py +374 -0
  87. package/vendor/packages/document-skills-plugin/skills/docx/setup.sh +177 -0
  88. package/vendor/packages/document-skills-plugin/skills/pdf/LICENSE.txt +13 -0
  89. package/vendor/packages/document-skills-plugin/skills/pdf/SKILL.md +919 -0
  90. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/academic.md +1058 -0
  91. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/creative.md +770 -0
  92. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/poster.md +702 -0
  93. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process-advanced.md +284 -0
  94. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process.md +319 -0
  95. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/report.md +1659 -0
  96. package/vendor/packages/document-skills-plugin/skills/pdf/configs/components.md +153 -0
  97. package/vendor/packages/document-skills-plugin/skills/pdf/configs/fonts.md +93 -0
  98. package/vendor/packages/document-skills-plugin/skills/pdf/configs/visual_framework.md +263 -0
  99. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-academic.tex +130 -0
  100. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-altacv.tex +190 -0
  101. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/cover_validate.js +367 -0
  102. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/design_engine.py +2816 -0
  103. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2pdf-next.js +754 -0
  104. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2poster.js +256 -0
  105. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf.py +2959 -0
  106. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf_qa.py +901 -0
  107. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/poster_validate.py +1337 -0
  108. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/setup.sh +269 -0
  109. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/toc_validate.py +2075 -0
  110. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/charts.md +320 -0
  111. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover-backgrounds.md +384 -0
  112. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover.md +1442 -0
  113. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/fill-engine.md +527 -0
  114. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/geometry.md +142 -0
  115. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/overflow.md +630 -0
  116. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/pagination.md +367 -0
  117. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/palette.md +217 -0
  118. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/typography.md +20 -0
  119. package/vendor/packages/ios-simulator-plugin/.mcp.json +15 -0
  120. package/vendor/packages/ios-simulator-plugin/.zcode-plugin/plugin.json +34 -0
  121. package/vendor/packages/ios-simulator-plugin/README.md +111 -0
  122. package/vendor/packages/ios-simulator-plugin/commands/ios-dev.md +11 -0
  123. package/vendor/packages/ios-simulator-plugin/dist/lib/path.d.ts +4 -0
  124. package/vendor/packages/ios-simulator-plugin/dist/lib/path.js +18 -0
  125. package/vendor/packages/ios-simulator-plugin/dist/lib/result.d.ts +5 -0
  126. package/vendor/packages/ios-simulator-plugin/dist/lib/result.js +20 -0
  127. package/vendor/packages/ios-simulator-plugin/dist/lib/run.d.ts +17 -0
  128. package/vendor/packages/ios-simulator-plugin/dist/lib/run.js +83 -0
  129. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.d.ts +3 -0
  130. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.js +46833 -0
  131. package/vendor/packages/ios-simulator-plugin/dist/providers/build.d.ts +112 -0
  132. package/vendor/packages/ios-simulator-plugin/dist/providers/build.js +99 -0
  133. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.d.ts +21 -0
  134. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.js +26 -0
  135. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.d.ts +12 -0
  136. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.js +62 -0
  137. package/vendor/packages/ios-simulator-plugin/dist/providers/project.d.ts +35 -0
  138. package/vendor/packages/ios-simulator-plugin/dist/providers/project.js +288 -0
  139. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.d.ts +22 -0
  140. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.js +30 -0
  141. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.d.ts +60 -0
  142. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.js +116 -0
  143. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.d.ts +57 -0
  144. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.js +67 -0
  145. package/vendor/packages/ios-simulator-plugin/hooks/hooks.json +3 -0
  146. package/vendor/packages/ios-simulator-plugin/package.json +35 -0
  147. package/vendor/packages/ios-simulator-plugin/skills/ios-dev/SKILL.md +45 -0
  148. package/vendor/packages/ios-simulator-plugin/templates/swiftui-app/README.md +5 -0
  149. package/vendor/packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json +9 -0
  150. package/vendor/packages/restore-legacy-sessions-plugin/README.md +35 -0
  151. package/vendor/packages/restore-legacy-sessions-plugin/commands/restore-legacy-sessions.md +11 -0
  152. package/vendor/packages/restore-legacy-sessions-plugin/package.json +8 -0
  153. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md +92 -0
  154. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/restore-conversation.mjs +648 -0
  155. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/scan-legacy-sessions.mjs +422 -0
  156. package/vendor/packages/skill-creator-plugin/.zcode-plugin/plugin.json +8 -0
  157. package/vendor/packages/skill-creator-plugin/package.json +8 -0
  158. package/vendor/packages/skill-creator-plugin/skills/skill-creator/SKILL.md +159 -0
  159. package/vendor/packages/zcode-guide-plugin/.zcode-plugin/plugin.json +8 -0
  160. package/vendor/packages/zcode-guide-plugin/README.md +22 -0
  161. package/vendor/packages/zcode-guide-plugin/package.json +8 -0
  162. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-commands/SKILL.md +66 -0
  163. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-hooks/SKILL.md +66 -0
  164. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-mcp/SKILL.md +97 -0
  165. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-plugins/SKILL.md +59 -0
  166. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-skills/SKILL.md +61 -0
  167. package/vendor/packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md +99 -0
  168. package/vendor/zcode.cjs +2926 -0
  169. package/zcode-runtime.lock.json +8 -0
@@ -0,0 +1,2816 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ design_engine.py — Aesthetic computation engine for art-direction-first PDF production.
4
+
5
+ Philosophy: The LLM handles narrative and composition; this script handles the math
6
+ that models get wrong — precise color harmony, algorithmic SVG, and spatial tension.
7
+
8
+ Three core functions:
9
+ 1. generate_color_palette(intent) — HSL-locked low-saturation palettes
10
+ 2. generate_generative_svg(svg_type) — Algorithmic art backgrounds
11
+ 3. calculate_layout(elements) — Deliberate offset/overlap coordinates
12
+
13
+ Usage:
14
+ python3 design_engine.py palette --intent calm --mode dark
15
+ python3 design_engine.py palette --intent tension --mode light
16
+ python3 design_engine.py svg --intent flow --dimensions 720x960
17
+ python3 design_engine.py svg --intent grid --dimensions 720x960
18
+ python3 design_engine.py layout --elements hero,body,meta --dimensions 720x960 --style offset
19
+ python3 design_engine.py full --intent energy --mode dark --dimensions 720x960 --output-dir ./assets/
20
+ """
21
+
22
+ import argparse
23
+ import colorsys
24
+ import json
25
+ import math
26
+ import os
27
+ import random
28
+ import sys
29
+
30
+ # ═══════════════════════════════════════════════════════════════════════
31
+ # 1. COLOR PALETTE — HSL with Saturation Clamped to [0.05, 0.25]
32
+ # ═══════════════════════════════════════════════════════════════════════
33
+ #
34
+ # Core constraint: Saturation MUST be between 0.05 and 0.25.
35
+ # This eliminates candy-colored, web-app-looking outputs and locks
36
+ # everything into the "high-end grey" (高级灰) tonal range.
37
+ #
38
+ # Two modes:
39
+ # - Dark: background L < 0.10, text L > 0.85
40
+ # - Light: background L > 0.95, text L < 0.15
41
+ # The "muddy middle" (L between 0.30 and 0.70) is forbidden for backgrounds.
42
+
43
+ # Intent → base hue mapping (degrees on the HSL wheel)
44
+ # 5 intents: Calm, Tension, Energy, Authority, Warmth
45
+ # Plus utility intents (nature, cold, neutral) for keyword auto-derive
46
+ INTENT_HUES = {
47
+ "calm": 210, # Steel blue-grey, low saturation (merges old serenity+minimalism)
48
+ "tension": 0, # Warm near-black vs cold
49
+ "energy": 30, # Amber undertone
50
+ "authority": 280, # Muted violet, formal/premium (replaces old elegance)
51
+ "warmth": 20, # Terracotta undertone
52
+ # Utility intents (for keyword auto-derive, not exposed in UI)
53
+ "nature": 150, # Desaturated sage
54
+ "cold": 200, # Slate blue
55
+ "neutral": 45, # Warm grey
56
+ # Legacy aliases (backward compatibility)
57
+ "serenity": 210, # → calm
58
+ "elegance": 280, # → authority
59
+ "minimalism": 0, # → calm (achromatic variant)
60
+ }
61
+
62
+ # Theme keywords → intent mapping (for auto-derive from document description)
63
+ # When the user doesn't specify an intent, scan the document title/description
64
+ # for these keywords and map to the closest intent.
65
+ THEME_KEYWORDS = {
66
+ # Technology / Data / Analytics
67
+ "tech": "cold", "数据": "cold", "data": "cold", "AI": "cold",
68
+ "科技": "cold", "digital": "cold", "analytics": "cold", "分析": "cold",
69
+ # Nature / Environment / Sustainability
70
+ "green": "nature", "绿色": "nature", "环保": "nature", "eco": "nature",
71
+ "sustainability": "nature", "生态": "nature", "forest": "nature",
72
+ # Business / Finance / Corporate
73
+ "report": "neutral", "报告": "neutral", "finance": "neutral", "财务": "neutral",
74
+ "annual": "neutral", "年度": "neutral", "corporate": "neutral",
75
+ # Creative / Marketing / Social
76
+ "marketing": "energy", "运营": "energy", "social": "energy", "品牌": "energy",
77
+ "campaign": "energy", "活动": "energy", "launch": "energy",
78
+ # Authority / Formal / Premium / Luxury
79
+ "luxury": "authority", "奢华": "authority", "fashion": "authority", "时尚": "authority",
80
+ "premium": "authority", "高端": "authority", "gala": "authority",
81
+ "formal": "authority", "正式": "authority", "professional": "authority", "专业": "authority",
82
+ "government": "authority", "政府": "authority", "bidding": "authority", "投标": "authority",
83
+ "政府报告": "authority", "政府文书": "authority", "公文": "authority",
84
+ "thesis": "authority", "毕业论文": "authority", "dissertation": "authority",
85
+ "开题": "authority", "开题报告": "authority", "proposal": "authority", "学位": "authority",
86
+ # Calm / Meditation / Healthcare / Minimalist
87
+ "health": "calm", "健康": "calm", "meditation": "calm",
88
+ "wellness": "calm", "calm": "calm", "医疗": "calm",
89
+ "minimalist": "calm", "极简": "calm", "simple": "calm", "简约": "calm",
90
+ # Urgent / Warning / Emergency
91
+ "urgent": "tension", "warning": "tension", "紧急": "tension",
92
+ "alert": "tension", "crisis": "tension",
93
+ # Warm / Food / Lifestyle
94
+ "food": "warmth", "美食": "warmth", "lifestyle": "warmth",
95
+ "生活": "warmth", "home": "warmth", "家居": "warmth",
96
+ }
97
+
98
+
99
+ def derive_intent(text):
100
+ """
101
+ Auto-derive design intent from document title/description.
102
+ Scans for theme keywords and returns the best-matching intent.
103
+ Falls back to 'neutral' if no keywords match.
104
+
105
+ Usage:
106
+ python3 design_engine.py derive "Social Media Operations Monthly Report" → energy
107
+ python3 design_engine.py derive "2025 Annual Sustainability Report" → nature
108
+ """
109
+ text_lower = text.lower()
110
+ scores = {}
111
+ for keyword, intent in THEME_KEYWORDS.items():
112
+ if keyword.lower() in text_lower:
113
+ scores[intent] = scores.get(intent, 0) + 1
114
+ if not scores:
115
+ return "neutral"
116
+ # When tied, prefer specific intents over 'neutral' (which is a generic fallback)
117
+ max_score = max(scores.values())
118
+ top_intents = [k for k, v in scores.items() if v == max_score]
119
+ if len(top_intents) > 1 and "neutral" in top_intents:
120
+ top_intents.remove("neutral")
121
+ return top_intents[0]
122
+
123
+ # Intent → recommended harmony mapping (reduces LLM decision burden)
124
+ # Used as fallback when LLM doesn't specify color_harmony
125
+ INTENT_HARMONY_MAP = {
126
+ "calm": "analogous", # peaceful, flowing transition (merges serenity+minimalism)
127
+ "tension": "complementary", # maximum visual conflict
128
+ "energy": "triadic", # vibrant, multi-directional
129
+ "authority": "split_complementary", # sophisticated, formal (replaces elegance)
130
+ "warmth": "analogous", # natural, earthy cohesion
131
+ # Utility intents
132
+ "nature": "analogous", # organic harmony
133
+ "cold": "split_complementary", # icy precision with subtle warmth
134
+ "neutral": "split_complementary", # safe default, still interesting
135
+ # Legacy aliases
136
+ "serenity": "analogous",
137
+ "elegance": "split_complementary",
138
+ "minimalism": "monochrome",
139
+ }
140
+
141
+ def _hsl_to_hex(h, s, l):
142
+ """Convert HSL (h: 0-360, s: 0-1, l: 0-1) to hex string."""
143
+ r, g, b = colorsys.hls_to_rgb(h / 360.0, l, s)
144
+ return f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}"
145
+
146
+
147
+ # Muddy / ugly hue zones that produce unattractive accent colors at medium saturation.
148
+ # These hue ranges tend to look "dirty" or "sickly" — yellow-green, brown-orange, etc.
149
+ # When an accent lands here, we nudge it to the nearest attractive neighbor.
150
+ _UGLY_HUE_ZONES = [
151
+ # (start, end, nudge_low, nudge_high) — hues that look muddy
152
+ # at S 0.4-0.7, L 0.35-0.55. When accent lands here, redirect.
153
+ (28, 105, 15, 120), # Dirty yellow/brown/olive/yellow-green zone
154
+ # nudge_low=15 (warm red-orange), nudge_high=120 (true green)
155
+ ]
156
+
157
+
158
+ def _sanitize_accent_hue(hue):
159
+ """Nudge accent hue away from muddy/ugly zones toward attractive neighbors."""
160
+ hue = hue % 360
161
+ for start, end, nudge_low, nudge_high in _UGLY_HUE_ZONES:
162
+ if start <= hue <= end:
163
+ mid = (start + end) / 2
164
+ return nudge_low if hue < mid else nudge_high
165
+ return hue
166
+
167
+ def _hex_to_rgb(hex_str):
168
+ """Convert hex to 'r,g,b' string for rgba() usage."""
169
+ hex_str = hex_str.lstrip('#')
170
+ return f"{int(hex_str[0:2], 16)},{int(hex_str[2:4], 16)},{int(hex_str[4:6], 16)}"
171
+
172
+ def _relative_luminance(hex_str):
173
+ """WCAG 2.1 relative luminance from hex color."""
174
+ hex_str = hex_str.lstrip('#')
175
+ channels = []
176
+ for i in (0, 2, 4):
177
+ c = int(hex_str[i:i+2], 16) / 255.0
178
+ channels.append(c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4)
179
+ return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2]
180
+
181
+ def _contrast_ratio(hex1, hex2):
182
+ """WCAG contrast ratio between two hex colors."""
183
+ l1, l2 = _relative_luminance(hex1), _relative_luminance(hex2)
184
+ lighter, darker = max(l1, l2), min(l1, l2)
185
+ return (lighter + 0.05) / (darker + 0.05)
186
+
187
+ def generate_color_palette(intent="neutral", mode="minimal", harmony=None, seed=None):
188
+ """
189
+ Generative Color Harmony Engine — geometric accent computation + 5 aesthetic modes.
190
+
191
+ LLM is FORBIDDEN from specifying HEX/RGB. It only selects:
192
+ - intent → base hue (from INTENT_HUES)
193
+ - mode → S/L physical boundaries (minimal/dark/pastel/jewel/light)
194
+ - harmony → accent hue geometry (auto-recommended from intent if omitted)
195
+
196
+ Returns dict with:
197
+ - bg: 60% — dominant ground
198
+ - mid: 30% — structural shade
199
+ - accent: 10% — geometric harmony emphasis
200
+ - text: primary text color
201
+ - muted: secondary/caption text
202
+ - surface: card/container background (translucent)
203
+ """
204
+ if seed is not None:
205
+ random.seed(seed)
206
+
207
+ # Auto-recommend harmony from intent if not specified
208
+ if harmony is None or harmony == "auto":
209
+ harmony = INTENT_HARMONY_MAP.get(intent, "split_complementary")
210
+
211
+ base_hue = INTENT_HUES.get(intent, random.randint(0, 359))
212
+
213
+ # 1. Geometric Accent Hue Derivation
214
+ if harmony == "complementary":
215
+ accent_hue = (base_hue + 180) % 360
216
+ elif harmony == "split_complementary":
217
+ accent_hue = (base_hue + random.choice([150, 210])) % 360
218
+ elif harmony == "triadic":
219
+ accent_hue = (base_hue + random.choice([120, 240])) % 360
220
+ elif harmony == "analogous":
221
+ accent_hue = (base_hue + random.choice([30, -30, 45, -45])) % 360
222
+ else: # monochrome
223
+ accent_hue = base_hue
224
+
225
+ # Sanitize accent hue — avoid muddy yellow-green and brown-orange zones
226
+ accent_hue = _sanitize_accent_hue(accent_hue)
227
+
228
+ # 2. Five Aesthetic Modes — hard-lock S and L boundaries
229
+ if mode == "minimal":
230
+ # DEFAULT for 50%+ of documents. Editorial paper tone + high-purity accent.
231
+ # bg has visible tint (S 0.08-0.15, L 0.92-0.96) — not dead white.
232
+ is_warm = random.choice([True, False])
233
+ paper_hue = random.randint(35, 45) if is_warm else random.randint(200, 215)
234
+ bg = _hsl_to_hex(paper_hue, random.uniform(0.08, 0.15), random.uniform(0.92, 0.96))
235
+ mid = _hsl_to_hex(paper_hue, random.uniform(0.10, 0.18), random.uniform(0.85, 0.90))
236
+ accent = _hsl_to_hex(accent_hue, random.uniform(0.55, 0.72), random.uniform(0.42, 0.52))
237
+ text = _hsl_to_hex(paper_hue, 0.05, random.uniform(0.10, 0.15))
238
+ muted = _hsl_to_hex(paper_hue, 0.05, random.uniform(0.45, 0.55))
239
+ surface = f"rgba(0,0,0,{random.uniform(0.01, 0.03):.2f})"
240
+
241
+ elif mode == "dark":
242
+ # Cyber/tech: ultra-low saturation, ultra-low lightness
243
+ bg = _hsl_to_hex(base_hue, random.uniform(0.04, 0.10), random.uniform(0.04, 0.08))
244
+ mid = _hsl_to_hex(base_hue, random.uniform(0.08, 0.15), random.uniform(0.12, 0.20))
245
+ accent = _hsl_to_hex(accent_hue, random.uniform(0.45, 0.60), random.uniform(0.52, 0.62))
246
+ text = _hsl_to_hex(base_hue, 0.05, random.uniform(0.88, 0.95))
247
+ muted = _hsl_to_hex(base_hue, 0.05, random.uniform(0.45, 0.55))
248
+ surface = f"rgba(255,255,255,{random.uniform(0.03, 0.06):.2f})"
249
+
250
+ elif mode == "pastel":
251
+ # Morandi/macaron: medium-low saturation, high lightness
252
+ # Accent tightened: S capped at 0.50 to avoid clashing with tinted bg
253
+ bg = _hsl_to_hex(base_hue, random.uniform(0.15, 0.35), random.uniform(0.85, 0.92))
254
+ mid = _hsl_to_hex(base_hue, random.uniform(0.20, 0.40), random.uniform(0.75, 0.82))
255
+ accent = _hsl_to_hex(accent_hue, random.uniform(0.38, 0.50), random.uniform(0.38, 0.48))
256
+ text = _hsl_to_hex(base_hue, 0.15, random.uniform(0.15, 0.25))
257
+ muted = _hsl_to_hex(base_hue, 0.20, random.uniform(0.45, 0.55))
258
+ surface = f"rgba(255,255,255,{random.uniform(0.30, 0.50):.2f})"
259
+
260
+ elif mode == "jewel":
261
+ # Gem/luxury: medium-high saturation bg, accent must NOT compete — lower S, higher L
262
+ bg = _hsl_to_hex(base_hue, random.uniform(0.40, 0.60), random.uniform(0.15, 0.25))
263
+ mid = _hsl_to_hex(base_hue, random.uniform(0.40, 0.60), random.uniform(0.25, 0.35))
264
+ accent = _hsl_to_hex(accent_hue, random.uniform(0.30, 0.50), random.uniform(0.65, 0.80))
265
+ text = _hsl_to_hex(base_hue, 0.10, random.uniform(0.90, 0.96))
266
+ muted = _hsl_to_hex(base_hue, 0.20, random.uniform(0.60, 0.70))
267
+ surface = f"rgba(0,0,0,{random.uniform(0.20, 0.40):.2f})"
268
+
269
+ else:
270
+ # light — noticeably tinted, not dead white (S 0.10-0.20, L 0.91-0.95)
271
+ bg = _hsl_to_hex(base_hue, random.uniform(0.10, 0.20), random.uniform(0.91, 0.95))
272
+ mid = _hsl_to_hex(base_hue, random.uniform(0.15, 0.25), random.uniform(0.84, 0.90))
273
+ accent = _hsl_to_hex(accent_hue, random.uniform(0.35, 0.45), random.uniform(0.35, 0.45))
274
+ text = _hsl_to_hex(base_hue, 0.08, random.uniform(0.08, 0.15))
275
+ muted = _hsl_to_hex(base_hue, 0.05, random.uniform(0.45, 0.55))
276
+ surface = f"rgba(0,0,0,{random.uniform(0.02, 0.05):.2f})"
277
+
278
+ # 3. WCAG Contrast Safety Net — ensure text:bg ratio ≥ 4.5:1
279
+ text_cr = _contrast_ratio(text, bg)
280
+ if text_cr < 4.5:
281
+ # Push text darker (light modes) or lighter (dark modes)
282
+ r, g, b = (int(bg.lstrip('#')[i:i+2], 16) / 255.0 for i in (0, 2, 4))
283
+ _, bg_l, _ = colorsys.rgb_to_hls(r, g, b)
284
+ if bg_l > 0.5:
285
+ text = _hsl_to_hex(base_hue, 0.08, 0.08) # force near-black
286
+ else:
287
+ text = _hsl_to_hex(base_hue, 0.05, 0.95) # force near-white
288
+
289
+ # 4. Accent-on-bg visibility check — ensure accent stands out (ratio ≥ 3:1)
290
+ accent_cr = _contrast_ratio(accent, bg)
291
+ if accent_cr < 3.0:
292
+ # Nudge accent lightness away from bg
293
+ r, g, b = (int(bg.lstrip('#')[i:i+2], 16) / 255.0 for i in (0, 2, 4))
294
+ _, bg_l, _ = colorsys.rgb_to_hls(r, g, b)
295
+ target_l = 0.35 if bg_l > 0.5 else 0.70
296
+ r2, g2, b2 = (int(accent.lstrip('#')[i:i+2], 16) / 255.0 for i in (0, 2, 4))
297
+ _, _, accent_s = colorsys.rgb_to_hls(r2, g2, b2)
298
+ accent = _hsl_to_hex(accent_hue, accent_s, target_l)
299
+
300
+ return {
301
+ "bg": bg, "bg_rgb": _hex_to_rgb(bg),
302
+ "mid": mid, "mid_rgb": _hex_to_rgb(mid),
303
+ "accent": accent, "accent_rgb": _hex_to_rgb(accent),
304
+ "text": text, "muted": muted,
305
+ "surface": surface,
306
+ "meta": {
307
+ "intent": intent, "mode": mode, "harmony": harmony,
308
+ "base_hue": base_hue, "accent_hue": accent_hue,
309
+ "contrast": {
310
+ "text_on_bg": round(_contrast_ratio(text, bg), 2),
311
+ "accent_on_bg": round(_contrast_ratio(accent, bg), 2),
312
+ }
313
+ }
314
+ }
315
+
316
+ def palette_to_css(palette):
317
+ """Convert palette dict to CSS custom properties."""
318
+ return f""":root {{
319
+ /* 60% ground */
320
+ --c-bg: {palette['bg']};
321
+ --c-bg-rgb: {palette['bg_rgb']};
322
+ /* 30% structure */
323
+ --c-mid: {palette['mid']};
324
+ --c-mid-rgb: {palette['mid_rgb']};
325
+ /* 10% emphasis */
326
+ --c-accent: {palette['accent']};
327
+ --c-accent-rgb: {palette['accent_rgb']};
328
+ /* Typography */
329
+ --c-text: {palette['text']};
330
+ --c-muted: {palette['muted']};
331
+ /* Surfaces */
332
+ --c-surface: {palette['surface']};
333
+ }}"""
334
+
335
+
336
+ # ═══════════════════════════════════════════════════════════════════════
337
+ # 1b. CASCADE PALETTE — Role-Based Unified Color System
338
+ # ═══════════════════════════════════════════════════════════════════════
339
+ #
340
+ # Iron Law: Area ∝ 1/Saturation.
341
+ # The larger the colored area, the LOWER its saturation must be.
342
+ #
343
+ # Role tiers by area usage:
344
+ # XL (>50% of page): page_bg, section_bg → S ≤ 0.08, near-white/near-black
345
+ # L (20-50%): card_bg, table_stripe → S ≤ 0.15
346
+ # M (5-20%): header_fill, sidebar → S ≤ 0.30
347
+ # S (1-5%): border, divider, icon → S ≤ 0.50
348
+ # XS (<1%): accent_dot, badge, tag → S up to 0.75 (the only place high-sat lives)
349
+ #
350
+ # Every color is derived from one base hue. No orphan colors.
351
+
352
+ # Tier saturation caps — enforced at generation AND audit time
353
+ CASCADE_TIER_CAPS = {
354
+ "xl": 0.08, # Page background, section background
355
+ "l": 0.15, # Card background, table stripe
356
+ "m": 0.30, # Header fill, sidebar, cover decorative blocks
357
+ "s": 0.50, # Borders, dividers, icons, chart grid lines
358
+ "xs": 0.75, # Accent dot, badge, tag, data point highlight
359
+ }
360
+
361
+
362
+ def generate_cascade_palette(intent="neutral", mode="minimal", harmony=None, seed=None):
363
+ """
364
+ Generate a role-based palette cascade where every color is derived from one
365
+ base hue and saturation is inversely proportional to usage area.
366
+
367
+ Returns a dict with:
368
+ roles: Complete role table (12 roles, each with hex, hsl, tier, usage_hint)
369
+ cover: Subset of roles for cover page rendering
370
+ body: Subset of roles for body content
371
+ charts: Subset of roles for data visualization
372
+ semantic: Low-saturation semantic colors (success, warning, error, info)
373
+ meta: Generation metadata (intent, mode, harmony, base_hue, audit)
374
+ css: Ready-to-use CSS custom properties
375
+ reportlab: Ready-to-paste ReportLab Python code
376
+ """
377
+ if seed is not None:
378
+ random.seed(seed)
379
+
380
+ if harmony is None or harmony == "auto":
381
+ harmony = INTENT_HARMONY_MAP.get(intent, "split_complementary")
382
+
383
+ base_hue = INTENT_HUES.get(intent, random.randint(0, 359))
384
+
385
+ # Geometric accent hue derivation (same logic as original)
386
+ if harmony == "complementary":
387
+ accent_hue = (base_hue + 180) % 360
388
+ elif harmony == "split_complementary":
389
+ accent_hue = (base_hue + random.choice([150, 210])) % 360
390
+ elif harmony == "triadic":
391
+ accent_hue = (base_hue + random.choice([120, 240])) % 360
392
+ elif harmony == "analogous":
393
+ accent_hue = (base_hue + random.choice([30, -30, 45, -45])) % 360
394
+ else: # monochrome
395
+ accent_hue = base_hue
396
+
397
+ # Sanitize accent hue — avoid muddy zones
398
+ accent_hue = _sanitize_accent_hue(accent_hue)
399
+
400
+ # Secondary hue — between base and accent, for chart variety
401
+ secondary_hue = _sanitize_accent_hue(
402
+ (base_hue + accent_hue) / 2 if accent_hue != base_hue else (base_hue + 30) % 360
403
+ )
404
+
405
+ # Mode-dependent lightness anchors
406
+ is_dark = mode == "dark"
407
+ if is_dark:
408
+ bg_l_range = (0.04, 0.08)
409
+ text_l = random.uniform(0.88, 0.95)
410
+ muted_l = random.uniform(0.50, 0.60)
411
+ elif mode == "jewel":
412
+ bg_l_range = (0.15, 0.25)
413
+ text_l = random.uniform(0.90, 0.96)
414
+ muted_l = random.uniform(0.60, 0.70)
415
+ else: # minimal, pastel, light
416
+ bg_l_range = (0.94, 0.97)
417
+ text_l = random.uniform(0.08, 0.15)
418
+ muted_l = random.uniform(0.45, 0.55)
419
+
420
+ # ── Generate all 12 roles ──
421
+ roles = {}
422
+
423
+ # XL tier: page bg, section bg
424
+ roles["page_bg"] = _make_role(
425
+ base_hue, random.uniform(0.03, 0.08), random.uniform(*bg_l_range),
426
+ "xl", "Page background, full-bleed areas")
427
+ roles["section_bg"] = _make_role(
428
+ base_hue, random.uniform(0.04, 0.08),
429
+ random.uniform(bg_l_range[0] - 0.03, bg_l_range[1] - 0.02) if not is_dark
430
+ else random.uniform(0.08, 0.14),
431
+ "xl", "Section background, alternating bands")
432
+
433
+ # L tier: card bg, table stripe
434
+ roles["card_bg"] = _make_role(
435
+ base_hue, random.uniform(0.06, 0.14),
436
+ random.uniform(0.90, 0.94) if not is_dark else random.uniform(0.10, 0.16),
437
+ "l", "Card/container background, table even rows")
438
+ roles["table_stripe"] = _make_role(
439
+ base_hue, random.uniform(0.05, 0.12),
440
+ random.uniform(0.92, 0.96) if not is_dark else random.uniform(0.08, 0.12),
441
+ "l", "Table alternating row fill")
442
+
443
+ # M tier: header fill, sidebar, cover decorative block
444
+ roles["header_fill"] = _make_role(
445
+ base_hue, random.uniform(0.15, 0.28),
446
+ random.uniform(0.25, 0.40) if not is_dark else random.uniform(0.20, 0.30),
447
+ "m", "Table header, sidebar background, cover top bar")
448
+ roles["cover_block"] = _make_role(
449
+ base_hue, random.uniform(0.12, 0.25),
450
+ random.uniform(0.30, 0.45) if not is_dark else random.uniform(0.15, 0.25),
451
+ "m", "Cover decorative block, sidebar pillar")
452
+
453
+ # S tier: border, divider, icon fill
454
+ roles["border"] = _make_role(
455
+ base_hue, random.uniform(0.10, 0.25),
456
+ random.uniform(0.70, 0.82) if not is_dark else random.uniform(0.25, 0.35),
457
+ "s", "Borders, divider lines, chart grid")
458
+ roles["icon"] = _make_role(
459
+ base_hue, random.uniform(0.25, 0.45),
460
+ random.uniform(0.35, 0.50) if not is_dark else random.uniform(0.55, 0.70),
461
+ "s", "Icons, bullet points, small UI elements")
462
+
463
+ # XS tier: accent, badge, data highlight
464
+ roles["accent"] = _make_role(
465
+ accent_hue, random.uniform(0.50, 0.70),
466
+ random.uniform(0.40, 0.55) if not is_dark else random.uniform(0.55, 0.70),
467
+ "xs", "Primary accent: badges, tags, data point highlights, CTA")
468
+ roles["accent_secondary"] = _make_role(
469
+ secondary_hue, random.uniform(0.40, 0.60),
470
+ random.uniform(0.45, 0.58) if not is_dark else random.uniform(0.50, 0.65),
471
+ "xs", "Secondary accent: chart series 2, secondary badge")
472
+
473
+ # Typography (no tier — text is special)
474
+ roles["text_primary"] = _make_role(
475
+ base_hue, 0.05, text_l,
476
+ "text", "Primary body text")
477
+ roles["text_muted"] = _make_role(
478
+ base_hue, 0.04, muted_l,
479
+ "text", "Captions, footnotes, secondary text")
480
+
481
+ # ── Semantic colors (derived from base hue, low-sat) ──
482
+ semantic = {
483
+ "success": _make_role(140, random.uniform(0.25, 0.40),
484
+ random.uniform(0.35, 0.45) if not is_dark else random.uniform(0.55, 0.65),
485
+ "xs", "Positive: growth, pass, complete"),
486
+ "warning": _make_role(40, random.uniform(0.30, 0.45),
487
+ random.uniform(0.40, 0.50) if not is_dark else random.uniform(0.55, 0.65),
488
+ "xs", "Caution: pending, alert"),
489
+ "error": _make_role(5, random.uniform(0.30, 0.45),
490
+ random.uniform(0.40, 0.50) if not is_dark else random.uniform(0.55, 0.65),
491
+ "xs", "Negative: decline, fail, error"),
492
+ "info": _make_role(210, random.uniform(0.25, 0.40),
493
+ random.uniform(0.40, 0.50) if not is_dark else random.uniform(0.55, 0.65),
494
+ "xs", "Informational: neutral status"),
495
+ }
496
+
497
+ # ── WCAG contrast enforcement ──
498
+ page_bg_hex = roles["page_bg"]["hex"]
499
+ text_hex = roles["text_primary"]["hex"]
500
+ if _contrast_ratio(text_hex, page_bg_hex) < 4.5:
501
+ if not is_dark:
502
+ roles["text_primary"] = _make_role(base_hue, 0.08, 0.08, "text", "Primary body text")
503
+ else:
504
+ roles["text_primary"] = _make_role(base_hue, 0.05, 0.95, "text", "Primary body text")
505
+
506
+ accent_hex = roles["accent"]["hex"]
507
+ if _contrast_ratio(accent_hex, page_bg_hex) < 3.0:
508
+ # Push accent lightness further from bg
509
+ r, g, b = (int(page_bg_hex.lstrip('#')[i:i+2], 16) / 255.0 for i in (0, 2, 4))
510
+ _, bg_l, _ = colorsys.rgb_to_hls(r, g, b)
511
+ target_l = 0.35 if bg_l > 0.5 else 0.75
512
+ roles["accent"] = _make_role(accent_hue, random.uniform(0.50, 0.70), target_l,
513
+ "xs", "Primary accent: badges, tags, data point highlights, CTA")
514
+
515
+ # ── Tier saturation audit (clamp any violations) ──
516
+ for name, role in {**roles, **semantic}.items():
517
+ tier = role["tier"]
518
+ if tier in CASCADE_TIER_CAPS:
519
+ cap = CASCADE_TIER_CAPS[tier]
520
+ if role["hsl"][1] > cap:
521
+ # Re-generate with capped saturation
522
+ capped_s = cap * random.uniform(0.85, 1.0)
523
+ fixed = _make_role(role["hsl"][0], capped_s, role["hsl"][2],
524
+ tier, role["usage_hint"])
525
+ if name in roles:
526
+ roles[name] = fixed
527
+ elif name in semantic:
528
+ semantic[name] = fixed
529
+
530
+ # ── Build convenience subsets ──
531
+ cover_subset = {
532
+ "background": roles["page_bg"]["hex"],
533
+ "top_bar": roles["header_fill"]["hex"],
534
+ "sidebar": roles["cover_block"]["hex"],
535
+ "accent_line": roles["accent"]["hex"],
536
+ "title": roles["text_primary"]["hex"],
537
+ "subtitle": roles["text_muted"]["hex"],
538
+ "watermark": roles["border"]["hex"], # low-opacity usage
539
+ }
540
+
541
+ body_subset = {
542
+ "page_bg": roles["page_bg"]["hex"],
543
+ "section_bg": roles["section_bg"]["hex"],
544
+ "card_bg": roles["card_bg"]["hex"],
545
+ "table_header": roles["header_fill"]["hex"],
546
+ "table_stripe": roles["table_stripe"]["hex"],
547
+ "border": roles["border"]["hex"],
548
+ "heading": roles["text_primary"]["hex"],
549
+ "body_text": roles["text_primary"]["hex"],
550
+ "caption": roles["text_muted"]["hex"],
551
+ "highlight": roles["accent"]["hex"],
552
+ }
553
+
554
+ chart_subset = {
555
+ "series_1": roles["accent"]["hex"],
556
+ "series_2": roles["accent_secondary"]["hex"],
557
+ "series_3": roles["header_fill"]["hex"],
558
+ "series_4": roles["icon"]["hex"],
559
+ "series_5": roles["cover_block"]["hex"],
560
+ "grid": roles["border"]["hex"],
561
+ "axis_text": roles["text_muted"]["hex"],
562
+ "label": roles["text_primary"]["hex"],
563
+ "up": semantic["success"]["hex"],
564
+ "down": semantic["error"]["hex"],
565
+ }
566
+
567
+ # ── Generate outputs ──
568
+ css = _cascade_to_css(roles, semantic)
569
+ reportlab_code = _cascade_to_reportlab(roles, semantic)
570
+
571
+ audit_results = audit_cascade_palette(roles, semantic)
572
+
573
+ return {
574
+ "roles": {k: {"hex": v["hex"], "hsl": v["hsl"], "tier": v["tier"], "usage": v["usage_hint"]} for k, v in roles.items()},
575
+ "cover": cover_subset,
576
+ "body": body_subset,
577
+ "charts": chart_subset,
578
+ "semantic": {k: {"hex": v["hex"], "hsl": v["hsl"]} for k, v in semantic.items()},
579
+ "meta": {
580
+ "intent": intent, "mode": mode, "harmony": harmony,
581
+ "base_hue": base_hue, "accent_hue": accent_hue, "secondary_hue": secondary_hue,
582
+ "contrast": {
583
+ "text_on_bg": round(_contrast_ratio(roles["text_primary"]["hex"], roles["page_bg"]["hex"]), 2),
584
+ "accent_on_bg": round(_contrast_ratio(roles["accent"]["hex"], roles["page_bg"]["hex"]), 2),
585
+ },
586
+ "audit": audit_results,
587
+ },
588
+ "css": css,
589
+ "reportlab": reportlab_code,
590
+ }
591
+
592
+
593
+ def _make_role(h, s, l, tier, usage_hint):
594
+ """Create a role entry with hex, HSL tuple, tier, and usage hint."""
595
+ hex_val = _hsl_to_hex(h, s, l)
596
+ return {
597
+ "hex": hex_val,
598
+ "hsl": (round(h, 1), round(s, 3), round(l, 3)),
599
+ "tier": tier,
600
+ "usage_hint": usage_hint,
601
+ }
602
+
603
+
604
+ def _cascade_to_css(roles, semantic):
605
+ """Convert cascade palette to CSS custom properties."""
606
+ lines = [":root {"]
607
+ lines.append(" /* ── XL tier: backgrounds (S ≤ 0.08) ── */")
608
+ lines.append(f" --page-bg: {roles['page_bg']['hex']};")
609
+ lines.append(f" --section-bg: {roles['section_bg']['hex']};")
610
+ lines.append(" /* ── L tier: surfaces (S ≤ 0.15) ── */")
611
+ lines.append(f" --card-bg: {roles['card_bg']['hex']};")
612
+ lines.append(f" --table-stripe: {roles['table_stripe']['hex']};")
613
+ lines.append(" /* ── M tier: structural fills (S ≤ 0.30) ── */")
614
+ lines.append(f" --header-fill: {roles['header_fill']['hex']};")
615
+ lines.append(f" --cover-block: {roles['cover_block']['hex']};")
616
+ lines.append(" /* ── S tier: edges & icons (S ≤ 0.50) ── */")
617
+ lines.append(f" --border: {roles['border']['hex']};")
618
+ lines.append(f" --icon: {roles['icon']['hex']};")
619
+ lines.append(" /* ── XS tier: emphasis (S ≤ 0.75) ── */")
620
+ lines.append(f" --accent: {roles['accent']['hex']};")
621
+ lines.append(f" --accent-secondary: {roles['accent_secondary']['hex']};")
622
+ lines.append(" /* ── Typography ── */")
623
+ lines.append(f" --text-primary: {roles['text_primary']['hex']};")
624
+ lines.append(f" --text-muted: {roles['text_muted']['hex']};")
625
+ lines.append(" /* ── Semantic (low-sat) ── */")
626
+ for k, v in semantic.items():
627
+ lines.append(f" --semantic-{k}: {v['hex']};")
628
+ lines.append("}")
629
+ return "\n".join(lines)
630
+
631
+
632
+ def _cascade_to_reportlab(roles, semantic):
633
+ """Convert cascade palette to ReportLab Python code."""
634
+ lines = [
635
+ "# ━━ Cascade Palette (auto-generated by design_engine.py palette-cascade) ━━",
636
+ "from reportlab.lib import colors",
637
+ "",
638
+ "# XL tier: backgrounds (area > 50%, S ≤ 0.08)",
639
+ f"PAGE_BG = colors.HexColor('{roles['page_bg']['hex']}')",
640
+ f"SECTION_BG = colors.HexColor('{roles['section_bg']['hex']}')",
641
+ "",
642
+ "# L tier: surfaces (area 20-50%, S ≤ 0.15)",
643
+ f"CARD_BG = colors.HexColor('{roles['card_bg']['hex']}')",
644
+ f"TABLE_STRIPE = colors.HexColor('{roles['table_stripe']['hex']}')",
645
+ "",
646
+ "# M tier: structural fills (area 5-20%, S ≤ 0.30)",
647
+ f"HEADER_FILL = colors.HexColor('{roles['header_fill']['hex']}')",
648
+ f"COVER_BLOCK = colors.HexColor('{roles['cover_block']['hex']}')",
649
+ "",
650
+ "# S tier: edges & icons (area 1-5%, S ≤ 0.50)",
651
+ f"BORDER = colors.HexColor('{roles['border']['hex']}')",
652
+ f"ICON = colors.HexColor('{roles['icon']['hex']}')",
653
+ "",
654
+ "# XS tier: emphasis (area < 1%, S ≤ 0.75)",
655
+ f"ACCENT = colors.HexColor('{roles['accent']['hex']}')",
656
+ f"ACCENT_2 = colors.HexColor('{roles['accent_secondary']['hex']}')",
657
+ "",
658
+ "# Typography",
659
+ f"TEXT_PRIMARY = colors.HexColor('{roles['text_primary']['hex']}')",
660
+ f"TEXT_MUTED = colors.HexColor('{roles['text_muted']['hex']}')",
661
+ "",
662
+ "# Semantic (low-saturation, area-appropriate)",
663
+ f"SEM_SUCCESS = colors.HexColor('{semantic['success']['hex']}')",
664
+ f"SEM_WARNING = colors.HexColor('{semantic['warning']['hex']}')",
665
+ f"SEM_ERROR = colors.HexColor('{semantic['error']['hex']}')",
666
+ f"SEM_INFO = colors.HexColor('{semantic['info']['hex']}')",
667
+ ]
668
+ return "\n".join(lines)
669
+
670
+
671
+ def audit_cascade_palette(roles, semantic):
672
+ """Audit cascade palette for tier saturation violations and WCAG contrast."""
673
+ violations = []
674
+ for name, role in {**roles, **semantic}.items():
675
+ tier = role["tier"]
676
+ if tier in CASCADE_TIER_CAPS:
677
+ cap = CASCADE_TIER_CAPS[tier]
678
+ s = role["hsl"][1]
679
+ if s > cap:
680
+ violations.append(f"{name}: S={s:.3f} exceeds tier '{tier}' cap {cap}")
681
+
682
+ # WCAG checks
683
+ bg_hex = roles["page_bg"]["hex"]
684
+ text_hex = roles["text_primary"]["hex"]
685
+ cr = _contrast_ratio(text_hex, bg_hex)
686
+ if cr < 4.5:
687
+ violations.append(f"text_primary:page_bg contrast {cr:.2f} < 4.5:1 (WCAG AA)")
688
+
689
+ accent_hex = roles["accent"]["hex"]
690
+ cr_a = _contrast_ratio(accent_hex, bg_hex)
691
+ if cr_a < 3.0:
692
+ violations.append(f"accent:page_bg contrast {cr_a:.2f} < 3.0:1 (accent invisible)")
693
+
694
+ # Header fill should be readable with white text on it
695
+ hf_hex = roles["header_fill"]["hex"]
696
+ cr_hf = _contrast_ratio("#ffffff", hf_hex)
697
+ if cr_hf < 3.0:
698
+ violations.append(f"white on header_fill contrast {cr_hf:.2f} < 3.0:1 (header text unreadable)")
699
+
700
+ return violations
701
+
702
+
703
+ # ═══════════════════════════════════════════════════════════════════════
704
+ # 2. GENERATIVE SVG — Algorithmic Art Backgrounds
705
+ # ═══════════════════════════════════════════════════════════════════════
706
+ #
707
+ # Two primary modes:
708
+ # - "flow": 3-5 large-radius bézier curves at ultra-low opacity (0.05)
709
+ # Creates organic, breathing atmospheric depth
710
+ # - "grid": 1px reference grid or noise texture
711
+ # Creates structured, architectural underlying rhythm
712
+ #
713
+ # All SVG is inline-ready (no external files needed).
714
+
715
+ def _svg_open(w, h):
716
+ return f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" width="{w}" height="{h}">'
717
+
718
+ def _random_bezier_path(w, h):
719
+ """Generate a single flowing bézier curve across the canvas."""
720
+ # Start from a random edge point
721
+ x0 = random.uniform(-w * 0.2, w * 0.3)
722
+ y0 = random.uniform(0, h)
723
+ # End at the opposite side
724
+ x3 = random.uniform(w * 0.7, w * 1.2)
725
+ y3 = random.uniform(0, h)
726
+ # Control points — large sweeps for organic feel
727
+ cx1 = random.uniform(w * 0.1, w * 0.5)
728
+ cy1 = random.uniform(-h * 0.3, h * 1.3)
729
+ cx2 = random.uniform(w * 0.5, w * 0.9)
730
+ cy2 = random.uniform(-h * 0.3, h * 1.3)
731
+ return f"M{x0:.0f},{y0:.0f} C{cx1:.0f},{cy1:.0f} {cx2:.0f},{cy2:.0f} {x3:.0f},{y3:.0f}"
732
+
733
+ def generate_flow_svg(w, h, color="#8a8a8a", curves=4, stroke_width=80, opacity=0.05):
734
+ """
735
+ Flow mode: ultra-wide, ultra-faint bézier curves.
736
+ Creates atmospheric depth without competing with content.
737
+ """
738
+ random.seed(42)
739
+ svg = _svg_open(w, h)
740
+ svg += '\n <defs>'
741
+ svg += f'\n <linearGradient id="fg" x1="0" y1="0" x2="1" y2="1">'
742
+ svg += f'\n <stop offset="0%" stop-color="{color}" stop-opacity="{opacity}"/>'
743
+ svg += f'\n <stop offset="50%" stop-color="{color}" stop-opacity="{opacity * 1.5:.3f}"/>'
744
+ svg += f'\n <stop offset="100%" stop-color="{color}" stop-opacity="{opacity * 0.5:.3f}"/>'
745
+ svg += '\n </linearGradient>'
746
+ svg += '\n </defs>'
747
+
748
+ for i in range(curves):
749
+ path = _random_bezier_path(w, h)
750
+ sw = stroke_width + random.uniform(-20, 30)
751
+ svg += f'\n <path d="{path}" fill="none" stroke="url(#fg)" '
752
+ svg += f'stroke-width="{sw:.0f}" stroke-linecap="round" opacity="{opacity + i * 0.01:.3f}"/>'
753
+
754
+ svg += '\n</svg>'
755
+ return svg
756
+
757
+ def generate_grid_svg(w, h, color="#888888", spacing=60, line_width=0.5, opacity=0.04):
758
+ """
759
+ Grid mode: architectural reference grid.
760
+ Ultra-faint 1px lines creating underlying structure.
761
+ """
762
+ svg = _svg_open(w, h)
763
+ svg += f'\n <g opacity="{opacity}">'
764
+ # Vertical lines
765
+ for x in range(0, int(w) + 1, spacing):
766
+ svg += f'\n <line x1="{x}" y1="0" x2="{x}" y2="{h}" stroke="{color}" stroke-width="{line_width}"/>'
767
+ # Horizontal lines
768
+ for y in range(0, int(h) + 1, spacing):
769
+ svg += f'\n <line x1="0" y1="{y}" x2="{w}" y2="{y}" stroke="{color}" stroke-width="{line_width}"/>'
770
+ svg += '\n </g>'
771
+ svg += '\n</svg>'
772
+ return svg
773
+
774
+ def generate_noise_svg(w, h, frequency=0.8, octaves=4, opacity=0.035):
775
+ """
776
+ Noise mode: feTurbulence grain texture.
777
+ Adds tactile paper-like quality.
778
+ """
779
+ svg = _svg_open(w, h)
780
+ svg += f"""
781
+ <defs>
782
+ <filter id="grain" x="0" y="0" width="100%" height="100%">
783
+ <feTurbulence type="fractalNoise" baseFrequency="{frequency}"
784
+ numOctaves="{octaves}" stitchTiles="stitch" result="noise"/>
785
+ <feColorMatrix type="saturate" values="0" in="noise" result="grey"/>
786
+ </filter>
787
+ </defs>
788
+ <rect width="{w}" height="{h}" filter="url(#grain)" opacity="{opacity}"/>"""
789
+ svg += '\n</svg>'
790
+ return svg
791
+
792
+ def _generate_data_driven_svg(data_points, w=720, h=960, color="#8a8a8a"):
793
+ """
794
+ Content-Aware SVG: Transform business data arrays into Bézier background curves.
795
+ The background subtly echoes the data's shape — a cross-modal design metaphor.
796
+ """
797
+ if not data_points or len(data_points) < 2:
798
+ return generate_flow_svg(w, h, color)
799
+
800
+ n = len(data_points)
801
+ min_v = min(data_points)
802
+ max_v = max(data_points)
803
+ rng = max_v - min_v if max_v != min_v else 1.0
804
+
805
+ # Normalize data to canvas coordinates
806
+ # X: evenly spaced across width; Y: mapped to 20%-80% of height (inverted for SVG)
807
+ points = []
808
+ for i, v in enumerate(data_points):
809
+ x = (i / (n - 1)) * w
810
+ y_norm = (v - min_v) / rng # 0..1
811
+ y = h * 0.8 - y_norm * (h * 0.6) # Map to 20%-80% height band
812
+ points.append((x, y))
813
+
814
+ # Build smooth Bézier path through all points (Catmull-Rom → cubic Bézier)
815
+ def catmull_to_bezier(p0, p1, p2, p3, tension=0.5):
816
+ """Convert 4 Catmull-Rom points to cubic Bézier control points for segment p1→p2."""
817
+ cp1x = p1[0] + (p2[0] - p0[0]) / (6 * tension)
818
+ cp1y = p1[1] + (p2[1] - p0[1]) / (6 * tension)
819
+ cp2x = p2[0] - (p3[0] - p1[0]) / (6 * tension)
820
+ cp2y = p2[1] - (p3[1] - p1[1]) / (6 * tension)
821
+ return (cp1x, cp1y), (cp2x, cp2y)
822
+
823
+ svg_paths = ""
824
+ # Generate 3 layers at different offsets for depth
825
+ for layer_idx, (opacity, y_offset, thickness) in enumerate([
826
+ (0.08, 0, 3), (0.05, 60, 2), (0.03, -40, 1.5)
827
+ ]):
828
+ pts = [(px, py + y_offset) for px, py in points]
829
+ # Pad start/end for Catmull-Rom
830
+ padded = [pts[0]] + pts + [pts[-1]]
831
+ d = f"M {padded[1][0]:.1f},{padded[1][1]:.1f} "
832
+ for i in range(1, len(padded) - 2):
833
+ cp1, cp2 = catmull_to_bezier(padded[i-1], padded[i], padded[i+1], padded[i+2])
834
+ d += f"C {cp1[0]:.1f},{cp1[1]:.1f} {cp2[0]:.1f},{cp2[1]:.1f} {padded[i+1][0]:.1f},{padded[i+1][1]:.1f} "
835
+
836
+ # Main stroke
837
+ svg_paths += f'<path d="{d}" fill="none" stroke="{color}" stroke-width="{thickness}" opacity="{opacity}" />\n'
838
+ # Filled area below the curve
839
+ fill_d = d + f"L {w},{h} L 0,{h} Z"
840
+ svg_paths += f'<path d="{fill_d}" fill="{color}" opacity="{opacity * 0.4}" />\n'
841
+
842
+ return f'<svg viewBox="0 0 {w} {h}" xmlns="http://www.w3.org/2000/svg" style="width:100%;height:100%">{svg_paths}</svg>'
843
+
844
+
845
+ def generate_supergraphic_svg(w, h, color="#8a8a8a", seed=42):
846
+ """
847
+ Supergraphic mode: oversized geometric shapes (circles, rectangles, polygons)
848
+ cropped by the canvas edge, rendered at 3-5% opacity.
849
+ Creates "blueprint of a larger world" feeling — McKinsey / Pentagram style.
850
+ Shapes deliberately overflow the viewport so only partial arcs/edges are visible.
851
+ """
852
+ random.seed(seed)
853
+ svg = _svg_open(w, h)
854
+ # Layer 1: Giant concentric circles, center placed off-canvas
855
+ cx = random.uniform(w * 0.6, w * 1.3) # right-biased, partially off-canvas
856
+ cy = random.uniform(-h * 0.2, h * 0.4) # top-biased
857
+ for i in range(4):
858
+ r = w * (0.6 + i * 0.35) # radii from 60% to 165% of width — always overflowing
859
+ opacity = 0.04 - i * 0.008 # outer rings fainter
860
+ svg += f'\n <circle cx="{cx:.0f}" cy="{cy:.0f}" r="{r:.0f}" '
861
+ svg += f'fill="none" stroke="{color}" stroke-width="1.5" opacity="{max(opacity, 0.015):.3f}"/>'
862
+
863
+ # Layer 2: Oversized rotated rectangles, clipped by viewport
864
+ for _ in range(2):
865
+ rx = random.uniform(-w * 0.3, w * 0.5)
866
+ ry = random.uniform(h * 0.3, h * 1.2)
867
+ rw = random.uniform(w * 0.8, w * 1.6)
868
+ rh = random.uniform(h * 0.5, h * 1.2)
869
+ angle = random.uniform(-15, 25)
870
+ svg += f'\n <rect x="{rx:.0f}" y="{ry:.0f}" width="{rw:.0f}" height="{rh:.0f}" '
871
+ svg += f'fill="none" stroke="{color}" stroke-width="1" opacity="0.025" '
872
+ svg += f'transform="rotate({angle:.1f} {rx + rw/2:.0f} {ry + rh/2:.0f})"/>'
873
+
874
+ # Layer 3: A single massive polygon (pentagon/hexagon) barely visible
875
+ sides = random.choice([5, 6, 8])
876
+ pcx = random.uniform(-w * 0.1, w * 0.4)
877
+ pcy = random.uniform(h * 0.5, h * 1.1)
878
+ pr = w * random.uniform(0.9, 1.4)
879
+ angle_offset = random.uniform(0, 360 / sides)
880
+ points = []
881
+ for i in range(sides):
882
+ a = math.radians(angle_offset + i * 360 / sides)
883
+ px = pcx + pr * math.cos(a)
884
+ py = pcy + pr * math.sin(a)
885
+ points.append(f"{px:.0f},{py:.0f}")
886
+ svg += f'\n <polygon points="{" ".join(points)}" '
887
+ svg += f'fill="none" stroke="{color}" stroke-width="1" opacity="0.02"/>'
888
+
889
+ svg += '\n</svg>'
890
+ return svg
891
+
892
+
893
+ def generate_ordered_texture_svg(w, h, color="#8a8a8a", seed=42):
894
+ """
895
+ Ordered Texture mode: precision dot-matrix, coordinate grids, and contour lines
896
+ placed in specific corners/edges of the canvas (not full coverage).
897
+ Creates "engineered precision" feeling — ideal for tech, finance, data reports.
898
+ """
899
+ random.seed(seed)
900
+ svg = _svg_open(w, h)
901
+
902
+ # Region 1: Dot matrix in top-right corner (10x10 grid of small circles)
903
+ dot_cols, dot_rows = 12, 10
904
+ dot_spacing = 18
905
+ dot_r = 2
906
+ dot_origin_x = w - dot_cols * dot_spacing - 40 # right-aligned with margin
907
+ dot_origin_y = 30 # top margin
908
+ svg += f'\n <g opacity="0.08">'
909
+ for row in range(dot_rows):
910
+ for col in range(dot_cols):
911
+ dx = dot_origin_x + col * dot_spacing
912
+ dy = dot_origin_y + row * dot_spacing
913
+ svg += f'\n <circle cx="{dx}" cy="{dy}" r="{dot_r}" fill="{color}"/>'
914
+ svg += '\n </g>'
915
+
916
+ # Region 2: Coordinate grid lines in bottom-left quadrant (blueprint style)
917
+ grid_x0, grid_y0 = 20, h * 0.7
918
+ grid_x1, grid_y1 = w * 0.45, h - 20
919
+ grid_spacing = 30
920
+ svg += f'\n <g opacity="0.05" stroke="{color}" stroke-width="0.5" stroke-dasharray="4,6">'
921
+ # Vertical lines
922
+ x = grid_x0
923
+ while x <= grid_x1:
924
+ svg += f'\n <line x1="{x:.0f}" y1="{grid_y0:.0f}" x2="{x:.0f}" y2="{grid_y1:.0f}"/>'
925
+ x += grid_spacing
926
+ # Horizontal lines
927
+ y = grid_y0
928
+ while y <= grid_y1:
929
+ svg += f'\n <line x1="{grid_x0:.0f}" y1="{y:.0f}" x2="{grid_x1:.0f}" y2="{y:.0f}"/>'
930
+ y += grid_spacing
931
+ svg += '\n </g>'
932
+
933
+ # Region 3: Tick marks along the grid (ruler effect)
934
+ svg += f'\n <g opacity="0.06" stroke="{color}" stroke-width="0.8">'
935
+ x = grid_x0
936
+ while x <= grid_x1:
937
+ svg += f'\n <line x1="{x:.0f}" y1="{grid_y1:.0f}" x2="{x:.0f}" y2="{grid_y1 + 5:.0f}"/>'
938
+ x += grid_spacing
939
+ svg += '\n </g>'
940
+
941
+ # Region 4: Flowing contour lines (Bézier) across mid-right area
942
+ svg += f'\n <g opacity="0.04" fill="none" stroke="{color}" stroke-width="1">'
943
+ for i in range(5):
944
+ y_base = h * 0.35 + i * 35
945
+ x_start = w * 0.55
946
+ x_end = w + 20 # overflow right edge
947
+ cx1 = x_start + (x_end - x_start) * 0.3 + random.uniform(-30, 30)
948
+ cy1 = y_base + random.uniform(-40, 40)
949
+ cx2 = x_start + (x_end - x_start) * 0.7 + random.uniform(-30, 30)
950
+ cy2 = y_base + random.uniform(-40, 40)
951
+ svg += f'\n <path d="M{x_start:.0f},{y_base:.0f} C{cx1:.0f},{cy1:.0f} {cx2:.0f},{cy2:.0f} {x_end:.0f},{y_base + random.uniform(-20, 20):.0f}"/>'
952
+ svg += '\n </g>'
953
+
954
+ # Region 5: Cross-hair markers at 2-3 strategic points
955
+ for _ in range(3):
956
+ mx = random.uniform(w * 0.15, w * 0.85)
957
+ my = random.uniform(h * 0.15, h * 0.85)
958
+ size = 8
959
+ svg += f'\n <g opacity="0.06" stroke="{color}" stroke-width="0.8">'
960
+ svg += f'\n <line x1="{mx - size}" y1="{my}" x2="{mx + size}" y2="{my}"/>'
961
+ svg += f'\n <line x1="{mx}" y1="{my - size}" x2="{mx}" y2="{my + size}"/>'
962
+ svg += f'\n <circle cx="{mx}" cy="{my}" r="{size * 0.6:.0f}" fill="none"/>'
963
+ svg += '\n </g>'
964
+
965
+ svg += '\n</svg>'
966
+ return svg
967
+
968
+
969
+ def generate_generative_svg(svg_type="flow", w=720, h=960, color="#8a8a8a"):
970
+ """Route to the appropriate SVG generator."""
971
+ if svg_type == "flow":
972
+ return generate_flow_svg(w, h, color)
973
+ elif svg_type == "grid":
974
+ return generate_grid_svg(w, h, color)
975
+ elif svg_type == "noise":
976
+ return generate_noise_svg(w, h)
977
+ elif svg_type == "supergraphic":
978
+ return generate_supergraphic_svg(w, h, color)
979
+ elif svg_type == "ordered_texture":
980
+ return generate_ordered_texture_svg(w, h, color)
981
+ else:
982
+ # Default: flow + noise layered
983
+ flow = generate_flow_svg(w, h, color)
984
+ return flow
985
+
986
+
987
+ def generate_continuous_flow_svg(w, h, total_pages, color="#8a8a8a", curves=4, stroke_width=80, opacity=0.05):
988
+ """
989
+ Continuous Flow mode: generates ONE large SVG spanning all pages.
990
+ Returns a list of per-page SVG strings, each using viewBox to slice the master.
991
+
992
+ The bezier curves are constrained to have anchor points every ~480px vertically,
993
+ ensuring visible content on every page.
994
+ """
995
+ total_h = h * total_pages
996
+ random.seed(42)
997
+
998
+ # Build the master path data
999
+ paths_data = []
1000
+ for _ in range(curves):
1001
+ # Generate anchor points — one every 480px ensures ~2 per page
1002
+ num_anchors = max(3, int(total_h / 480))
1003
+ anchors = []
1004
+ for i in range(num_anchors):
1005
+ ax = random.uniform(w * 0.1, w * 0.9)
1006
+ ay = (total_h / (num_anchors - 1)) * i
1007
+ anchors.append((ax, ay))
1008
+
1009
+ # Build cubic bezier path through anchors
1010
+ path = f"M{anchors[0][0]:.0f},{anchors[0][1]:.0f}"
1011
+ for i in range(1, len(anchors)):
1012
+ prev = anchors[i - 1]
1013
+ curr = anchors[i]
1014
+ # Control points: spread horizontally for organic feel
1015
+ cx1 = random.uniform(w * 0.0, w * 1.0)
1016
+ cy1 = prev[1] + (curr[1] - prev[1]) * 0.33 + random.uniform(-100, 100)
1017
+ cx2 = random.uniform(w * 0.0, w * 1.0)
1018
+ cy2 = prev[1] + (curr[1] - prev[1]) * 0.66 + random.uniform(-100, 100)
1019
+ path += f" C{cx1:.0f},{cy1:.0f} {cx2:.0f},{cy2:.0f} {curr[0]:.0f},{curr[1]:.0f}"
1020
+
1021
+ sw = stroke_width + random.uniform(-20, 30)
1022
+ paths_data.append((path, sw))
1023
+
1024
+ # Generate per-page SVG slices
1025
+ page_svgs = []
1026
+ gradient_def = f'''<defs>
1027
+ <linearGradient id="fg" x1="0" y1="0" x2="1" y2="1">
1028
+ <stop offset="0%" stop-color="{color}" stop-opacity="{opacity}"/>
1029
+ <stop offset="50%" stop-color="{color}" stop-opacity="{opacity * 1.5:.3f}"/>
1030
+ <stop offset="100%" stop-color="{color}" stop-opacity="{opacity * 0.5:.3f}"/>
1031
+ </linearGradient>
1032
+ </defs>'''
1033
+
1034
+ for page_idx in range(total_pages):
1035
+ vy = page_idx * h
1036
+ svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 {vy} {w} {h}" width="{w}" height="{h}">'
1037
+ svg += f'\n {gradient_def}'
1038
+ for i, (path, sw) in enumerate(paths_data):
1039
+ svg += f'\n <path d="{path}" fill="none" stroke="url(#fg)" '
1040
+ svg += f'stroke-width="{sw:.0f}" stroke-linecap="round" opacity="{opacity + i * 0.01:.3f}"/>'
1041
+ svg += '\n</svg>'
1042
+ page_svgs.append(svg)
1043
+
1044
+ return page_svgs
1045
+
1046
+
1047
+ def generate_unified_svg(w, h, total_pages, svg_type, color="#8a8a8a", curves=4, stroke_width=80, opacity=0.05):
1048
+ """
1049
+ Generate a single SVG that spans the full continuous canvas (w x h*total_pages).
1050
+ Unlike generate_continuous_flow_svg which returns per-page slices,
1051
+ this returns ONE svg string for the entire document.
1052
+ Used by the continuous-canvas rendering mode.
1053
+ """
1054
+ total_h = h * total_pages
1055
+ random.seed(42)
1056
+
1057
+ if svg_type in ("continuous_flow", "flow"):
1058
+ # Bezier curves spanning entire height
1059
+ paths_data = []
1060
+ for _ in range(curves):
1061
+ num_anchors = max(3, int(total_h / 480))
1062
+ anchors = []
1063
+ for i in range(num_anchors):
1064
+ ax = random.uniform(w * 0.1, w * 0.9)
1065
+ ay = (total_h / (num_anchors - 1)) * i
1066
+ anchors.append((ax, ay))
1067
+ path = f"M{anchors[0][0]:.0f},{anchors[0][1]:.0f}"
1068
+ for i in range(1, len(anchors)):
1069
+ prev = anchors[i - 1]
1070
+ curr = anchors[i]
1071
+ cx1 = random.uniform(w * 0.0, w * 1.0)
1072
+ cy1 = prev[1] + (curr[1] - prev[1]) * 0.33 + random.uniform(-100, 100)
1073
+ cx2 = random.uniform(w * 0.0, w * 1.0)
1074
+ cy2 = prev[1] + (curr[1] - prev[1]) * 0.66 + random.uniform(-100, 100)
1075
+ path += f" C{cx1:.0f},{cy1:.0f} {cx2:.0f},{cy2:.0f} {curr[0]:.0f},{curr[1]:.0f}"
1076
+ sw = stroke_width + random.uniform(-20, 30)
1077
+ paths_data.append((path, sw))
1078
+
1079
+ gradient_def = f'''<defs>
1080
+ <linearGradient id="fg" x1="0" y1="0" x2="1" y2="1">
1081
+ <stop offset="0%" stop-color="{color}" stop-opacity="{opacity}"/>
1082
+ <stop offset="50%" stop-color="{color}" stop-opacity="{opacity * 1.5:.3f}"/>
1083
+ <stop offset="100%" stop-color="{color}" stop-opacity="{opacity * 0.5:.3f}"/>
1084
+ </linearGradient>
1085
+ </defs>'''
1086
+
1087
+ svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {total_h}" width="{w}" height="{total_h}">'
1088
+ svg += f'\n {gradient_def}'
1089
+ for i, (path, sw) in enumerate(paths_data):
1090
+ svg += f'\n <path d="{path}" fill="none" stroke="url(#fg)" '
1091
+ svg += f'stroke-width="{sw:.0f}" stroke-linecap="round" opacity="{opacity + i * 0.01:.3f}"/>'
1092
+ svg += '\n</svg>'
1093
+ return svg
1094
+
1095
+ elif svg_type == "grid":
1096
+ # Grid pattern spanning full height
1097
+ svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {total_h}" width="{w}" height="{total_h}">'
1098
+ spacing = 60
1099
+ for x in range(0, w + 1, spacing):
1100
+ svg += f'\n <line x1="{x}" y1="0" x2="{x}" y2="{total_h}" stroke="{color}" stroke-width="0.5" opacity="{opacity}"/>'
1101
+ for y in range(0, int(total_h) + 1, spacing):
1102
+ svg += f'\n <line x1="0" y1="{y}" x2="{w}" y2="{y}" stroke="{color}" stroke-width="0.5" opacity="{opacity}"/>'
1103
+ svg += '\n</svg>'
1104
+ return svg
1105
+
1106
+ elif svg_type == "noise":
1107
+ # Noise dots spanning full height
1108
+ svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {total_h}" width="{w}" height="{total_h}">'
1109
+ num_dots = int(200 * total_pages)
1110
+ for _ in range(num_dots):
1111
+ cx = random.uniform(0, w)
1112
+ cy = random.uniform(0, total_h)
1113
+ r = random.uniform(0.5, 2.5)
1114
+ svg += f'\n <circle cx="{cx:.0f}" cy="{cy:.0f}" r="{r:.1f}" fill="{color}" opacity="{random.uniform(opacity * 0.3, opacity * 1.5):.3f}"/>'
1115
+ svg += '\n</svg>'
1116
+ return svg
1117
+
1118
+ return ""
1119
+
1120
+
1121
+ # ═══════════════════════════════════════════════════════════════════════
1122
+ # 3. LAYOUT CALCULATOR — Deliberate Spatial Tension
1123
+ # ═══════════════════════════════════════════════════════════════════════
1124
+ #
1125
+ # Returns absolute coordinates for elements with intentional:
1126
+ # - Offset: elements not perfectly centered (art tension)
1127
+ # - Overlap: controlled z-index collisions
1128
+ # - Breathing margin: 15% minimum on all edges
1129
+
1130
+ BREATHING_MARGIN = 0.12 # 12% of canvas on each edge (was 15%, too tight for content-dense pages)
1131
+
1132
+ def calculate_layout(elements, w=720, h=960, style="offset"):
1133
+ """
1134
+ Calculate positioned layout for named elements.
1135
+
1136
+ Args:
1137
+ elements: list of element names (e.g. ["hero", "body", "meta", "footer"])
1138
+ style: "offset" (deliberate asymmetry), "centered" (formal), "stacked" (vertical flow)
1139
+
1140
+ Returns:
1141
+ dict mapping element names to {x, y, w, h, rotation} in pixels
1142
+ """
1143
+ # Safe area (15% breathing margin on all sides)
1144
+ safe_x = w * BREATHING_MARGIN
1145
+ safe_y = h * BREATHING_MARGIN
1146
+ safe_w = w * (1 - 2 * BREATHING_MARGIN)
1147
+ safe_h = h * (1 - 2 * BREATHING_MARGIN)
1148
+
1149
+ layout = {}
1150
+
1151
+ if style == "offset":
1152
+ # Asymmetric placement — elements shift left/right of center
1153
+ regions = _divide_vertical(safe_x, safe_y, safe_w, safe_h, len(elements))
1154
+ for i, name in enumerate(elements):
1155
+ rx, ry, rw, rh = regions[i]
1156
+ # Apply deliberate offset: odd elements shift left, even shift right
1157
+ offset_x = rw * 0.08 * (-1 if i % 2 == 0 else 1)
1158
+ layout[name] = {
1159
+ "x": round(rx + offset_x, 1),
1160
+ "y": round(ry, 1),
1161
+ "w": round(rw * 0.85, 1), # Don't fill the full width
1162
+ "h": round(rh * 0.85, 1),
1163
+ "rotation": round(random.uniform(-1.5, 1.5), 2) if name != "body" else 0,
1164
+ }
1165
+
1166
+ elif style == "centered":
1167
+ # Formal centered — golden ratio vertical split
1168
+ regions = _divide_vertical(safe_x, safe_y, safe_w, safe_h, len(elements))
1169
+ for i, name in enumerate(elements):
1170
+ rx, ry, rw, rh = regions[i]
1171
+ layout[name] = {
1172
+ "x": round(rx + (rw * 0.075), 1), # Slight horizontal centering margin
1173
+ "y": round(ry, 1),
1174
+ "w": round(rw * 0.85, 1),
1175
+ "h": round(rh * 0.9, 1),
1176
+ "rotation": 0,
1177
+ }
1178
+
1179
+ elif style == "overlap":
1180
+ # Controlled overlaps — elements bleed into each other's space
1181
+ regions = _divide_vertical(safe_x, safe_y, safe_w, safe_h, len(elements))
1182
+ for i, name in enumerate(elements):
1183
+ rx, ry, rw, rh = regions[i]
1184
+ overlap_y = rh * 0.15 if i > 0 else 0 # Pull up into previous region
1185
+ layout[name] = {
1186
+ "x": round(rx, 1),
1187
+ "y": round(ry - overlap_y, 1),
1188
+ "w": round(rw, 1),
1189
+ "h": round(rh + overlap_y * 0.5, 1),
1190
+ "rotation": 0,
1191
+ "z_index": len(elements) - i, # Later elements on top
1192
+ }
1193
+
1194
+ return layout
1195
+
1196
+ def _divide_vertical(x, y, w, h, n):
1197
+ """Divide a rectangle into n vertical bands with golden-ratio-inspired proportions."""
1198
+ if n <= 0:
1199
+ return []
1200
+ if n == 1:
1201
+ return [(x, y, w, h)]
1202
+
1203
+ # Weighted distribution: first element (hero) gets more space
1204
+ weights = [1.618 if i == 0 else 1.0 for i in range(n)]
1205
+ total = sum(weights)
1206
+
1207
+ regions = []
1208
+ current_y = y
1209
+ for i in range(n):
1210
+ region_h = h * weights[i] / total
1211
+ regions.append((x, current_y, w, region_h))
1212
+ current_y += region_h
1213
+
1214
+ return regions
1215
+
1216
+
1217
+ # ═══════════════════════════════════════════════════════════════════════
1218
+ # VALIDATION — Post-generation color audit
1219
+ # ═══════════════════════════════════════════════════════════════════════
1220
+
1221
+ def audit_palette(palette):
1222
+ """
1223
+ Strict audit: mode-specific S/L bounds + WCAG contrast checks.
1224
+ Returns list of violations (empty = clean).
1225
+ """
1226
+ violations = []
1227
+ mode = palette.get("meta", {}).get("mode", "minimal")
1228
+
1229
+ for key in ["bg", "mid", "accent", "text"]:
1230
+ hex_val = palette.get(key, "")
1231
+ if not hex_val.startswith("#"):
1232
+ continue
1233
+ r, g, b = (int(hex_val[i:i+2], 16) / 255.0 for i in (1, 3, 5))
1234
+ h, l, s = colorsys.rgb_to_hls(r, g, b)
1235
+
1236
+ # Tight bg/mid saturation limits per mode
1237
+ if key in ("bg", "mid"):
1238
+ limits = {"minimal": 0.20, "dark": 0.16, "pastel": 0.42, "jewel": 0.62, "light": 0.28}
1239
+ cap = limits.get(mode, 0.15)
1240
+ if s > cap:
1241
+ violations.append(f"{key}: S={s:.3f} > {cap} in {mode} mode")
1242
+
1243
+ # Tight accent saturation — pastel/jewel reined in
1244
+ if key == "accent":
1245
+ accent_caps = {"minimal": 0.78, "dark": 0.62, "pastel": 0.52, "jewel": 0.52, "light": 0.48}
1246
+ cap = accent_caps.get(mode, 0.60)
1247
+ if s > cap:
1248
+ violations.append(f"accent: S={s:.3f} > {cap} in {mode} mode")
1249
+
1250
+ # Lightness guardrails
1251
+ if key == "bg":
1252
+ if mode == "dark" and l > 0.10:
1253
+ violations.append(f"bg L={l:.3f} > 0.10 in dark (muddy middle)")
1254
+ elif mode == "minimal" and l < 0.90:
1255
+ violations.append(f"bg L={l:.3f} < 0.90 in minimal (too dark for paper)")
1256
+ elif mode == "light" and l < 0.88:
1257
+ violations.append(f"bg L={l:.3f} < 0.88 in light (too dark)")
1258
+ elif mode == "jewel" and l > 0.28:
1259
+ violations.append(f"bg L={l:.3f} > 0.28 in jewel (not deep enough)")
1260
+ elif mode == "pastel" and l < 0.83:
1261
+ violations.append(f"bg L={l:.3f} < 0.83 in pastel (too dark for Morandi)")
1262
+
1263
+ # WCAG contrast checks
1264
+ bg_hex = palette.get("bg", "")
1265
+ text_hex = palette.get("text", "")
1266
+ accent_hex = palette.get("accent", "")
1267
+ if bg_hex.startswith("#") and text_hex.startswith("#"):
1268
+ cr = _contrast_ratio(text_hex, bg_hex)
1269
+ if cr < 4.5:
1270
+ violations.append(f"text:bg contrast {cr:.2f} < 4.5:1 (WCAG AA fail)")
1271
+ if bg_hex.startswith("#") and accent_hex.startswith("#"):
1272
+ cr = _contrast_ratio(accent_hex, bg_hex)
1273
+ if cr < 2.5:
1274
+ violations.append(f"accent:bg contrast {cr:.2f} < 2.5:1 (accent invisible)")
1275
+
1276
+ return violations
1277
+
1278
+
1279
+ # ═══════════════════════════════════════════════════════════════════════
1280
+ # CLI
1281
+ # ═══════════════════════════════════════════════════════════════════════
1282
+
1283
+ def main():
1284
+ parser = argparse.ArgumentParser(
1285
+ description="Design Engine — aesthetic computation for art-direction-first PDF",
1286
+ formatter_class=argparse.RawDescriptionHelpFormatter,
1287
+ epilog="""
1288
+ Examples:
1289
+ %(prog)s palette --intent serenity --mode dark
1290
+ %(prog)s palette --intent tension --mode light --seed 42
1291
+ %(prog)s palette-cascade --intent cold --mode minimal
1292
+ %(prog)s palette-cascade --intent neutral --format reportlab
1293
+ %(prog)s svg --intent flow --dimensions 720x960
1294
+ %(prog)s svg --intent grid --dimensions 720x960
1295
+ %(prog)s layout --elements hero,body,meta --dimensions 720x960 --style offset
1296
+ %(prog)s full --intent serenity --mode dark --dimensions 720x960 --output-dir ./assets/
1297
+ %(prog)s audit --css-file assets/palette.css
1298
+ """
1299
+ )
1300
+ sub = parser.add_subparsers(dest="command")
1301
+
1302
+ # palette
1303
+ p_pal = sub.add_parser("palette", help="Generate HSL-locked color palette")
1304
+ p_pal.add_argument("--intent", default="neutral", choices=list(INTENT_HUES.keys()))
1305
+ p_pal.add_argument("--mode", default="minimal", choices=["minimal", "dark", "pastel", "jewel", "light"])
1306
+ p_pal.add_argument("--harmony", default="auto", choices=["auto", "complementary", "split_complementary", "triadic", "analogous", "monochrome"])
1307
+ p_pal.add_argument("--seed", type=int, default=None)
1308
+ p_pal.add_argument("--format", default="css", choices=["css", "json"])
1309
+
1310
+ # svg
1311
+ p_svg = sub.add_parser("svg", help="Generate algorithmic SVG background")
1312
+ p_svg.add_argument("--svg-type", default="flow", choices=["flow", "grid", "noise", "supergraphic", "ordered_texture"])
1313
+ p_svg.add_argument("--dimensions", default="720x960")
1314
+ p_svg.add_argument("--color", default="#8a8a8a")
1315
+
1316
+ # layout
1317
+ p_lay = sub.add_parser("layout", help="Calculate element positions")
1318
+ p_lay.add_argument("--elements", default="hero,body,meta")
1319
+ p_lay.add_argument("--dimensions", default="720x960")
1320
+ p_lay.add_argument("--style", default="offset", choices=["offset", "centered", "overlap"])
1321
+
1322
+ # full
1323
+ p_full = sub.add_parser("full", help="Generate all assets at once")
1324
+ p_full.add_argument("--intent", default="neutral")
1325
+ p_full.add_argument("--mode", default="minimal", choices=["minimal", "dark", "pastel", "jewel", "light"])
1326
+ p_full.add_argument("--harmony", default="auto", choices=["auto", "complementary", "split_complementary", "triadic", "analogous", "monochrome"])
1327
+ p_full.add_argument("--svg-intent", default="flow", choices=["flow", "grid", "noise"])
1328
+ p_full.add_argument("--dimensions", default="720x960")
1329
+ p_full.add_argument("--elements", default="hero,body,meta")
1330
+ p_full.add_argument("--style", default="offset")
1331
+ p_full.add_argument("--seed", type=int, default=None)
1332
+ p_full.add_argument("--output-dir", default="./assets/")
1333
+
1334
+ # audit
1335
+ p_audit = sub.add_parser("audit", help="Audit a palette for constraint violations")
1336
+ p_audit.add_argument("--palette-json", required=True)
1337
+
1338
+ # palette-cascade
1339
+ p_pcas = sub.add_parser("palette-cascade", help="Generate role-based cascade palette (area ∝ 1/saturation)")
1340
+ p_pcas.add_argument("--intent", default="neutral", choices=list(INTENT_HUES.keys()))
1341
+ p_pcas.add_argument("--mode", default="minimal", choices=["minimal", "dark", "pastel", "jewel", "light"])
1342
+ p_pcas.add_argument("--harmony", default="auto", choices=["auto", "complementary", "split_complementary", "triadic", "analogous", "monochrome"])
1343
+ p_pcas.add_argument("--seed", type=int, default=None)
1344
+ p_pcas.add_argument("--format", default="summary", choices=["summary", "json", "css", "reportlab"])
1345
+
1346
+ # compile
1347
+ p_compile = sub.add_parser("compile", help="Compile a JSON Blueprint into a final HTML document")
1348
+ p_compile.add_argument("--blueprint", required=True, help="Path to the JSON blueprint generated by LLM")
1349
+ p_compile.add_argument("--output", default="poster.html", help="Path to save the output HTML")
1350
+
1351
+ # derive
1352
+ p_derive = sub.add_parser("derive", help="Auto-derive design intent from document description")
1353
+ p_derive.add_argument("text", help="Document title or description")
1354
+
1355
+ # Backward compat: positional command
1356
+ parser.add_argument("legacy_command", nargs="?")
1357
+ parser.add_argument("legacy_args", nargs="*")
1358
+
1359
+ args = parser.parse_args()
1360
+
1361
+ if args.command == "palette":
1362
+ pal = generate_color_palette(args.intent, args.mode, harmony=args.harmony, seed=args.seed)
1363
+ if args.format == "json":
1364
+ print(json.dumps(pal, indent=2))
1365
+ else:
1366
+ print(palette_to_css(pal))
1367
+
1368
+ elif args.command == "svg":
1369
+ w, h = map(int, args.dimensions.split("x"))
1370
+ print(generate_generative_svg(args.svg_type, w, h, args.color))
1371
+
1372
+ elif args.command == "layout":
1373
+ w, h = map(int, args.dimensions.split("x"))
1374
+ elements = [e.strip() for e in args.elements.split(",")]
1375
+ result = calculate_layout(elements, w, h, args.style)
1376
+ print(json.dumps(result, indent=2))
1377
+
1378
+ elif args.command == "full":
1379
+ w, h = map(int, args.dimensions.split("x"))
1380
+ os.makedirs(args.output_dir, exist_ok=True)
1381
+
1382
+ # 1. Palette
1383
+ pal = generate_color_palette(args.intent, args.mode, harmony=getattr(args, 'harmony', 'split_complementary'), seed=args.seed)
1384
+ css = palette_to_css(pal)
1385
+ css_path = os.path.join(args.output_dir, "palette.css")
1386
+ with open(css_path, "w") as f:
1387
+ f.write(css)
1388
+ json_path = os.path.join(args.output_dir, "palette.json")
1389
+ with open(json_path, "w") as f:
1390
+ json.dump(pal, f, indent=2)
1391
+ print(f"✅ {css_path}")
1392
+
1393
+ # 2. SVG
1394
+ svg_color = pal["accent"] # Use accent for SVG strokes
1395
+ svg = generate_generative_svg(args.svg_intent, w, h, svg_color)
1396
+ svg_path = os.path.join(args.output_dir, "background.svg")
1397
+ with open(svg_path, "w") as f:
1398
+ f.write(svg)
1399
+ print(f"✅ {svg_path}")
1400
+
1401
+ # 3. Layout
1402
+ elements = [e.strip() for e in args.elements.split(",")]
1403
+ lay = calculate_layout(elements, w, h, args.style)
1404
+ lay_path = os.path.join(args.output_dir, "layout.json")
1405
+ with open(lay_path, "w") as f:
1406
+ json.dump(lay, f, indent=2)
1407
+ print(f"✅ {lay_path}")
1408
+
1409
+ # 4. Audit
1410
+ violations = audit_palette(pal)
1411
+ if violations:
1412
+ print(f"\n⚠️ Palette violations:")
1413
+ for v in violations:
1414
+ print(f" - {v}")
1415
+ else:
1416
+ print(f"\n✅ Palette passes all constraints")
1417
+
1418
+ print(f"\n🎨 {args.intent}/{args.mode} | {w}×{h} | {len(elements)} elements")
1419
+
1420
+ elif args.command == "audit":
1421
+ with open(args.palette_json) as f:
1422
+ pal = json.load(f)
1423
+ violations = audit_palette(pal)
1424
+ if violations:
1425
+ print("⚠️ Violations found:")
1426
+ for v in violations:
1427
+ print(f" - {v}")
1428
+ sys.exit(1)
1429
+ else:
1430
+ print("✅ Palette passes all constraints")
1431
+
1432
+ elif args.command == "derive":
1433
+ intent = derive_intent(args.text)
1434
+ print(f"Intent: {intent}")
1435
+ print(f"Hue: {INTENT_HUES.get(intent, 45)}°")
1436
+ # Also generate a quick palette preview
1437
+ pal = generate_color_palette(intent, "dark")
1438
+ print(f"Preview (dark): bg={pal['bg']} accent={pal['accent']}")
1439
+ pal_light = generate_color_palette(intent, "light")
1440
+ print(f"Preview (light): bg={pal_light['bg']} accent={pal_light['accent']}")
1441
+
1442
+ elif args.command == "palette-cascade":
1443
+ cascade = generate_cascade_palette(args.intent, args.mode, harmony=args.harmony, seed=args.seed)
1444
+ if args.format == "json":
1445
+ print(json.dumps(cascade, indent=2, ensure_ascii=False, default=str))
1446
+ elif args.format == "css":
1447
+ print(cascade["css"])
1448
+ elif args.format == "reportlab":
1449
+ print(cascade["reportlab"])
1450
+ else: # summary
1451
+ meta = cascade["meta"]
1452
+ print(f"🎨 Cascade Palette | Intent: {meta['intent']} | Mode: {meta['mode']} | Harmony: {meta['harmony']}")
1453
+ print(f" Base hue: {meta['base_hue']}° | Accent hue: {meta['accent_hue']}° | Secondary hue: {meta['secondary_hue']}°")
1454
+ print(f" Contrast: text:bg={meta['contrast']['text_on_bg']} | accent:bg={meta['contrast']['accent_on_bg']}")
1455
+ print()
1456
+ print(" TIER | ROLE | HEX | S | USAGE")
1457
+ print(" ────── | ────────────────── | ─────── | ────── | ────────────")
1458
+ for name, info in cascade["roles"].items():
1459
+ tier = info['tier'].upper().ljust(6)
1460
+ nm = name.ljust(18)
1461
+ hx = info['hex'].ljust(7)
1462
+ s_val = f"{info['hsl'][1]:.3f}".ljust(6)
1463
+ print(f" {tier} | {nm} | {hx} | {s_val} | {info['usage']}")
1464
+ print()
1465
+ print(" Semantic:")
1466
+ for name, info in cascade["semantic"].items():
1467
+ print(f" {name}: {info['hex']} (S={info['hsl'][1]:.3f})")
1468
+ if meta["audit"]:
1469
+ print(f"\n ⚠️ Violations:")
1470
+ for v in meta["audit"]:
1471
+ print(f" - {v}")
1472
+ else:
1473
+ print(f"\n ✅ All tier constraints pass")
1474
+
1475
+ elif args.command == "compile":
1476
+ try:
1477
+ out_path, pal = compile_blueprint(args.blueprint, args.output)
1478
+ print(f"✅ Blueprint compiled successfully to: {out_path}")
1479
+ violations = audit_palette(pal)
1480
+ if violations:
1481
+ print(f"⚠️ Warning: Generated palette had minor violations (auto-corrected by engine):")
1482
+ for v in violations: print(f" - {v}")
1483
+
1484
+ except Exception as e:
1485
+ print(f"❌ Failed to compile blueprint: {str(e)}")
1486
+ sys.exit(1)
1487
+ else:
1488
+ parser.print_help()
1489
+
1490
+
1491
+ # ═══════════════════════════════════════════════════════════════════════
1492
+ # 4. BLUEPRINT COMPILER — Converting JSON Intent to HTML Canvas
1493
+ # ═══════════════════════════════════════════════════════════════════════
1494
+ import re
1495
+
1496
+ # Base CSS that enforces the "Axioms" from visual_framework.md
1497
+ BASE_CSS = """
1498
+ @page {
1499
+ size: var(--canvas-w, 720px) var(--canvas-h, 960px);
1500
+ margin: 0;
1501
+ }
1502
+ :root {
1503
+ --font-sans: 'Inter', 'Noto Sans SC', 'Helvetica Neue', 'Apple Color Emoji', 'Segoe UI Emoji', sans-serif;
1504
+ --font-serif: 'Playfair Display', 'Noto Serif SC', 'Cormorant Garamond', 'Apple Color Emoji', serif;
1505
+ --font-mono: 'SF Mono', 'Consolas', 'Apple Color Emoji', monospace;
1506
+
1507
+ /* Typographic Scale — 6-level fluid type system (Modular Scale) */
1508
+ --text-scale-6: clamp(64px, 12vw, 150px); /* Hero / Display — oversized, single word or short phrase */
1509
+ --text-scale-5: clamp(48px, 8vw, 96px); /* Primary Title — poster headline */
1510
+ --text-scale-4: clamp(32px, 5vw, 56px); /* Subheadline — chapter opener or key quote */
1511
+ --text-scale-3: clamp(20px, 3vw, 32px); /* Lead Paragraph — slightly larger than body */
1512
+ --text-scale-2: 16px; /* Body — standard body text */
1513
+ --text-scale-1: 12px; /* Meta / Caption — minimum readable size */
1514
+ }
1515
+ html, body {
1516
+ margin: 0; padding: 0;
1517
+ background: var(--c-bg);
1518
+ color: var(--c-text);
1519
+ font-family: var(--font-sans);
1520
+ -webkit-font-smoothing: antialiased;
1521
+ }
1522
+ /* Browser preview: scale poster to fit viewport & center on matching background */
1523
+ @media screen {
1524
+ html {
1525
+ height: auto;
1526
+ display: flex;
1527
+ justify-content: center;
1528
+ align-items: flex-start;
1529
+ min-height: 100vh;
1530
+ background: var(--c-bg);
1531
+ }
1532
+ body {
1533
+ transform-origin: top center;
1534
+ margin: 0 auto;
1535
+ box-shadow: 0 0 60px rgba(0,0,0,0.3);
1536
+ /* scale injected by override_css with concrete canvas dimensions */
1537
+ }
1538
+ }
1539
+ .canvas {
1540
+ width: var(--canvas-w, 720px);
1541
+ min-height: var(--canvas-h, 960px);
1542
+ position: relative;
1543
+ overflow: hidden;
1544
+ box-sizing: border-box;
1545
+ page-break-after: always;
1546
+ }
1547
+ /* ═══ Continuous Canvas Mode (multi-page as one seamless surface) ═══ */
1548
+ .continuous-canvas {
1549
+ width: var(--canvas-w, 720px);
1550
+ position: relative;
1551
+ overflow: hidden;
1552
+ box-sizing: border-box;
1553
+ /* height is set inline: canvas_h * total_pages */
1554
+ }
1555
+ .continuous-canvas .bg-layer-full {
1556
+ position: absolute;
1557
+ inset: 0;
1558
+ z-index: 1;
1559
+ pointer-events: none;
1560
+ }
1561
+ .continuous-canvas .bg-layer-full svg {
1562
+ width: 100%;
1563
+ height: 100%;
1564
+ }
1565
+ .continuous-canvas .page-section {
1566
+ position: absolute;
1567
+ left: 0;
1568
+ width: 100%;
1569
+ box-sizing: border-box;
1570
+ overflow: visible;
1571
+ /* top and height set inline per page */
1572
+ }
1573
+ .continuous-canvas .page-section .safe-zone {
1574
+ position: absolute;
1575
+ inset: 10% 12%;
1576
+ display: grid;
1577
+ grid-template-columns: repeat(12, 1fr);
1578
+ grid-template-rows: repeat(12, minmax(0, auto));
1579
+ align-content: start;
1580
+ }
1581
+ .continuous-canvas .page-section .page-ghost {
1582
+ position: absolute;
1583
+ bottom: -5%;
1584
+ right: 5%;
1585
+ font-size: 240px;
1586
+ font-weight: 900;
1587
+ color: var(--c-mid);
1588
+ opacity: 0.05;
1589
+ pointer-events: none;
1590
+ z-index: 0;
1591
+ }
1592
+ /* 12% Breathing Margin Enforcer (balanced: enough air without wasting space) */
1593
+ .safe-zone {
1594
+ position: absolute;
1595
+ inset: 10% 12%;
1596
+ display: grid;
1597
+ grid-template-columns: repeat(12, 1fr);
1598
+ grid-template-rows: repeat(12, minmax(0, auto));
1599
+ align-content: start;
1600
+ /* gap is injected dynamically by compile_blueprint via inline style */
1601
+ }
1602
+ /* Grid-item wrapper — every component gets one */
1603
+ .grid-item {
1604
+ display: flex;
1605
+ min-width: 0;
1606
+ min-height: 0;
1607
+ overflow: visible;
1608
+ }
1609
+ /* Global content-overflow protection — prevents ANY text/block from breaking out of its container */
1610
+ .grid-item * {
1611
+ max-width: 100%;
1612
+ box-sizing: border-box;
1613
+ }
1614
+ .grid-item p, .grid-item li, .grid-item span, .grid-item h1, .grid-item h2, .grid-item h3, .grid-item h4, .grid-item td, .grid-item th, .grid-item div {
1615
+ overflow-wrap: break-word;
1616
+ word-break: break-word;
1617
+ }
1618
+ /* CJK-safe text wrapping: prefer keeping CJK word groups intact, but allow break when necessary */
1619
+ .hero-type, .hero-sub, .glass-canvas, .shaped-content, .stat-label, .delta-metric, .delta-label {
1620
+ text-wrap: balance;
1621
+ overflow-wrap: break-word;
1622
+ word-break: normal;
1623
+ line-break: strict;
1624
+ }
1625
+
1626
+ /* ═══ Micro-Typography: Computational Typesetting ═══ */
1627
+ p, .glass-canvas, .shaped-content, li {
1628
+ /* Algorithmic justification — eliminates white rivers between words */
1629
+ text-align: justify;
1630
+ hyphens: auto;
1631
+ word-spacing: -0.05em;
1632
+ /* Hanging punctuation — visually aligned optical edges */
1633
+ hanging-punctuation: first last;
1634
+ /* Kill orphans & widows — force min 3 lines carried across page breaks */
1635
+ orphans: 3;
1636
+ widows: 3;
1637
+ }
1638
+ .grid-item table {
1639
+ width: 100%;
1640
+ table-layout: fixed;
1641
+ overflow: hidden;
1642
+ }
1643
+ .grid-item img {
1644
+ max-width: 100%;
1645
+ height: auto;
1646
+ }
1647
+
1648
+ /* --- Archetype Layouts --- */
1649
+ /* All archetypes share the 12×12 grid via .safe-zone.
1650
+ Archetype classes may override alignment defaults on the canvas level. */
1651
+ .archetype-cover_hero .safe-zone {
1652
+ align-content: start;
1653
+ inset: 12% 14%;
1654
+ }
1655
+ /* Cover hero typography scale: larger text for covers */
1656
+ .archetype-cover_hero .hero-type {
1657
+ font-size: clamp(42px, 8vw, 72px);
1658
+ line-height: 1.15;
1659
+ }
1660
+ .archetype-cover_hero .hero-sub {
1661
+ font-size: clamp(22px, 4vw, 32px);
1662
+ line-height: 1.3;
1663
+ opacity: 0.85;
1664
+ }
1665
+ .archetype-cover_hero .floating-meta {
1666
+ font-size: clamp(16px, 2.5vw, 22px);
1667
+ }
1668
+ .archetype-split_vertical { display: grid; grid-template-columns: 1fr 1fr; min-height: 960px; }
1669
+ .archetype-split_vertical .safe-zone { position: relative; inset: auto; padding: 10%; display: grid; grid-template-columns: repeat(12, 1fr); grid-template-rows: repeat(12, 1fr); align-content: center; }
1670
+ .archetype-split_vertical.single-column { grid-template-columns: 1fr; }
1671
+ .archetype-editorial_flow .safe-zone { align-content: center; }
1672
+ .archetype-scattered_canvas .safe-zone { /* same 12×12 grid — scattered effect via grid_area placement */ }
1673
+ .archetype-data_dashboard .safe-zone { /* same 12×12 grid — dashboard tiles via grid_area placement */ }
1674
+ .archetype-shaped_editorial .safe-zone { align-content: center; }
1675
+
1676
+ /* Continuous canvas archetype overrides (page-section inherits archetype class) */
1677
+ .continuous-canvas .page-section.archetype-cover_hero .safe-zone { align-content: start; inset: 12% 14%; }
1678
+ .continuous-canvas .page-section.archetype-cover_hero .hero-type { font-size: clamp(42px, 8vw, 72px); line-height: 1.15; }
1679
+ .continuous-canvas .page-section.archetype-cover_hero .hero-sub { font-size: clamp(22px, 4vw, 32px); line-height: 1.3; opacity: 0.85; }
1680
+ .continuous-canvas .page-section.archetype-cover_hero .floating-meta { font-size: clamp(16px, 2.5vw, 22px); }
1681
+ .continuous-canvas .page-section.archetype-editorial_flow .safe-zone { align-content: center; }
1682
+ .continuous-canvas .page-section.archetype-shaped_editorial .safe-zone { align-content: center; inset: 5% 6%; }
1683
+
1684
+ /* --- Components --- */
1685
+ .hero-type {
1686
+ font-size: clamp(48px, 10vw, 110px);
1687
+ line-height: 0.88;
1688
+ letter-spacing: -0.03em;
1689
+ margin: 0;
1690
+ overflow-wrap: break-word;
1691
+ word-break: break-word;
1692
+ position: relative;
1693
+ z-index: 10;
1694
+ }
1695
+ .hero-type.weight-black { font-weight: 900; }
1696
+ .hero-type.weight-thin { font-weight: 100; letter-spacing: 0.05em; font-family: var(--font-serif); }
1697
+ .hero-sub {
1698
+ margin: 8px 0 0 0;
1699
+ font-size: var(--text-scale-2);
1700
+ line-height: 1.3;
1701
+ opacity: 0.8;
1702
+ }
1703
+ /* Hero container needs vertical stacking */
1704
+ .grid-item:has(.hero-type) {
1705
+ flex-direction: column;
1706
+ justify-content: center;
1707
+ }
1708
+ .hero-type, .hero-sub {
1709
+ width: 100%;
1710
+ }
1711
+ .hero-type {
1712
+ color: var(--c-text);
1713
+ }
1714
+
1715
+ .glass-canvas {
1716
+ background: var(--c-surface);
1717
+ border: 1px solid rgba(128, 128, 128, 0.08);
1718
+ border-radius: 2px;
1719
+ padding: 36px;
1720
+ font-size: 16px;
1721
+ line-height: 1.6;
1722
+ z-index: 5;
1723
+ position: relative;
1724
+ overflow-wrap: break-word;
1725
+ word-break: break-word;
1726
+ }
1727
+
1728
+ .floating-meta {
1729
+ display: flex;
1730
+ flex-direction: column;
1731
+ font-size: 12px;
1732
+ font-family: var(--font-mono);
1733
+ letter-spacing: 0.1em;
1734
+ color: var(--c-muted);
1735
+ opacity: 0.6;
1736
+ z-index: 20;
1737
+ overflow: hidden;
1738
+ text-overflow: ellipsis;
1739
+ /* Positioned via grid_area in .grid-item wrapper — no absolute needed */
1740
+ }
1741
+ /* Legacy position helpers (kept for backwards compat with old blueprints) */
1742
+ .pos-top-left { align-self: start; justify-self: start; }
1743
+ .pos-top-right { align-self: start; justify-self: end; text-align: right; }
1744
+ .pos-bottom-left { align-self: end; justify-self: start; }
1745
+ .pos-bottom-right { align-self: end; justify-self: end; text-align: right; }
1746
+
1747
+ .stat-block { display: flex; flex-direction: column; margin-bottom: 24px; }
1748
+ .stat-num { font-size: clamp(32px, 5vw, 56px); font-weight: 900; line-height: 0.9; color: var(--c-text); }
1749
+ .stat-unit { font-size: clamp(14px, 2vw, 20px); font-weight: 300; color: var(--c-muted); margin-left: 4px; display: inline;}
1750
+ .stat-label { font-size: 12px; letter-spacing: 0.15em; color: var(--c-accent); margin-top: 8px; text-transform: uppercase; }
1751
+
1752
+ .hairline { border: none; border-top: 0.5px solid var(--c-muted); opacity: 0.3; margin: 8px 0; width: 100%; }
1753
+ .hairline.style-accent { border-top-color: var(--c-accent); width: 30%; margin-left: 0; opacity: 0.8;}
1754
+
1755
+ .page-ghost {
1756
+ position: absolute; bottom: -5%; right: 5%;
1757
+ font-size: 240px; font-weight: 900; color: var(--c-mid);
1758
+ opacity: 0.05; pointer-events: none; z-index: 0;
1759
+ }
1760
+
1761
+ .bg-layer { position: absolute; inset: 0; z-index: 1; pointer-events: none; }
1762
+ .bg-layer svg { width: 100%; height: 100%; }
1763
+
1764
+ /* --- Shaped_Canvas (Semantic Shape-Wrapping) --- */
1765
+ .shaped-canvas {
1766
+ position: relative;
1767
+ padding: 24px;
1768
+ font-size: 16px;
1769
+ line-height: 1.7;
1770
+ z-index: 5;
1771
+ overflow-wrap: break-word;
1772
+ word-break: break-word;
1773
+ }
1774
+ .shape-float {
1775
+ float: left;
1776
+ margin: 0;
1777
+ padding: 0;
1778
+ }
1779
+ .shape-circle { shape-outside: circle(45% at 50% 50%); width: 40%; height: 90%; }
1780
+ .shape-wave { shape-outside: polygon(0 0, 80% 0, 60% 25%, 80% 50%, 60% 75%, 80% 100%, 0 100%); width: 45%; height: 100%; }
1781
+ .shape-diagonal_slash { shape-outside: polygon(0 0, 100% 0, 0 100%); width: 50%; height: 100%; }
1782
+ .shape-diamond { shape-outside: polygon(50% 0, 100% 50%, 50% 100%, 0 50%); width: 45%; height: 90%; }
1783
+ .shape-wedge_right { shape-outside: polygon(0 0, 60% 0, 100% 50%, 60% 100%, 0 100%); width: 50%; height: 100%; }
1784
+
1785
+ /* --- Archetype: shaped_editorial --- */
1786
+ .archetype-shaped_editorial .safe-zone {
1787
+ inset: 5% 6%;
1788
+ /* Inherits 12×12 grid from .safe-zone */
1789
+ align-content: center;
1790
+ }
1791
+
1792
+ /* ═══ Tufte Marginalia System ═══ */
1793
+ /* 30% sidenote rail for report/long-form archetypes */
1794
+ .archetype-tufte_report .safe-zone {
1795
+ display: grid;
1796
+ grid-template-columns: 1fr 280px;
1797
+ gap: 40px;
1798
+ align-content: start;
1799
+ }
1800
+ .archetype-tufte_report .main-column {
1801
+ display: grid;
1802
+ grid-template-columns: repeat(12, 1fr);
1803
+ grid-template-rows: repeat(12, 1fr);
1804
+ gap: inherit;
1805
+ }
1806
+ .archetype-tufte_report .side-rail {
1807
+ display: flex;
1808
+ flex-direction: column;
1809
+ gap: 24px;
1810
+ padding-top: 8px;
1811
+ }
1812
+ .sidenote {
1813
+ font-size: 13px;
1814
+ line-height: 1.5;
1815
+ color: var(--c-muted);
1816
+ border-left: 2px solid var(--c-accent);
1817
+ padding-left: 12px;
1818
+ opacity: 0.85;
1819
+ }
1820
+ .sidenote .sidenote-label {
1821
+ font-weight: 700;
1822
+ font-size: 12px;
1823
+ text-transform: uppercase;
1824
+ letter-spacing: 0.08em;
1825
+ color: var(--c-accent);
1826
+ display: block;
1827
+ margin-bottom: 4px;
1828
+ }
1829
+
1830
+ /* ═══ Delta Widget — Data-to-Ink Ratio Component ═══ */
1831
+ .delta-widget {
1832
+ text-align: center;
1833
+ padding: 16px 12px;
1834
+ }
1835
+ .delta-widget .delta-metric {
1836
+ font-size: 12px;
1837
+ font-weight: 600;
1838
+ text-transform: uppercase;
1839
+ letter-spacing: 0.1em;
1840
+ color: var(--c-muted);
1841
+ margin-bottom: 4px;
1842
+ }
1843
+ .delta-widget .delta-value {
1844
+ font-size: 36px;
1845
+ font-weight: 900;
1846
+ color: var(--c-text);
1847
+ line-height: 1.1;
1848
+ }
1849
+ .delta-widget .delta-change {
1850
+ font-size: 14px;
1851
+ font-weight: 700;
1852
+ margin-top: 4px;
1853
+ }
1854
+ .delta-widget .delta-label {
1855
+ font-size: 12px;
1856
+ color: var(--c-muted);
1857
+ margin-top: 8px;
1858
+ }
1859
+
1860
+ /* ═══ Polymorphic Process_List — Container Query Adaptive ═══ */
1861
+ .process-list-container {
1862
+ container-type: inline-size;
1863
+ width: 100%;
1864
+ min-height: 100%;
1865
+ }
1866
+ /* Wide: horizontal timeline */
1867
+ .process-list {
1868
+ display: flex;
1869
+ flex-direction: row;
1870
+ align-items: flex-start;
1871
+ gap: 8px;
1872
+ list-style: none;
1873
+ padding: 0;
1874
+ margin: 0;
1875
+ min-height: 100%;
1876
+ }
1877
+ .process-list .process-step {
1878
+ flex: 1;
1879
+ display: flex;
1880
+ flex-direction: column;
1881
+ align-items: center;
1882
+ text-align: center;
1883
+ position: relative;
1884
+ padding: 12px 4px;
1885
+ }
1886
+ .process-step .step-num {
1887
+ width: 32px; height: 32px; border-radius: 50%;
1888
+ background: var(--c-accent); color: #fff;
1889
+ display: flex; align-items: center; justify-content: center;
1890
+ font-weight: 800; font-size: 14px; margin-bottom: 8px;
1891
+ flex-shrink: 0;
1892
+ }
1893
+ .process-step .step-title { font-weight: 700; font-size: 13px; color: var(--c-text); }
1894
+ .process-step .step-desc { font-size: 12px; color: var(--c-muted); margin-top: 4px; line-height: 1.4; }
1895
+ /* Connector line between horizontal steps */
1896
+ .process-step:not(:last-child)::after {
1897
+ content: ''; position: absolute; top: 28px; right: -6px;
1898
+ width: 12px; height: 2px; background: var(--c-accent); opacity: 0.5;
1899
+ }
1900
+ /* Narrow: vertical numbered list */
1901
+ @container (max-width: 360px) {
1902
+ .process-list {
1903
+ flex-direction: column;
1904
+ gap: 12px;
1905
+ }
1906
+ .process-list .process-step {
1907
+ flex-direction: row;
1908
+ text-align: left;
1909
+ align-items: flex-start;
1910
+ gap: 12px;
1911
+ padding: 4px 0;
1912
+ }
1913
+ .process-step .step-num { margin-bottom: 0; }
1914
+ .process-step:not(:last-child)::after { display: none; }
1915
+ }
1916
+ """
1917
+
1918
+
1919
+ def _prevent_orphan_chars(text):
1920
+ """
1921
+ Prevent orphan characters at end of paragraphs.
1922
+ Replace the last space/breakable point between the final two CJK chars
1923
+ (or words) with &nbsp; so the browser never wraps a single trailing char
1924
+ onto its own line.
1925
+ """
1926
+ # CJK orphan: bind last two CJK characters with a zero-width no-break joiner
1927
+ # Match: (CJK char)(optional space)(CJK char) at end of string (before tags)
1928
+ text = re.sub(r'([\u4e00-\u9fff\u3400-\u4dbf])[\s]+([\u4e00-\u9fff\u3400-\u4dbf])(?=\s*(?:<[^>]*>)*\s*$)', '\\g<1>\u2060\\g<2>', text)
1929
+ # Latin orphan: bind last two words
1930
+ text = re.sub(r'(\S+)\s+(\S+)\s*$', r'\1&nbsp;\2', text)
1931
+ return text
1932
+
1933
+
1934
+ def simple_markdown_to_html(md_text):
1935
+ """Lightweight markdown → HTML for Glass Canvas. Handles paragraphs, headers, bold, italic, lists, and inline code."""
1936
+ if not md_text:
1937
+ return ""
1938
+
1939
+ lines = md_text.split('\n')
1940
+ html_parts = []
1941
+ in_list = False
1942
+ paragraph_buffer = []
1943
+
1944
+ def flush_paragraph():
1945
+ nonlocal paragraph_buffer
1946
+ if paragraph_buffer:
1947
+ text = ' '.join(paragraph_buffer)
1948
+ # Apply inline formatting
1949
+ text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', text)
1950
+ text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', text)
1951
+ text = re.sub(r'`(.*?)`', r'<code style="background:var(--c-surface);padding:2px 6px;border-radius:3px;font-size:max(12px, 0.9em)">\1</code>', text)
1952
+ # Anti-orphan: prevent single trailing character on last line
1953
+ text = _prevent_orphan_chars(text)
1954
+ html_parts.append(f'<p style="margin:0 0 12px 0;line-height:1.7">{text}</p>')
1955
+ paragraph_buffer = []
1956
+
1957
+ def apply_inline(text):
1958
+ """Apply bold, italic, inline code."""
1959
+ text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', text)
1960
+ text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', text)
1961
+ text = re.sub(r'`(.*?)`', r'<code style="background:var(--c-surface);padding:2px 6px;border-radius:3px;font-size:max(12px, 0.9em)">\1</code>', text)
1962
+ return text
1963
+
1964
+ for line in lines:
1965
+ stripped = line.strip()
1966
+
1967
+ # Empty line — flush paragraph
1968
+ if not stripped:
1969
+ flush_paragraph()
1970
+ if in_list:
1971
+ html_parts.append('</ul>')
1972
+ in_list = False
1973
+ continue
1974
+
1975
+ # Headers
1976
+ if stripped.startswith('### '):
1977
+ flush_paragraph()
1978
+ if in_list:
1979
+ html_parts.append('</ul>')
1980
+ in_list = False
1981
+ html_parts.append(f'<h3 style="font-size:16px;font-weight:700;margin:20px 0 8px 0;color:var(--c-accent);text-transform:uppercase;letter-spacing:0.05em;">{apply_inline(stripped[4:])}</h3>')
1982
+ continue
1983
+ if stripped.startswith('## '):
1984
+ flush_paragraph()
1985
+ if in_list:
1986
+ html_parts.append('</ul>')
1987
+ in_list = False
1988
+ html_parts.append(f'<h2 style="font-size:20px;font-weight:700;margin:24px 0 12px 0;color:var(--c-text)">{apply_inline(stripped[3:])}</h2>')
1989
+ continue
1990
+ if stripped.startswith('# '):
1991
+ flush_paragraph()
1992
+ if in_list:
1993
+ html_parts.append('</ul>')
1994
+ in_list = False
1995
+ html_parts.append(f'<h1 style="font-size:24px;font-weight:800;margin:28px 0 14px 0;color:var(--c-text)">{apply_inline(stripped[2:])}</h1>')
1996
+ continue
1997
+
1998
+ # List items (- or *)
1999
+ list_match = re.match(r'^[-*]\s+(.*)', stripped)
2000
+ if list_match:
2001
+ flush_paragraph()
2002
+ if not in_list:
2003
+ html_parts.append('<ul style="margin:8px 0;padding-left:20px;list-style-type:disc">')
2004
+ in_list = True
2005
+ html_parts.append(f'<li style="margin:4px 0;line-height:1.6">{apply_inline(list_match.group(1))}</li>')
2006
+ continue
2007
+
2008
+ # Numbered list items
2009
+ num_match = re.match(r'^(\d+)[.)]\s+(.*)', stripped)
2010
+ if num_match:
2011
+ flush_paragraph()
2012
+ if in_list:
2013
+ html_parts.append('</ul>')
2014
+ in_list = False
2015
+ html_parts.append(f'<p style="margin:4px 0 4px 20px;line-height:1.6"><strong>{num_match.group(1)}.</strong> {apply_inline(num_match.group(2))}</p>')
2016
+ continue
2017
+
2018
+ # Normal text — accumulate into paragraph
2019
+ paragraph_buffer.append(stripped)
2020
+
2021
+ # Flush remaining
2022
+ flush_paragraph()
2023
+ if in_list:
2024
+ html_parts.append('</ul>')
2025
+
2026
+ return '\n'.join(html_parts)
2027
+
2028
+
2029
+ def _parse_grid_area(comp):
2030
+ """
2031
+ Parse grid_area from component JSON.
2032
+ Accepts two formats:
2033
+ - Array: [row_start, col_start, row_end, col_end] — 1-based, max 13.
2034
+ - String: "row_start / col_start / row_end / col_end" — 1-based, max 13.
2035
+ Returns CSS grid-area string or None.
2036
+ """
2037
+ ga = comp.get("grid_area", None)
2038
+ if ga is None:
2039
+ return None
2040
+ # Array format: [1, 1, 3, 5]
2041
+ if isinstance(ga, list) and len(ga) == 4:
2042
+ rs, cs, re, ce = [max(1, min(13, int(v))) for v in ga]
2043
+ # Fix zero-height/zero-width grid areas (row_end must be > row_start)
2044
+ if re <= rs:
2045
+ re = min(13, rs + 1)
2046
+ if ce <= cs:
2047
+ ce = min(13, cs + 1)
2048
+ return f"{rs} / {cs} / {re} / {ce}"
2049
+ # String format: "1 / 1 / 3 / 5"
2050
+ if isinstance(ga, str) and "/" in ga:
2051
+ parts = [p.strip() for p in ga.split("/")]
2052
+ if len(parts) == 4:
2053
+ try:
2054
+ rs, cs, re, ce = [max(1, min(13, int(p))) for p in parts]
2055
+ # Fix zero-height/zero-width grid areas
2056
+ if re <= rs:
2057
+ re = min(13, rs + 1)
2058
+ if ce <= cs:
2059
+ ce = min(13, cs + 1)
2060
+ return f"{rs} / {cs} / {re} / {ce}"
2061
+ except ValueError:
2062
+ pass
2063
+ return None
2064
+
2065
+
2066
+ def _parse_align(comp):
2067
+ """
2068
+ Parse align from component JSON.
2069
+ Format: "vertical / horizontal" where each is start|center|end.
2070
+ Returns (align-items, justify-content) tuple.
2071
+ """
2072
+ align = comp.get("align", "start / start")
2073
+ if "/" in str(align):
2074
+ parts = [p.strip() for p in str(align).split("/")]
2075
+ v = parts[0] if parts[0] in ("start", "center", "end") else "start"
2076
+ h = parts[1] if len(parts) > 1 and parts[1] in ("start", "center", "end") else "start"
2077
+ else:
2078
+ v, h = "start", "start"
2079
+ return v, h
2080
+
2081
+
2082
+ def _estimate_content_weight(comp):
2083
+ """
2084
+ Estimate the visual weight (space needed) of a component based on its content.
2085
+ Returns a numeric weight proportional to how many grid rows it should occupy.
2086
+
2087
+ Text-heavy components (Glass_Canvas, Shaped_Canvas) get weight proportional to
2088
+ character count. Fixed-height components (Stat_Block, Hero_Typography, etc.) get
2089
+ a small fixed weight since they don't grow with content.
2090
+ """
2091
+ ctype = comp.get("type", "")
2092
+
2093
+ # Fixed-height components: their visual size is independent of text length
2094
+ FIXED_WEIGHTS = {
2095
+ "Hero_Typography": 2.5,
2096
+ "Stat_Block": 2.0,
2097
+ "Delta_Widget": 2.0,
2098
+ "Hairline_Divider": 1.0,
2099
+ "Floating_Meta": 1.0, # usually positioned in corners, but fallback
2100
+ "Image_Asset": 3.0,
2101
+ }
2102
+ if ctype in FIXED_WEIGHTS:
2103
+ return FIXED_WEIGHTS[ctype]
2104
+
2105
+ # Text-heavy components: weight scales with content length
2106
+ text = comp.get("markdown_content", "") or comp.get("body", "") or ""
2107
+
2108
+ # Also count sub-items (Process_List steps)
2109
+ for step in comp.get("steps", []):
2110
+ text += step.get("title", "") + step.get("description", "")
2111
+
2112
+ char_count = len(text)
2113
+
2114
+ if ctype in ("Glass_Canvas", "Shaped_Canvas", "Process_List"):
2115
+ # Rough estimate: ~40 CJK chars per line at 16px in a ~500px wide container,
2116
+ # ~1.6 line-height, so each 40 chars ≈ 1 visual line ≈ ~25px.
2117
+ # Grid row on a 960px canvas ≈ 80px each (960/12).
2118
+ # So 40 chars ≈ 0.3 grid rows. But Glass_Canvas has padding (~72px total),
2119
+ # headings, list spacing, etc. Add base weight for the container itself.
2120
+ base = 2.0 # minimum for padding + heading
2121
+ text_rows = char_count / 120.0 # ~120 chars per grid-row worth of space
2122
+ return base + text_rows
2123
+
2124
+ # Unknown component type: estimate from text length with a reasonable default
2125
+ if char_count > 0:
2126
+ return 2.0 + char_count / 120.0
2127
+ return 2.0
2128
+
2129
+
2130
+ def _assign_floating_meta(comp):
2131
+ """Assign grid_area to a Floating_Meta component based on its position."""
2132
+ pos = comp.get("position", "top-right")
2133
+ if "top" in pos and "left" in pos:
2134
+ comp["grid_area"] = "1 / 1 / 2 / 7"
2135
+ elif "top" in pos:
2136
+ comp["grid_area"] = "1 / 7 / 2 / 13"
2137
+ elif "bottom" in pos and "left" in pos:
2138
+ comp["grid_area"] = "12 / 1 / 13 / 7"
2139
+ else:
2140
+ comp["grid_area"] = "12 / 7 / 13 / 13"
2141
+
2142
+
2143
+ def _distribute_rows_by_weight(content_comps, start_row=1, end_row=13, full_width=True):
2144
+ """
2145
+ Distribute grid rows among content components proportionally to their content weight.
2146
+ Each component gets at least 2 rows. Components fill start_row to end_row seamlessly.
2147
+ """
2148
+ nn = len(content_comps)
2149
+ if nn == 0:
2150
+ return
2151
+
2152
+ total_rows = end_row - start_row # available rows
2153
+
2154
+ # Calculate weights
2155
+ weights = [_estimate_content_weight(c) for c in content_comps]
2156
+ total_weight = sum(weights)
2157
+
2158
+ if total_weight == 0:
2159
+ total_weight = nn # fallback: equal distribution
2160
+ weights = [1.0] * nn
2161
+
2162
+ # Allocate rows proportionally, with minimum 2 per component
2163
+ MIN_ROWS = 2
2164
+ raw_rows = [(w / total_weight) * total_rows for w in weights]
2165
+
2166
+ # Ensure minimum, then redistribute excess
2167
+ allocated = []
2168
+ for r in raw_rows:
2169
+ allocated.append(max(MIN_ROWS, round(r)))
2170
+
2171
+ # Adjust total to exactly fill the available rows
2172
+ # First pass: if total exceeds available, shrink the largest allocations
2173
+ while sum(allocated) > total_rows and any(a > MIN_ROWS for a in allocated):
2174
+ max_idx = max(range(nn), key=lambda i: allocated[i])
2175
+ allocated[max_idx] -= 1
2176
+
2177
+ # Second pass: if total is less than available, grow the heaviest components
2178
+ while sum(allocated) < total_rows:
2179
+ max_weight_idx = max(range(nn), key=lambda i: weights[i])
2180
+ allocated[max_weight_idx] += 1
2181
+
2182
+ # Assign grid_area
2183
+ col_start = 1
2184
+ col_end = 13 if full_width else 7 # can be overridden by caller
2185
+ current_row = start_row
2186
+ for j, comp in enumerate(content_comps):
2187
+ rs = current_row
2188
+ re = min(end_row, current_row + allocated[j])
2189
+ comp["grid_area"] = f"{rs} / {col_start} / {re} / {col_end}"
2190
+ current_row = re
2191
+
2192
+
2193
+ def _auto_assign_grid_areas(archetype, components):
2194
+ """
2195
+ Auto-assign grid_area to components that don't have one,
2196
+ based on the archetype and number of components.
2197
+ Mutates components in-place.
2198
+ Skips Page_Ghost_Number (uses absolute positioning, not grid).
2199
+
2200
+ Uses content-aware row distribution: text-heavy components (Glass_Canvas)
2201
+ get more rows than fixed-height components (Stat_Block, Hero_Typography).
2202
+ """
2203
+ # Filter out ghost numbers — they use absolute positioning, not grid
2204
+ gridded = [c for c in components if c.get("type") != "Page_Ghost_Number"]
2205
+
2206
+ # Only process components without grid_area
2207
+ needs_area = [c for c in gridded if not c.get("grid_area")]
2208
+ if not needs_area:
2209
+ return # All components already have grid_area
2210
+
2211
+ n = len(gridded)
2212
+
2213
+ if archetype == "cover_hero":
2214
+ # Cover: stack vertically, full width, spread across page
2215
+ # Typical: 2-4 components (Hero + Floating_Meta + optional divider/ghost)
2216
+ if n <= 2:
2217
+ slots = ["1 / 1 / 7 / 13", "9 / 1 / 13 / 13"]
2218
+ elif n == 3:
2219
+ slots = ["1 / 1 / 5 / 13", "5 / 1 / 9 / 13", "10 / 1 / 13 / 13"]
2220
+ else:
2221
+ slots = ["1 / 1 / 4 / 13", "4 / 1 / 7 / 13", "8 / 1 / 10 / 13", "10 / 1 / 13 / 13"]
2222
+ for i, comp in enumerate(gridded):
2223
+ if not comp.get("grid_area") and i < len(slots):
2224
+ comp["grid_area"] = slots[i]
2225
+
2226
+ elif archetype == "data_dashboard":
2227
+ # Dashboard: tile components in a 2-column or 3-column grid
2228
+ has_area = [c for c in gridded if c.get("grid_area")]
2229
+ no_area = [c for c in gridded if not c.get("grid_area")]
2230
+ nn = len(no_area)
2231
+ if nn <= 2:
2232
+ slots = ["1 / 1 / 7 / 7", "1 / 7 / 7 / 13"]
2233
+ elif nn <= 4:
2234
+ slots = ["1 / 1 / 7 / 7", "1 / 7 / 7 / 13",
2235
+ "7 / 1 / 13 / 7", "7 / 7 / 13 / 13"]
2236
+ elif nn <= 6:
2237
+ slots = ["1 / 1 / 5 / 7", "1 / 7 / 5 / 13",
2238
+ "5 / 1 / 9 / 7", "5 / 7 / 9 / 13",
2239
+ "9 / 1 / 13 / 7", "9 / 7 / 13 / 13"]
2240
+ elif nn <= 9:
2241
+ slots = ["1 / 1 / 5 / 5", "1 / 5 / 5 / 9", "1 / 9 / 5 / 13",
2242
+ "5 / 1 / 9 / 5", "5 / 5 / 9 / 9", "5 / 9 / 9 / 13",
2243
+ "9 / 1 / 13 / 5", "9 / 5 / 13 / 9", "9 / 9 / 13 / 13"]
2244
+ else:
2245
+ # Too many: 3-col grid, auto-expand rows
2246
+ slots = []
2247
+ cols = 3
2248
+ row_h = max(2, 12 // ((nn + cols - 1) // cols))
2249
+ for idx in range(nn):
2250
+ r = idx // cols
2251
+ c = idx % cols
2252
+ rs = 1 + r * row_h
2253
+ re = min(13, rs + row_h)
2254
+ cs = 1 + c * 4
2255
+ ce = min(13, cs + 4)
2256
+ slots.append(f"{rs} / {cs} / {re} / {ce}")
2257
+ j = 0
2258
+ for comp in no_area:
2259
+ if j < len(slots):
2260
+ comp["grid_area"] = slots[j]
2261
+ j += 1
2262
+
2263
+ elif archetype == "editorial_flow":
2264
+ # Editorial: stack vertically, full width
2265
+ # Handle Floating_Meta separately — assign to corners based on position
2266
+ # Content components get rows proportional to their content weight
2267
+ no_area = [c for c in gridded if not c.get("grid_area")]
2268
+ content_comps = []
2269
+ for comp in no_area:
2270
+ if comp.get("type") == "Floating_Meta":
2271
+ _assign_floating_meta(comp)
2272
+ else:
2273
+ content_comps.append(comp)
2274
+ if content_comps:
2275
+ _distribute_rows_by_weight(content_comps, start_row=1, end_row=13, full_width=True)
2276
+
2277
+ elif archetype == "split_vertical":
2278
+ # Split: first half on left, second half on right
2279
+ # Each side gets content-proportional row distribution
2280
+ no_area = [c for c in gridded if not c.get("grid_area")]
2281
+ nn = len(no_area)
2282
+ mid = (nn + 1) // 2
2283
+ left = no_area[:mid]
2284
+ right = no_area[mid:]
2285
+ # Left column: cols 1-7
2286
+ if left:
2287
+ weights_l = [_estimate_content_weight(c) for c in left]
2288
+ total_w = sum(weights_l) or 1
2289
+ current = 1
2290
+ for j, comp in enumerate(left):
2291
+ rows = max(2, round((weights_l[j] / total_w) * 12))
2292
+ rs = current
2293
+ re = min(13, current + rows)
2294
+ comp["grid_area"] = f"{rs} / 1 / {re} / 7"
2295
+ current = re
2296
+ # Right column: cols 7-13
2297
+ if right:
2298
+ weights_r = [_estimate_content_weight(c) for c in right]
2299
+ total_w = sum(weights_r) or 1
2300
+ current = 1
2301
+ for j, comp in enumerate(right):
2302
+ rows = max(2, round((weights_r[j] / total_w) * 12))
2303
+ rs = current
2304
+ re = min(13, current + rows)
2305
+ comp["grid_area"] = f"{rs} / 7 / {re} / 13"
2306
+ current = re
2307
+
2308
+ elif archetype == "scattered_canvas":
2309
+ # Scatter: distribute pseudo-randomly across the grid
2310
+ no_area = [c for c in gridded if not c.get("grid_area")]
2311
+ scatter_slots = [
2312
+ "1 / 1 / 5 / 6", "1 / 7 / 4 / 13", "5 / 3 / 9 / 10",
2313
+ "6 / 1 / 10 / 5", "7 / 8 / 11 / 13", "10 / 2 / 13 / 8",
2314
+ "10 / 8 / 13 / 13", "3 / 1 / 6 / 5", "1 / 4 / 4 / 10",
2315
+ ]
2316
+ for j, comp in enumerate(no_area):
2317
+ if j < len(scatter_slots):
2318
+ comp["grid_area"] = scatter_slots[j]
2319
+
2320
+ elif archetype == "shaped_editorial":
2321
+ # Shaped: main shaped canvas gets most of the page
2322
+ no_area = [c for c in gridded if not c.get("grid_area")]
2323
+ for j, comp in enumerate(no_area):
2324
+ if comp.get("type") == "Shaped_Canvas":
2325
+ comp["grid_area"] = "2 / 2 / 12 / 12"
2326
+ elif comp.get("type") == "Floating_Meta":
2327
+ _assign_floating_meta(comp)
2328
+ else:
2329
+ comp["grid_area"] = f"{1 + j * 3} / 1 / {min(13, 4 + j * 3)} / 13"
2330
+
2331
+ # Fallback: if still no grid_area, make full-width stacked rows
2332
+ # Uses content-aware distribution instead of equal division
2333
+ remaining = [c for c in gridded if not c.get("grid_area")]
2334
+ if remaining:
2335
+ # First, handle Floating_Meta components by position
2336
+ non_meta = []
2337
+ for comp in remaining:
2338
+ if comp.get("type") == "Floating_Meta":
2339
+ _assign_floating_meta(comp)
2340
+ else:
2341
+ non_meta.append(comp)
2342
+ # Then distribute rows proportionally to content weight
2343
+ if non_meta:
2344
+ _distribute_rows_by_weight(non_meta, start_row=1, end_row=13, full_width=True)
2345
+
2346
+
2347
+ def _wrap_grid_item(comp, inner_html):
2348
+ """Wrap a rendered component in a .grid-item div with grid positioning."""
2349
+ grid_area_css = _parse_grid_area(comp)
2350
+ v_align, h_align = _parse_align(comp)
2351
+
2352
+ # Glass_Canvas and Process_List should stretch to fill their grid area
2353
+ ctype = comp.get("type", "")
2354
+ if ctype in ("Glass_Canvas", "Process_List"):
2355
+ v_align = "stretch"
2356
+
2357
+ style_parts = []
2358
+ if grid_area_css:
2359
+ style_parts.append(f"grid-area: {grid_area_css}")
2360
+ style_parts.append(f"align-items: {v_align}")
2361
+ style_parts.append(f"justify-content: {h_align}")
2362
+
2363
+ style = "; ".join(style_parts) + ";"
2364
+ return f'<div class="grid-item" style="{style}">\n{inner_html}</div>\n'
2365
+
2366
+
2367
+ def render_component(comp):
2368
+ """Convert a JSON component object into HTML string, wrapped in grid-item."""
2369
+ # Flatten nested "content" and "style" dicts into top-level for compat
2370
+ # e.g. {"content": {"heading": "Hi"}} → {"heading": "Hi"}
2371
+ _content = comp.get("content", None)
2372
+ if isinstance(_content, dict):
2373
+ for k, v in _content.items():
2374
+ if k not in comp:
2375
+ comp[k] = v
2376
+ _style = comp.get("style", None)
2377
+ if isinstance(_style, dict):
2378
+ for k, v in _style.items():
2379
+ if k not in comp:
2380
+ comp[k] = v
2381
+
2382
+ ctype = comp.get("type", "")
2383
+ inner = ""
2384
+
2385
+ if ctype == "Hero_Typography":
2386
+ weight = comp.get("weight", "black")
2387
+ heading = comp.get("heading", "")
2388
+ subheading = comp.get("subheading", "")
2389
+ # Fallback: if "content" is a plain string, use it as heading
2390
+ raw_content = comp.get("content", "")
2391
+ if not heading and isinstance(raw_content, str) and raw_content:
2392
+ heading = raw_content
2393
+ # Sanitize consecutive <br> — collapse 3+ into max 2
2394
+ heading = re.sub(r'(<br\s*/?>){3,}', '<br><br>', heading)
2395
+ if subheading:
2396
+ subheading = re.sub(r'(<br\s*/?>){3,}', '<br><br>', subheading)
2397
+ scale = comp.get("scale", None)
2398
+ # Build inline style from both scale and custom style props
2399
+ style_parts = []
2400
+ if scale is not None and 1 <= int(scale) <= 6:
2401
+ style_parts.append(f"font-size: var(--text-scale-{int(scale)})")
2402
+ heading_font_size = comp.get("heading_font_size", "")
2403
+ heading_color = comp.get("heading_color", "")
2404
+ heading_ls = comp.get("heading_letter_spacing", "")
2405
+ text_align = comp.get("text_align", "")
2406
+ if heading_font_size:
2407
+ style_parts.append(f"font-size: {heading_font_size}")
2408
+ if heading_color:
2409
+ style_parts.append(f"color: {heading_color}")
2410
+ if heading_ls:
2411
+ style_parts.append(f"letter-spacing: {heading_ls}")
2412
+ if text_align:
2413
+ style_parts.append(f"text-align: {text_align}")
2414
+ h_style = f' style="{"; ".join(style_parts)}"' if style_parts else ""
2415
+ inner = f'<h1 class="hero-type weight-{weight}"{h_style}>{heading}</h1>\n'
2416
+ if subheading:
2417
+ sub_style_parts = []
2418
+ sub_fs = comp.get("subheading_font_size", "")
2419
+ sub_color = comp.get("subheading_color", "")
2420
+ sub_ls = comp.get("subheading_letter_spacing", "")
2421
+ if sub_fs:
2422
+ sub_style_parts.append(f"font-size: {sub_fs}")
2423
+ if sub_color:
2424
+ sub_style_parts.append(f"color: {sub_color}")
2425
+ if sub_ls:
2426
+ sub_style_parts.append(f"letter-spacing: {sub_ls}")
2427
+ if text_align:
2428
+ sub_style_parts.append(f"text-align: {text_align}")
2429
+ s_style = f' style="{"; ".join(sub_style_parts)}"' if sub_style_parts else ""
2430
+ inner += f'<p class="hero-sub"{s_style}>{subheading}</p>\n'
2431
+
2432
+ elif ctype == "Glass_Canvas":
2433
+ md = comp.get("markdown_content", "") or comp.get("body", "")
2434
+ html_content = simple_markdown_to_html(md)
2435
+ # Build inline style from custom style props
2436
+ gs_parts = ["width:100%", "min-height:100%", "box-sizing:border-box"]
2437
+
2438
+ # --- Auto font-size scaling for Glass_Canvas ---
2439
+ # When content is too long for the allocated grid rows, shrink font-size
2440
+ # to avoid overflow into adjacent components.
2441
+ # Estimation: ~80 chars per row at 16px base font-size (with padding).
2442
+ user_font_size = comp.get("font_size", "")
2443
+ if not user_font_size: # Only auto-scale when user hasn't set a custom size
2444
+ grid_area_str = comp.get("grid_area", "")
2445
+ if grid_area_str:
2446
+ try:
2447
+ ga_parts = [int(x.strip()) for x in grid_area_str.split("/")]
2448
+ allocated_rows = ga_parts[2] - ga_parts[0] # row_end - row_start
2449
+ content_len = len(md)
2450
+ chars_per_row = 80 # approximate chars that fit in one grid row at 16px
2451
+ needed_rows = max(1, content_len / chars_per_row)
2452
+ if needed_rows > allocated_rows:
2453
+ # Scale down proportionally, but never below 12px
2454
+ scale = allocated_rows / needed_rows
2455
+ new_size = max(12, int(16 * scale))
2456
+ if new_size < 16:
2457
+ gs_parts.append(f"font-size: {new_size}px")
2458
+ except (ValueError, IndexError):
2459
+ pass
2460
+
2461
+ for prop in ["background", "border", "border_radius", "padding", "font_size", "color", "line_height", "text_align"]:
2462
+ val = comp.get(prop, "")
2463
+ if val:
2464
+ css_prop = prop.replace("_", "-")
2465
+ gs_parts.append(f"{css_prop}: {val}")
2466
+ grid_style = "; ".join(gs_parts) + ";"
2467
+ tension = comp.get("tension_score", None)
2468
+ if tension is not None:
2469
+ weight = int(300 + (float(tension) * 600))
2470
+ inner = f'<div class="glass-canvas" style="{grid_style}font-variation-settings: \'wght\' {weight};">{html_content}</div>\n'
2471
+ else:
2472
+ inner = f'<div class="glass-canvas" style="{grid_style}">{html_content}</div>\n'
2473
+
2474
+ elif ctype == "Floating_Meta":
2475
+ pos = comp.get("position", "top-left")
2476
+ items_html = "".join([f"<span>{item}</span>" for item in comp.get("items", [])])
2477
+ fm_style_parts = []
2478
+ for prop in ["font_size", "color", "letter_spacing", "text_align"]:
2479
+ val = comp.get(prop, "")
2480
+ if val:
2481
+ fm_style_parts.append(f"{prop.replace('_', '-')}: {val}")
2482
+ fm_style = f' style="{"; ".join(fm_style_parts)}"' if fm_style_parts else ""
2483
+ inner = f'<div class="floating-meta pos-{pos}"{fm_style}>{items_html}</div>\n'
2484
+
2485
+ elif ctype == "Stat_Block":
2486
+ inner = f'''<div class="stat-block">
2487
+ <div><span class="stat-num">{comp.get("number", "")}</span><span class="stat-unit">{comp.get("unit", "")}</span></div>
2488
+ <span class="stat-label">{comp.get("label", "")}</span>
2489
+ </div>\n'''
2490
+
2491
+ elif ctype == "Hairline_Divider":
2492
+ style = comp.get("style", "bleed")
2493
+ inner = f'<hr class="hairline style-{style}">\n'
2494
+
2495
+ elif ctype == "Page_Ghost_Number":
2496
+ # Ghost numbers are decorative overlays — still use absolute positioning
2497
+ return f'<div class="page-ghost">{comp.get("number", "")}</div>\n'
2498
+
2499
+ elif ctype == "Shaped_Canvas":
2500
+ shape = comp.get("shape_keyword", "circle")
2501
+ md = comp.get("markdown_content", "") or comp.get("body", "")
2502
+ html_content = simple_markdown_to_html(md)
2503
+ sc_style_parts = []
2504
+ for prop in ["background", "border", "border_radius", "padding"]:
2505
+ val = comp.get(prop, "")
2506
+ if val:
2507
+ sc_style_parts.append(f"{prop.replace('_', '-')}: {val}")
2508
+ sc_style = f' style="{"; ".join(sc_style_parts)}"' if sc_style_parts else ""
2509
+ inner = f'''<div class="shaped-canvas"{sc_style}>
2510
+ <div class="shape-float shape-{shape}" aria-hidden="true"></div>
2511
+ <div class="shaped-content">{html_content}</div>
2512
+ </div>\n'''
2513
+
2514
+ elif ctype == "Image_Asset":
2515
+ src = comp.get("src", "")
2516
+ alt = comp.get("alt", "")
2517
+ fit = comp.get("object_fit", "cover")
2518
+ inner = f'<img src="{src}" alt="{alt}" style="width:100%;height:100%;object-fit:{fit};border-radius:2px;" />\n'
2519
+
2520
+ elif ctype == "Sidenote_Block":
2521
+ label = comp.get("label", "")
2522
+ body = comp.get("body", "") or comp.get("markdown_content", "")
2523
+ html_body = simple_markdown_to_html(body)
2524
+ label_html = f'<span class="sidenote-label">{label}</span>' if label else ""
2525
+ inner = f'<div class="sidenote">{label_html}{html_body}</div>\n'
2526
+ # Sidenotes bypass grid-item wrapping for Tufte layout — returned raw
2527
+ return inner
2528
+
2529
+ elif ctype == "Delta_Widget":
2530
+ metric = comp.get("metric", "")
2531
+ value = comp.get("value", "")
2532
+ delta = comp.get("delta", "")
2533
+ trend = comp.get("trend", "up") # up / down / flat
2534
+ label = comp.get("label", "")
2535
+ trend_symbol = {"up": "▲", "down": "▼", "flat": "─"}.get(trend, "")
2536
+ trend_color = {"up": "#22c55e", "down": "#ef4444", "flat": "var(--c-muted)"}.get(trend, "var(--c-muted)")
2537
+ inner = f'''<div class="delta-widget">
2538
+ <div class="delta-metric">{metric}</div>
2539
+ <div class="delta-value">{value}</div>
2540
+ <div class="delta-change" style="color:{trend_color}"><span>{trend_symbol}</span> {delta}</div>
2541
+ <div class="delta-label">{label}</div>
2542
+ </div>\n'''
2543
+
2544
+ elif ctype == "Process_List":
2545
+ steps = comp.get("steps", [])
2546
+ steps_html = ""
2547
+ for i, step in enumerate(steps):
2548
+ title = step.get("title", "")
2549
+ desc = step.get("description", "")
2550
+ steps_html += f'<li class="process-step"><span class="step-num">{i+1}</span><div><div class="step-title">{title}</div><div class="step-desc">{desc}</div></div></li>\n'
2551
+ inner = f'<div class="process-list-container"><ul class="process-list">{steps_html}</ul></div>\n'
2552
+
2553
+ else:
2554
+ return f"<!-- Unknown component: {ctype} -->\n"
2555
+
2556
+ return _wrap_grid_item(comp, inner)
2557
+
2558
+
2559
+ def compile_blueprint(json_path, output_html_path):
2560
+ """Reads the LLM JSON blueprint and generates the final poster.html"""
2561
+ with open(json_path, 'r', encoding='utf-8') as f:
2562
+ blueprint = json.load(f)
2563
+
2564
+ art = blueprint.get("art_direction", {})
2565
+ # Intent: auto-derive from document title if not explicitly provided
2566
+ doc_title = blueprint.get("document_meta", {}).get("title", "")
2567
+ intent = art.get("intent", None)
2568
+ if not intent:
2569
+ intent = derive_intent(doc_title) if doc_title else "neutral"
2570
+ intent = intent.lower()
2571
+ mode = art.get("palette_mode", "minimal").lower()
2572
+ harmony = art.get("color_harmony", "auto").lower() # "auto" → intent-based recommendation
2573
+ svg_type = art.get("background_svg", "flow")
2574
+ pages = blueprint.get("pages", [])
2575
+ total_pages = len(pages)
2576
+
2577
+ # 1. Compute Aesthetics — three pillars: intent + mode + harmony
2578
+ palette = generate_color_palette(intent, mode, harmony=harmony)
2579
+ css_vars = palette_to_css(palette)
2580
+
2581
+ # Detect if any component uses tension_score → switch to Variable Font URL
2582
+ has_tension = False
2583
+ for page in pages:
2584
+ for comp in page.get("components", []):
2585
+ if comp.get("tension_score") is not None:
2586
+ has_tension = True
2587
+ break
2588
+ if has_tension:
2589
+ break
2590
+
2591
+ # Generate SVG backgrounds
2592
+ canvas_w = art.get("canvas_width", 720)
2593
+ canvas_h = art.get("canvas_height", 960)
2594
+ use_continuous = total_pages > 1 # Multi-page → continuous canvas mode
2595
+ continuous_svgs = None
2596
+ unified_svg = ""
2597
+ bg_svg = ""
2598
+ if use_continuous and svg_type != "none":
2599
+ # Generate one unified SVG spanning the entire document
2600
+ unified_svg = generate_unified_svg(canvas_w, canvas_h, total_pages, svg_type, palette['accent'])
2601
+ elif not use_continuous:
2602
+ if svg_type == "continuous_flow" and total_pages > 1:
2603
+ continuous_svgs = generate_continuous_flow_svg(canvas_w, canvas_h, total_pages, palette['accent'])
2604
+ elif svg_type != "none":
2605
+ bg_svg = generate_generative_svg(svg_type, canvas_w, canvas_h, palette['accent'])
2606
+
2607
+ # Font URL: use variable axis range if tension is active
2608
+ if has_tension:
2609
+ font_url = "https://fonts.googleapis.com/css2?family=Inter:wght@100..900&family=Noto+Sans+SC:wght@300;400;500;700;900&family=Playfair+Display:ital,wght@0,400;0,700;0,900;1,400&display=swap"
2610
+ else:
2611
+ font_url = "https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&family=Noto+Sans+SC:wght@300;400;500;700;900&family=Playfair+Display:ital,wght@0,400;0,700;0,900;1,400&display=swap"
2612
+
2613
+ # 1b. Dynamic Gap — intent-driven grid density
2614
+ # If the LLM explicitly sets grid_gap in art_direction, use that (override).
2615
+ # Otherwise, derive from intent.
2616
+ explicit_gap = art.get("grid_gap", None)
2617
+ if explicit_gap is not None:
2618
+ dynamic_gap = str(explicit_gap) if "px" in str(explicit_gap) else f"{explicit_gap}px"
2619
+ else:
2620
+ gap_mapping = {
2621
+ "serenity": "48px",
2622
+ "elegance": "32px",
2623
+ "minimalism": "40px",
2624
+ "warmth": "24px",
2625
+ "neutral": "16px",
2626
+ "tension": "8px",
2627
+ "energy": "4px",
2628
+ }
2629
+ dynamic_gap = gap_mapping.get(intent, "16px")
2630
+
2631
+ # 2. Build override CSS for custom canvas size, background, bleed
2632
+ override_css = ""
2633
+ override_css += f":root {{ --canvas-w: {canvas_w}px; --canvas-h: {canvas_h}px; }}\n"
2634
+ # @page size MUST use concrete values (CSS variables are NOT resolved in @page rules)
2635
+ override_css += f"@page {{ size: {canvas_w}px {canvas_h}px; margin: 0; }}\n"
2636
+ # html/body must match canvas size for full-bleed PDF output
2637
+ # Use min-height (not height) so content taller than canvas_h expands naturally
2638
+ override_css += f"html, body {{ width: {canvas_w}px; min-height: {canvas_h}px; }}\n"
2639
+ bg_color = art.get("background_color", "")
2640
+ if bg_color:
2641
+ override_css += f".canvas {{ background: {bg_color}; }}\n"
2642
+ override_css += f".continuous-canvas {{ background: {bg_color}; }}\n"
2643
+ if art.get("bleed", False):
2644
+ override_css += ".safe-zone { inset: 0 !important; padding: 0 !important; }\n"
2645
+
2646
+ # Screen preview: inject concrete scale value (CSS calc with var may not work in scale)
2647
+ override_css += f"@media screen {{ body {{ scale: min(1, calc(100vw / {canvas_w}), calc(100vh / {canvas_h})); }} }}\n"
2648
+
2649
+ # 3. Build HTML Document
2650
+ html = f"""<!DOCTYPE html>
2651
+ <html lang="en">
2652
+ <head>
2653
+ <meta charset="UTF-8">
2654
+ <link href="{font_url}" rel="stylesheet">
2655
+ <title>{blueprint.get("document_meta", {}).get("title", "Document")}</title>
2656
+ <style>
2657
+ {css_vars}
2658
+ {BASE_CSS}
2659
+ {override_css}
2660
+ </style>
2661
+ </head>
2662
+ <body>
2663
+ """
2664
+
2665
+ # 3. Render Pages
2666
+ if use_continuous:
2667
+ # ═══ CONTINUOUS CANVAS MODE ═══
2668
+ # Render all pages as one seamless surface, then let Playwright's page.pdf() slice it.
2669
+ total_height = canvas_h * total_pages
2670
+ html += f'\n<div class="continuous-canvas" style="height: {total_height}px; background: var(--c-bg);">\n'
2671
+
2672
+ # Unified background SVG spanning the entire document
2673
+ if unified_svg:
2674
+ html += f' <div class="bg-layer-full">{unified_svg}</div>\n'
2675
+
2676
+ # Render each page as an absolutely-positioned section within the continuous canvas
2677
+ for page_idx, page in enumerate(pages):
2678
+ archetype = page.get("archetype", "cover_hero")
2679
+ page_top = page_idx * canvas_h
2680
+
2681
+ # Auto-assign grid areas
2682
+ _auto_assign_grid_areas(archetype, page.get("components", []))
2683
+
2684
+ # Cognitive Load Margins
2685
+ total_chars = 0
2686
+ sidenotes = []
2687
+ main_components = []
2688
+ for comp in page.get("components", []):
2689
+ text_content = comp.get("markdown_content", "") or comp.get("body", "") or ""
2690
+ total_chars += len(text_content)
2691
+ if comp.get("type") == "Sidenote_Block":
2692
+ sidenotes.append(comp)
2693
+ else:
2694
+ main_components.append(comp)
2695
+ for step in comp.get("steps", []):
2696
+ total_chars += len(step.get("title", "")) + len(step.get("description", ""))
2697
+
2698
+ if total_chars > 500:
2699
+ safe_inset = "8% 10%"
2700
+ elif total_chars > 200:
2701
+ safe_inset = "10% 12%"
2702
+ else:
2703
+ safe_inset = ""
2704
+ safe_inset_style = f" inset: {safe_inset};" if safe_inset else ""
2705
+
2706
+ # Page section: positioned absolutely within continuous canvas
2707
+ html += f'\n <div class="page-section archetype-{archetype}" style="top: {page_top}px; height: {canvas_h}px;">\n'
2708
+
2709
+ # Per-page data-driven SVG background (overlays on top of unified bg)
2710
+ if svg_type != "none":
2711
+ data_points = None
2712
+ for comp in page.get("components", []):
2713
+ dp = comp.get("data_points")
2714
+ if dp and isinstance(dp, list) and all(isinstance(x, (int, float)) for x in dp):
2715
+ data_points = dp
2716
+ break
2717
+ if data_points and len(data_points) >= 2:
2718
+ page_svg = _generate_data_driven_svg(data_points, canvas_w, canvas_h, palette['accent'])
2719
+ html += f' <div class="bg-layer" style="position:absolute;inset:0;z-index:2;pointer-events:none;">{page_svg}</div>\n'
2720
+
2721
+ # Tufte layout
2722
+ if archetype == "tufte_report" and sidenotes:
2723
+ html += f' <div class="safe-zone" style="gap: {dynamic_gap};{safe_inset_style}">\n'
2724
+ html += f' <div class="main-column" style="gap: {dynamic_gap};">\n'
2725
+ for comp in main_components:
2726
+ html += " " + render_component(comp)
2727
+ html += ' </div>\n'
2728
+ html += ' <div class="side-rail">\n'
2729
+ for comp in sidenotes:
2730
+ html += " " + render_component(comp)
2731
+ html += ' </div>\n'
2732
+ html += ' </div>\n'
2733
+ else:
2734
+ html += f' <div class="safe-zone" style="gap: {dynamic_gap};{safe_inset_style}">\n'
2735
+ for comp in page.get("components", []):
2736
+ html += " " + render_component(comp)
2737
+ html += ' </div>\n'
2738
+
2739
+ html += ' </div>\n'
2740
+
2741
+ html += '</div>\n'
2742
+
2743
+ else:
2744
+ # ═══ LEGACY PER-PAGE MODE (single-page documents) ═══
2745
+ for page_idx, page in enumerate(pages):
2746
+ archetype = page.get("archetype", "cover_hero")
2747
+
2748
+ _auto_assign_grid_areas(archetype, page.get("components", []))
2749
+
2750
+ total_chars = 0
2751
+ sidenotes = []
2752
+ main_components = []
2753
+ for comp in page.get("components", []):
2754
+ text_content = comp.get("markdown_content", "") or comp.get("body", "") or ""
2755
+ total_chars += len(text_content)
2756
+ if comp.get("type") == "Sidenote_Block":
2757
+ sidenotes.append(comp)
2758
+ else:
2759
+ main_components.append(comp)
2760
+ for step in comp.get("steps", []):
2761
+ total_chars += len(step.get("title", "")) + len(step.get("description", ""))
2762
+
2763
+ if total_chars > 500:
2764
+ safe_inset = "8% 10%"
2765
+ elif total_chars > 200:
2766
+ safe_inset = "10% 12%"
2767
+ else:
2768
+ safe_inset = ""
2769
+ safe_inset_style = f" inset: {safe_inset};" if safe_inset else ""
2770
+
2771
+ page_svg = ""
2772
+ if svg_type != "none":
2773
+ data_points = None
2774
+ for comp in page.get("components", []):
2775
+ dp = comp.get("data_points")
2776
+ if dp and isinstance(dp, list) and all(isinstance(x, (int, float)) for x in dp):
2777
+ data_points = dp
2778
+ break
2779
+ if data_points and len(data_points) >= 2:
2780
+ page_svg = _generate_data_driven_svg(data_points, canvas_w, canvas_h, palette['accent'])
2781
+ elif continuous_svgs and page_idx < len(continuous_svgs):
2782
+ page_svg = continuous_svgs[page_idx]
2783
+ elif bg_svg:
2784
+ page_svg = bg_svg
2785
+
2786
+ html += f'\n<div class="canvas archetype-{archetype}">\n'
2787
+ if page_svg:
2788
+ html += f' <div class="bg-layer">{page_svg}</div>\n'
2789
+
2790
+ if archetype == "tufte_report" and sidenotes:
2791
+ html += f' <div class="safe-zone" style="gap: {dynamic_gap};{safe_inset_style}">\n'
2792
+ html += f' <div class="main-column" style="gap: {dynamic_gap};">\n'
2793
+ for comp in main_components:
2794
+ html += " " + render_component(comp)
2795
+ html += ' </div>\n'
2796
+ html += ' <div class="side-rail">\n'
2797
+ for comp in sidenotes:
2798
+ html += " " + render_component(comp)
2799
+ html += ' </div>\n'
2800
+ html += ' </div>\n</div>\n'
2801
+ else:
2802
+ html += f' <div class="safe-zone" style="gap: {dynamic_gap};{safe_inset_style}">\n'
2803
+ for comp in page.get("components", []):
2804
+ html += " " + render_component(comp)
2805
+ html += ' </div>\n</div>\n'
2806
+
2807
+ html += "</body>\n</html>"
2808
+
2809
+ # 4. Save
2810
+ with open(output_html_path, 'w', encoding='utf-8') as f:
2811
+ f.write(html)
2812
+
2813
+ return output_html_path, palette
2814
+
2815
+ if __name__ == "__main__":
2816
+ main()