"""Markdown exporter implementation.

Export meeting transcripts to Markdown format.
"""

from __future__ import annotations

from datetime import datetime
from typing import TYPE_CHECKING

from noteflow.infrastructure.export._formatting import format_datetime, format_timestamp

if TYPE_CHECKING:
    from collections.abc import Sequence

    from noteflow.domain.entities.meeting import Meeting
    from noteflow.domain.entities.segment import Segment


class MarkdownExporter:
    """Export meeting transcripts to Markdown format.

    Produces clean, readable Markdown with meeting metadata header,
    transcript sections with timestamps, and optional summary section.
    """

    @property
    def format_name(self) -> str:
        """Human-readable format name."""
        return "Markdown"

    @property
    def file_extension(self) -> str:
        """File extension for Markdown."""
        return ".md"

    def export(
        self,
        meeting: Meeting,
        segments: Sequence[Segment],
    ) -> str:
        """Export meeting transcript to Markdown.

        Args:
            meeting: Meeting entity with metadata.
            segments: Ordered list of transcript segments.

        Returns:
            Markdown-formatted transcript string.
        """
        lines: list[str] = [
            f"# {meeting.title}",
            "",
            "## Meeting Info",
            "",
            f"- **Date:** {format_datetime(meeting.created_at)}",
        ]

        if meeting.started_at:
            lines.append(f"- **Started:** {format_datetime(meeting.started_at)}")
        if meeting.ended_at:
            lines.append(f"- **Ended:** {format_datetime(meeting.ended_at)}")
        lines.append(f"- **Duration:** {format_timestamp(meeting.duration_seconds)}")
        lines.extend((f"- **Segments:** {len(segments)}", "", "## Transcript", ""))
        for segment in segments:
            timestamp = format_timestamp(segment.start_time)
            lines.extend((f"**[{timestamp}]** {segment.text}", ""))
        # Summary section (if available)
        if meeting.summary:
            lines.extend(("## Summary", ""))
            if meeting.summary.executive_summary:
                lines.extend((meeting.summary.executive_summary, ""))
            if meeting.summary.key_points:
                lines.extend(("### Key Points", ""))
                lines.extend(f"- {point.text}" for point in meeting.summary.key_points)
                lines.append("")

            if meeting.summary.action_items:
                lines.extend(("### Action Items", ""))
                for item in meeting.summary.action_items:
                    assignee = f" (@{item.assignee})" if item.assignee else ""
                    lines.append(f"- [ ] {item.text}{assignee}")
                lines.append("")

        # Footer
        lines.append("---")
        lines.append(f"*Exported from NoteFlow on {format_datetime(datetime.now())}*")

        return "\n".join(lines)
