"""Render the three visibility classes from Huang et al. (2019), Table IV."""
from csv import DictReader
from html import escape
from pathlib import Path

base = Path(__file__).resolve().with_suffix('')
with base.with_suffix('.csv').open(encoding='utf-8', newline='') as data:
    rows = list(DictReader(data))

svg = [
    '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 410 336" width="410" height="336" role="img" aria-labelledby="title desc">',
    '<title id="title">Ball positions within five pixels</title>',
    '<desc id="desc">Percentages and counts of correct positions by visibility class in the TrackNet single-broadcast test.</desc>',
    '<rect width="410" height="336" rx="15" fill="#eef6f2"/>',
    '<g fill="#17372e" font-family="Arial,sans-serif">',
    '<text x="20" y="35" font-size="25" font-weight="bold">Ball tracking by visibility</text>',
    '<text x="20" y="63" font-size="18">Within five pixels of the label</text>',
]
for index, row in enumerate(rows):
    correct, labelled = int(row['correct']), int(row['labelled'])
    share = 100 * correct / labelled
    y = 100 + index * 66
    svg.extend([
        f'<text x="20" y="{y}" font-size="20" font-weight="bold">{escape(row["visibility"])}</text>',
        f'<text x="389" y="{y}" font-size="17" text-anchor="end">{correct:,}/{labelled:,} · {share:.1f}%</text>',
        f'<rect x="20" y="{y + 10}" width="369" height="13" rx="6" fill="#ccddd3"/>',
        f'<rect x="20" y="{y + 10}" width="{369 * share / 100:.2f}" height="13" rx="6" fill="#22634d"/>',
    ])
svg.extend([
    '<text x="20" y="296" font-size="17">2017 Summer Universiade men’s final</text>',
    '<text x="20" y="318" font-size="16">Source: Huang et al. (2019), Table IV</text>',
    '</g></svg>',
])
base.with_suffix('.svg').write_text('\n'.join(svg) + '\n', encoding='utf-8')
