"""Generic CSV table renderer. Used for all CSV @import unless overridden."""
import csv
from html import escape


def render(filepath):
    """Load CSV and render as HTML table."""
    rows = []
    with open(str(filepath), encoding='utf-8') as f:
        for row in csv.DictReader(f):
            rows.append({
                k.strip(): v.strip() if v else ''
                for k, v in row.items()
            })

    if not rows:
        return '<p><em>empty file</em></p>'

    cols = list(rows[0].keys())
    h = ['<table><thead><tr>']
    for c in cols:
        h.append(f'<th>{escape(c)}</th>')
    h.append('</tr></thead><tbody>')
    for r in rows:
        h.append('<tr>')
        for c in cols:
            h.append(f'<td>{escape(str(r.get(c, "")))}</td>')
        h.append('</tr>')
    h.append('</tbody></table>')
    return '\n'.join(h)
