"""markdown.py — the Markdown surface projector (text facet).

The most tractable surface, and the reference implementation: reads the IR's
realized sentences and lays them out as Markdown. Introduces no content — it is
pure typography over the faithful text the realizer produced.
"""
from __future__ import annotations

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from document_ir import DocumentIR  # noqa: E402
from projectors.base import register  # noqa: E402


class MarkdownProjector:
    surface = "markdown"
    media_type = "text/markdown"
    ext = "md"
    modality = "text"

    def render_str(self, doc: DocumentIR) -> str:
        lines: list[str] = [f"# {doc.title}"]
        if doc.subtitle:
            lines.append(f"\n*{doc.subtitle}*")
        abstract = doc.meta.get("abstract")
        if abstract is not None and abstract.sentences:
            lines.append("")
            lines.append(abstract.text())
        for sec in doc.sections:
            lines.append("")
            lines.append(f"{'#' * max(2, sec.level)} {sec.heading}")
            for block in sec.blocks:
                body = block.text()
                if body:
                    lines.append("")
                    lines.append(body)
        return "\n".join(lines) + "\n"

    def project(self, doc: DocumentIR) -> bytes:
        return self.render_str(doc).encode("utf-8")


register(MarkdownProjector())
