"""Markdown output formatter."""

from datetime import date
from typing import List, Optional
from ..models import RuleSuggestion, FailureRecord


def format_markdown(
    suggestions: List[RuleSuggestion],
    records: List[FailureRecord],
    source_label: str = "",
) -> str:
    """Format suggestions as a markdown report."""
    today = date.today().isoformat()
    lines = [
        f"## agentreflect suggestions ({today})",
        "",
    ]

    if source_label:
        lines.append(f"### From: {source_label}")
        lines.append("")

    if not suggestions:
        lines.append("_No suggestions generated. Try adding more failure context._")
        lines.append("")
    else:
        for suggestion in suggestions:
            lines.append(suggestion.as_markdown_item())
        lines.append("")

    # Summary line
    n_failures = len(records)
    n_suggestions = len(suggestions)
    failure_word = "failure" if n_failures == 1 else "failures"
    suggestion_word = "suggestion" if n_suggestions == 1 else "suggestions"
    lines.append(
        f"_Source: {n_failures} {failure_word} analyzed, {n_suggestions} {suggestion_word} generated_"
    )
    lines.append("")

    return "\n".join(lines)
