"""Rebuild the coffee-label figure from the published means and SEs."""
import csv
from html import escape
from pathlib import Path

here = Path(__file__).parent
rows = list(csv.DictReader((here / "coffee-label-acidity.csv").open(encoding="utf-8")))
axis_start, axis_end = 20, 365
units = (axis_end - axis_start) / 10
items = [
    '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 330" role="img" aria-labelledby="acidity-title acidity-desc">',
    '<title id="acidity-title">One coffee, three acidity ratings</title>',
    '<desc id="acidity-desc">Mean ratings on a zero to ten scale: no process term 4.6 (SE 0.2); fermentation 6.3 (SE 0.1); carbonic maceration 4.9 (SE 0.2).</desc>',
    '<rect width="400" height="330" rx="14" fill="#f6eee4"/>',
    '<g font-family="Arial,sans-serif" fill="#2e211c">',
    '<text x="20" y="35" font-size="23" font-weight="700">One coffee, three acidity ratings</text>',
    '<text x="20" y="62" font-size="17">Mean ratings after tasting, with standard errors</text>',
]
for index, row in enumerate(rows):
    label_y = 103 + 53 * index
    point_y = label_y + 19
    mean = float(row["mean_acidity"])
    se = float(row["standard_error"])
    point = axis_start + units * mean
    left, right = point - units * se, point + units * se
    items += [
        f'<text x="20" y="{label_y}" font-size="19">{escape(row["processing_label"])}</text>',
        f'<line x1="{axis_start}" x2="{axis_end}" y1="{point_y}" y2="{point_y}" stroke="#cbbcad"/>',
        f'<line x1="{left:.2f}" x2="{right:.2f}" y1="{point_y}" y2="{point_y}" stroke="#18584d" stroke-width="5"/>',
        f'<line x1="{left:.2f}" x2="{left:.2f}" y1="{point_y-5}" y2="{point_y+5}" stroke="#18584d" stroke-width="2"/>',
        f'<line x1="{right:.2f}" x2="{right:.2f}" y1="{point_y-5}" y2="{point_y+5}" stroke="#18584d" stroke-width="2"/>',
        f'<circle cx="{point:.2f}" cy="{point_y}" r="4.5" fill="#18584d"/>',
        f'<text x="{right+9:.2f}" y="{point_y-7}" font-size="17" font-weight="700">{mean:.1f}</text>',
    ]
items += [
    '<line x1="20" x2="365" y1="263" y2="263" stroke="#66574f"/>',
    '<text x="20" y="285" font-size="17">0</text>',
    '<text x="192.5" y="285" font-size="17" text-anchor="middle">5</text>',
    '<text x="365" y="285" font-size="17" text-anchor="end">10</text>',
    '<text x="20" y="313" font-size="16">Carvalho et al. (2026) · 180 São Paulo tasters</text>',
    '</g></svg>',
]
(here / "coffee-label-acidity.svg").write_text("\n".join(items) + "\n", encoding="utf-8")
