"""Reproduce the chart from the US Federal Trade Commission's 2012 report."""
import csv
from html import escape
from pathlib import Path

source = Path(__file__).with_suffix(".csv")
with source.open(encoding="utf-8", newline="") as file:
    rows = list(csv.DictReader(file))
chart = [
    '<svg xmlns="http://www.w3.org/2000/svg" width="420" height="328" viewBox="0 0 420 328" role="img" aria-labelledby="title desc">',
    '<title id="title">What changed after a dispute?</title>',
    '<desc id="desc">People at each stage of the 2012 US study, out of 1,001 volunteers. Bars use the same denominator.</desc>',
    '<rect width="420" height="328" rx="14" fill="#edf5f1"/>',
    '<g fill="#183932" font-family="Arial, sans-serif" font-size="19">',
    '<text x="22" y="35" font-size="25" font-weight="700">What changed after a dispute?</text>',
    '<text x="22" y="62">US Federal Trade Commission · 2012</text>',
]
for number, row in enumerate(rows):
    count = int(row["people"])
    width = 308 * count / int(row["denominator"])
    y = 93 + 54 * number
    chart.extend(
        [
            f'<text x="22" y="{y}">{escape(row["stage"])}</text>',
            f'<text x="391" y="{y}" text-anchor="end" font-weight="700">{count:,}</text>',
            f'<rect x="22" y="{y + 8}" width="{width:.2f}" height="12" rx="3" fill="#176356"/>',
        ]
    )
chart.extend(
    [
        '<text x="22" y="306" font-size="17">Unit: people, from 1,001 study volunteers</text>',
        '</g></svg>',
    ]
)
source.with_suffix(".svg").write_text("\n".join(chart) + "\n", encoding="utf-8")
