"""Markdown export service."""

from datetime import datetime


def create_markdown(title: str, text: str, metadata: dict = None) -> str:
    """
    Create a Markdown document from transcription text.

    Args:
        title: Document title
        text: Transcription text content
        metadata: Optional dict with url, duration, created_at, etc.

    Returns:
        Markdown formatted string
    """
    lines = []

    # YAML frontmatter
    lines.append("---")
    lines.append(f"title: \"{title}\"")
    if metadata:
        if metadata.get('url'):
            lines.append(f"source: \"{metadata['url']}\"")
        if metadata.get('duration'):
            lines.append(f"duration: \"{metadata['duration']}\"")
        if metadata.get('created_at'):
            lines.append(f"transcribed: \"{metadata['created_at']}\"")
    lines.append(f"exported: \"{datetime.now().strftime('%Y-%m-%d %H:%M')}\"")
    lines.append("---")
    lines.append("")

    # Title
    lines.append(f"# {title}")
    lines.append("")

    # Metadata section
    if metadata:
        meta_parts = []
        if metadata.get('url'):
            meta_parts.append(f"**Source:** [{metadata['url']}]({metadata['url']})")
        if metadata.get('duration'):
            meta_parts.append(f"**Duration:** {metadata['duration']}")
        if metadata.get('created_at'):
            meta_parts.append(f"**Transcribed:** {metadata['created_at']}")
        if meta_parts:
            lines.append(" | ".join(meta_parts))
            lines.append("")

    lines.append("---")
    lines.append("")

    # Transcription content
    lines.append("## Transcription")
    lines.append("")

    # Split into paragraphs and add proper formatting
    paragraphs = text.split('\n\n')
    for para in paragraphs:
        if para.strip():
            lines.append(para.strip())
            lines.append("")

    return "\n".join(lines)
