"""HTML exporter implementation.

Export meeting transcripts to HTML format.
"""

from __future__ import annotations

from datetime import datetime
from typing import TYPE_CHECKING

from noteflow.config.constants import EXPORT_EXT_HTML, EXPORT_FORMAT_HTML
from noteflow.infrastructure.export._formatting import (
    escape_html,
    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
    from noteflow.domain.entities.summary import Summary


# CSS styles for print-friendly HTML output
_HTML_STYLES = """
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            line-height: 1.6;
            max-width: 800px;
            margin: 0 auto;
            padding: 2rem;
            color: #333;
        }
        h1 { color: #1a1a1a; border-bottom: 2px solid #e0e0e0; padding-bottom: 0.5rem; }
        h2 { color: #2c2c2c; margin-top: 2rem; }
        h3 { color: #444; }
        .metadata { background: #f5f5f5; padding: 1rem; border-radius: 8px; margin-bottom: 2rem; }
        .metadata dt { font-weight: bold; display: inline; }
        .metadata dd { display: inline; margin: 0 1rem 0 0.5rem; }
        .transcript { margin: 1rem 0; }
        .segment { margin-bottom: 1rem; padding: 0.5rem; border-left: 3px solid #e0e0e0; }
        .segment:hover { background: #f9f9f9; }
        .timestamp { color: #666; font-size: 0.9em; font-weight: bold; margin-right: 0.5rem; }
        .summary { background: #f0f7ff; padding: 1rem; border-radius: 8px; margin-top: 2rem; }
        .key-points li, .action-items li { margin-bottom: 0.5rem; }
        .action-items li { list-style-type: none; }
        .action-items li::before { content: '☐ '; }
        .assignee { color: #0066cc; font-size: 0.9em; }
        footer { margin-top: 3rem; padding-top: 1rem; border-top: 1px solid #e0e0e0; color: #888; font-size: 0.9em; }
        @media print {
            body { max-width: none; padding: 1cm; }
            .segment:hover { background: none; }
        }
"""


def _build_html_document(title: str, content: str) -> str:
    """Build complete HTML document with title and content."""
    return f"""<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <style>{_HTML_STYLES}    </style>
</head>
<body>
{content}
</body>
</html>"""


def _build_metadata_html(meeting: Meeting, segment_count: int) -> list[str]:
    """Build HTML for meeting metadata section."""
    parts: list[str] = [
        '<div class="metadata">',
        "<dl>",
        f"<dt>Date:</dt><dd>{escape_html(format_datetime(meeting.created_at))}</dd>",
    ]
    if meeting.started_at:
        parts.append(
            f"<dt>Started:</dt><dd>{escape_html(format_datetime(meeting.started_at))}</dd>"
        )
    if meeting.ended_at:
        parts.append(
            f"<dt>Ended:</dt><dd>{escape_html(format_datetime(meeting.ended_at))}</dd>"
        )
    parts.extend(
        (
            f"<dt>Duration:</dt><dd>{format_timestamp(meeting.duration_seconds)}</dd>",
            f"<dt>Segments:</dt><dd>{segment_count}</dd>",
            "</dl>",
            "</div>",
        )
    )
    return parts


def _build_transcript_html(segments: Sequence[Segment]) -> list[str]:
    """Build HTML for transcript section."""
    parts: list[str] = ["<h2>Transcript</h2>", '<div class="transcript">']
    for segment in segments:
        timestamp = format_timestamp(segment.start_time)
        parts.extend(
            (
                '<div class="segment">',
                f'<span class="timestamp">[{timestamp}]</span>',
                f"<span>{escape_html(segment.text)}</span>",
                "</div>",
            )
        )
    parts.append("</div>")
    return parts


def _build_summary_html(summary: Summary) -> list[str]:
    """Build HTML for summary section."""
    parts: list[str] = ['<div class="summary">', "<h2>Summary</h2>"]
    if summary.executive_summary:
        parts.append(f"<p>{escape_html(summary.executive_summary)}</p>")

    if summary.key_points:
        parts.extend(("<h3>Key Points</h3>", '<ul class="key-points">'))
        parts.extend(
            f"<li>{escape_html(point.text)}</li>" for point in summary.key_points
        )
        parts.append("</ul>")

    if summary.action_items:
        parts.extend(("<h3>Action Items</h3>", '<ul class="action-items">'))
        for item in summary.action_items:
            assignee = (
                f' <span class="assignee">@{escape_html(item.assignee)}</span>'
                if item.assignee
                else ""
            )
            parts.append(f"<li>{escape_html(item.text)}{assignee}</li>")
        parts.append("</ul>")

    parts.append("</div>")
    return parts


class HtmlExporter:
    """Export meeting transcripts to HTML format.

    Produces clean, print-friendly HTML with embedded CSS styling,
    meeting metadata, transcript with timestamps, and optional summary.
    """

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

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

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

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

        Returns:
            HTML-formatted transcript string.
        """
        content_parts: list[str] = [f"<h1>{escape_html(meeting.title)}</h1>"]
        content_parts.extend(_build_metadata_html(meeting, len(segments)))
        content_parts.extend(_build_transcript_html(segments))

        if meeting.summary:
            content_parts.extend(_build_summary_html(meeting.summary))

        content_parts.extend(
            (
                "<footer>",
                f"Exported from NoteFlow on {escape_html(format_datetime(datetime.now()))}",
                "</footer>",
            )
        )
        content = "\n".join(content_parts)
        return _build_html_document(title=escape_html(meeting.title), content=content)
