"""Rebuild the figure from three CFPB Table 4C conforming columns."""
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 292" width="400" height="292">',
    '<title>Denial rates for US home-purchase applications</title>',
    '<desc>Five rows give denial percentages from 2021 to 2023. The race and ethnicity categories are from the source table.</desc>',
    '<rect width="400" height="292" rx="14" fill="#f4f5fc"/>',
    '<g font-family="Arial,sans-serif" fill="#23264a">',
    '<text x="20" y="28" font-size="19" font-weight="bold">US home-purchase denial rates</text>',
    '<text x="20" y="52" font-size="16">Conventional conforming mortgages</text>',
    '<text x="20" y="81" font-size="15" font-weight="bold">Applicant group</text>',
]
columns = ((2021, 248), (2022, 308), (2023, 368))
for year, x in columns:
    svg.append(f'<text x="{x}" y="81" text-anchor="end" font-size="15" font-weight="bold">{year}</text>')
for index, row in enumerate(records):
    y = 113 + index * 33
    svg.append(f'<path d="M20 {y - 20}H380" stroke="#d4d5e7"/>')
    svg.append(f'<text x="20" y="{y}" font-size="15">{escape(row["applicant_group"])}</text>')
    for year, x in columns:
        value = float(row[f"{year}_percent"])
        svg.append(f'<rect x="{x-42}" y="{y+4}" width="42" height="3" rx="1.5" fill="#d4d5e7"/>')
        svg.append(f'<rect x="{x-42}" y="{y+4}" width="{value*2.1:.2f}" height="3" rx="1.5" fill="#62519c"/>')
        svg.append(f'<text x="{x}" y="{y}" text-anchor="end" font-size="15">{value:.1f}%</text>')
svg.extend((
    '<text x="20" y="271" font-size="15">CFPB Home Mortgage Disclosure Act records</text>',
    '</g></svg>',
))
path.with_suffix(".svg").write_text("\n".join(svg) + "\n", encoding="utf-8")
