"""
Module: src.export.markdown_exporter
Workorder: WO01
Purpose: Markdown transcript export for documentation workflows.

Dependencies:
    - pathlib: File path handling

Inputs:
    - transcript: Transcript text
    - target_path: Output path

Outputs:
    - Markdown transcript file on disk

Key Functions/Classes:
    - export_markdown: Writes Markdown output

Tests: tests/unit/test_placeholder.py
"""
from pathlib import Path
from typing import Any


def _render_frontmatter(frontmatter: dict[str, Any] | None) -> str:
    if not frontmatter:
        return ""

    lines = ["---"]
    for key, value in frontmatter.items():
        if isinstance(value, list):
            lines.append(f"{key}:")
            for item in value:
                lines.append(f"  - {item}")
        else:
            lines.append(f"{key}: {value}")
    lines.append("---")
    return "\n".join(lines).strip()


def export_markdown(
    transcript: str,
    target_path: Path,
    summary_text: str | None = None,
    frontmatter: dict[str, Any] | None = None,
) -> None:
    """Export transcript text as Markdown.

    Args:
        transcript: Transcript text.
        target_path: Output path.
        summary_text: Optional summary block to prepend.
        frontmatter: Optional YAML frontmatter metadata.

    Raises:
        OSError: If write operation fails.
    """
    target_path.parent.mkdir(parents=True, exist_ok=True)
    sections: list[str] = []
    frontmatter_block = _render_frontmatter(frontmatter)
    if frontmatter_block:
        sections.append(frontmatter_block)

    if summary_text and summary_text.strip():
        sections.append("# Zusammenfassung\n\n" + summary_text.strip())

    sections.append("# Transkript\n\n" + transcript.strip())
    content = "\n\n".join(sections).strip() + "\n"
    with target_path.open("w", encoding="utf-8") as file:
        file.write(content)
