import csv, sys
from decimal import Decimal
from pathlib import Path
from html import escape

source, target, mode = sys.argv[1:]
with Path(source).open() as f:
    rows = list(csv.DictReader(f))

if mode == 'sports':
    assert len(rows) == 9 and len({r['outlet'] for r in rows}) == 9
    prices = [Decimal(r['price_jmd']) for r in rows]
    assert (min(prices), max(prices), max(prices)-min(prices)) == (Decimal('435'),Decimal('499.53'),Decimal('64.53'))
    title = 'Price per 800 g rice pack'
    desc = 'Nine outlet prices in Westmoreland and St Elizabeth in Jamaican dollars, 7–8 October 2026.'
    height = 448
    marks = []
    for i, r in enumerate(sorted(rows, key=lambda r: Decimal(r['price_jmd']))):
        value = Decimal(r['price_jmd'])
        y = 92+32*i
        x = 286 + float((value-400)/100)*239
        marks.append(f'<text x="20" y="{y+5}" font-size="17">{escape(r["outlet"])}</text><path d="M286 {y}H525" stroke="#dde6df"/><circle cx="{x:.2f}" cy="{y}" r="7" fill="#126547"/><text x="554" y="{y+5}" font-size="16">J${value:.2f}</text>')
    marks.extend(f'<text x="{286+(v-400)*2.39}" y="395" text-anchor="middle" font-size="16">{v}</text>' for v in (400,450,500))
    marks.append('<text x="404" y="425" text-anchor="middle" font-size="16">Jamaican dollars per pack</text>')
else:
    assert len(rows)==1
    lo,hi=(int(rows[0][k]) for k in ('low_pct','high_pct'))
    assert (lo,hi)==(15,30)
    title = 'Share approved by the US fintech'
    desc = 'Authors’ reported range, 15% to 30% of low-credit-score applicants rejected by traditional models. This is not a confidence interval.'
    height = 245
    x = lambda v: 65 + v*5.5
    marks=[f'<path d="M65 125H615" stroke="#d4dfeb" stroke-width="3"/><path d="M{x(lo)} 125H{x(hi)}" stroke="#235b73" stroke-width="10"/><circle cx="{x(lo)}" cy="125" r="8" fill="#235b73"/><circle cx="{x(hi)}" cy="125" r="8" fill="#235b73"/>',
           f'<text x="{x(lo)}" y="98" text-anchor="middle" font-size="22">{lo}%</text><text x="{x(hi)}" y="98" text-anchor="middle" font-size="22">{hi}%</text>']
    marks.extend(f'<text x="{x(v)}" y="166" text-anchor="middle" font-size="17">{v}%</text>' for v in (0,25,50,75,100))
    marks.append('<text x="340" y="210" text-anchor="middle" font-size="16">Denominator: low-score applicants refused by the comparisons</text>')
svg = f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 680 {height}" role="img" aria-labelledby="title desc"><title id="title">{escape(title)}</title><desc id="desc">{escape(desc)}</desc><rect width="680" height="{height}" fill="#f7faf7"/><g font-family="Arial,sans-serif" fill="#17352a"><text x="20" y="38" font-size="25" font-weight="700">{escape(title)}</text>{"".join(marks)}</g></svg>\n'
Path(target).write_text(svg)
