"""BGA ball grid renderer — for pin_loc.csv style files."""
import csv
from html import escape


def render(filepath):
    """Render CSV as BGA ball grid table."""
    rows = []
    with open(str(filepath), encoding='utf-8') as f:
        for row in csv.reader(f):
            rows.append([c.strip() for c in row])

    if len(rows) < 2:
        return '<p><em>empty or malformed file</em></p>'

    ncols = len(rows[0]) - 1
    h = ['<table class="compact pin-grid"><thead><tr><th></th>']
    for c in range(1, ncols + 1):
        h.append(f'<th class="text-center">{c}</th>')
    h.append('</tr></thead><tbody>')

    for r in rows[1:]:
        if not r:
            continue
        h.append(
            f'<tr><th class="text-center">{escape(r[0])}</th>'
        )
        for c in range(1, ncols + 1):
            val = r[c] if c < len(r) else ''
            h.append(
                f'<td class="text-center text-mono"'
                f' style="font-size:6pt">{escape(val)}</td>'
            )
        h.append('</tr>')
    h.append('</tbody></table>')
    return '\n'.join(h)
