"""Rebuild the figure from the NCHS published aggregate estimates."""
import csv
from pathlib import Path
from xml.sax.saxutils import escape

path = Path(__file__)
with path.with_suffix(".csv").open(newline="", encoding="utf-8") as file:
    records = list(csv.DictReader(file))

svg = [
    '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 325" width="400" height="325">',
    '<title>Organised sport participation by family income</title>',
    '<desc>Three bars show increasing participation as family income rises. A line crossing each bar tip shows the published confidence interval.</desc>',
    '<rect width="400" height="325" rx="14" fill="#f2f7f4"/>',
    '<g font-family="Arial,sans-serif" fill="#18382b">',
    '<text x="20" y="28" font-size="19" font-weight="bold">Organised sport participation</text>',
    '<text x="20" y="51" font-size="16">US children aged 6–17, 2020 survey</text>',
    '<text x="20" y="76" font-size="15">Family income as a share of the poverty level</text>',
]
start, extent = 23, 329
for index, row in enumerate(records):
    y = 111 + index * 53
    point, low, high = (
        float(row[column])
        for column in ("estimate_percent", "lower_95_percent", "upper_95_percent")
    )
    left = start + extent * low / 100
    right = start + extent * high / 100
    estimate = extent * point / 100
    svg.append(f'<text x="{start}" y="{y}" font-size="16">{escape(row["family_income_share_of_poverty_level"])}</text>')
    svg.append(f'<text x="377" y="{y}" text-anchor="end" font-size="16" font-weight="bold">{point:g}%</text>')
    svg.append(f'<rect x="{start}" y="{y + 10}" width="{estimate:.2f}" height="13" rx="4" fill="#4a795c"/>')
    svg.append(f'<path d="M{left:.2f} {y+12}v9m0 -4.5H{right:.2f}m0 -4.5v9" stroke="#13231a" stroke-width="2.4" fill="none"/>')
for tick in (0, 25, 50, 75, 100):
    x = start + extent * tick / 100
    svg.append(f'<text x="{x:.2f}" y="263" text-anchor="middle" font-size="15">{tick}</text>')
svg.extend((
    '<text x="23" y="290" font-size="15">Reported participation (%)</text>',
    '<path d="M27 301v10m0 -5h24m0 -5v10" stroke="#13231a" stroke-width="2.4" fill="none"/>',
    '<text x="60" y="311" font-size="15">95% confidence interval</text>',
    '</g></svg>',
))
path.with_suffix(".svg").write_text("\n".join(svg) + "\n", encoding="utf-8")
