from collections import defaultdict
from datetime import date

from ..models import LogEntry


class MarkdownFormatter:
    log_format = "%Y-%m-%d"
    footer = "\n\n*Proudly generated by BragLog™*"

    def __init__(self, entries: list[LogEntry]) -> None:
        self.entries = entries

    def _get_entries_by_date(self) -> dict[int, dict[str, dict[date, list[str]]]]:
        entries_by_date = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
        for entry in self.entries:
            year: int = entry.log_date.year
            month: str = entry.log_date.strftime("%B")

            entries_by_date[year][month][entry.log_date].append(entry.message)
        return entries_by_date

    def __str__(self) -> str:
        markdown_sections = []

        for year, month_dict in self._get_entries_by_date().items():
            markdown_sections.append(f"# {year}")

            for month, days_dict in month_dict.items():
                markdown_sections.append(f"## {month}")

                for day, messeages in days_dict.items():
                    markdown_sections.append(f"- {day.strftime(self.log_format)}")
                    markdown_sections.extend(f"    - {msg}" for msg in messeages)

        return "\n".join(markdown_sections) + self.footer
