"""Reproduce the original chart of the temporal split described by Fonseca and Lopes."""
import csv
from html import escape
from pathlib import Path

base = Path(__file__)
with base.with_suffix('.csv').open(encoding='utf-8', newline='') as source:
    rows = list(csv.DictReader(source))
assert len(rows) == 3 and sum(int(row['share_percent']) for row in rows) == 100
assert {row['dataset_count'] for row in rows} == {'18'}
assert {row['publication_year'] for row in rows} == {'2017'}

parts = ['''<svg xmlns="http://www.w3.org/2000/svg" width="420" height="310" viewBox="0 0 420 310" role="img" aria-labelledby="title description">
<title id="title">The latest records formed a separate test set</title>
<desc id="description">The first 60 percent of records trained the model. The next 20 percent fitted recalibration. The final 20 percent tested the predictions.</desc>
<rect width="420" height="310" rx="16" fill="#f0f7f5"/>
<g font-family="system-ui, sans-serif" fill="#142f31">
<text x="22" y="42" font-size="27" font-weight="700">Which records went where?</text>
<text x="22" y="72" font-size="21">18 consumer-lending datasets · 2017</text>
<path d="M32 103v154m-7-7 7 7 7-7" fill="none" stroke="#537379" stroke-width="2"/>''']
for index, (row, colour) in enumerate(zip(rows, ('#145a55', '#205a79', '#3b4674'), strict=True)):
    share = int(row['share_percent'])
    width = share * 3.6
    y = 112 + index * 62
    parts.extend((
        f'<text x="54" y="{y}" font-size="22">{escape(row["stage"])}</text>',
        f'<rect x="54" y="{y + 9}" width="{width:g}" height="22" fill="{colour}"/>',
        f'<text x="{63 + width:g}" y="{y + 28}" font-size="23" font-weight="700">{share}%</text>',
    ))
parts.append('''<text x="22" y="292" font-size="20">Earlier to later records in each dataset</text>
</g></svg>''')
base.with_suffix('.svg').write_text('\n'.join(parts) + '\n', encoding='utf-8')
