"""Address map table renderer — for seg_define.csv style files."""
import csv
from html import escape


def render(filepath):
    """Render CSV as address map table, merging repeated function cells."""
    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>'

    # Merge consecutive rows with '^' in 功能划分
    segs, prev = [], ''
    for r in rows:
        func = r.get('功能划分', '')
        if func == '^':
            func = prev
        else:
            prev = func
        segs.append({
            '功能划分': func,
            '子模块': r.get('子模块', ''),
            '开始地址': r.get('开始地址', ''),
            '大小': r.get('大小', ''),
        })

    cols = ['功能划分', '子模块', '开始地址', '大小']
    h = ['<table><thead><tr>']
    for c in cols:
        h.append(f'<th>{escape(c)}</th>')
    h.append('</tr></thead><tbody>')
    for s in segs:
        h.append('<tr>')
        for c in cols:
            h.append(f'<td>{escape(str(s.get(c, "")))}</td>')
        h.append('</tr>')
    h.append('</tbody></table>')
    return '\n'.join(h)
