"""把 Document 渲染为带 inline style 的 HTML 段落，给前端用。"""

from __future__ import annotations
from html import escape
from fastapi_modules.fastapi_leaudit.govdoc_engine.models import Document


def _style(p) -> str:
    s = p.style
    parts = []
    if s.font_size_pt:
        sz = s.font_size_pt
        sz_str = str(int(sz)) if sz == int(sz) else str(sz)
        parts.append(f"font-size:{sz_str}pt")
    if s.font_eastasia:
        parts.append(f"font-family:'{s.font_eastasia}',serif")
    if s.alignment and s.alignment != "left":
        parts.append(f"text-align:{s.alignment}")
    if s.bold:
        parts.append("font-weight:700")
    if s.first_line_indent_pt:
        parts.append(f"text-indent:{s.first_line_indent_pt}pt")
    return ";".join(parts)


def paragraphs_to_html(doc: Document, finding_map: dict[int, list[str]]) -> str:
    """把 doc 每个段落渲染成 <p> 带 data-pi / data-role / data-finding-ids。"""
    out = ['<div class="doc-view">']
    for p in doc.paragraphs:
        style = _style(p)
        finding_ids = finding_map.get(p.index, [])
        attrs = [
            f'data-pi="{p.index}"',
            f'data-role="{escape(p.role or "")}"',
        ]
        if finding_ids:
            attrs.append(f'data-finding-ids="{escape(",".join(finding_ids))}"')
        if style:
            attrs.append(f'style="{escape(style)}"')
        out.append(f"<p {' '.join(attrs)}>{escape(p.text)}</p>")
    out.append("</div>")
    return "\n".join(out)
