"""Markdown exporter for chronobox reports.

Generates Markdown documents compatible with GitHub, MkDocs, and Jupyter.
"""

from __future__ import annotations

from typing import Any


class MarkdownExporter:
    """Export report context to Markdown document.

    Features:
    - Standard Markdown tables
    - Image references for plots
    - Compatible with GitHub Flavored Markdown
    - Compatible with MkDocs
    - Clean, readable output
    """

    def export(self, context: dict[str, Any]) -> str:
        """Export context to Markdown string.

        Parameters
        ----------
        context : dict
            Template context from a transformer.

        Returns
        -------
        str
            Markdown document.
        """
        title = context.get("title", "Report")
        sections = context.get("sections", [])
        model_info = context.get("model_info", {})

        parts = [f"# {title}", ""]

        # Model info
        if model_info:
            parts.append("## Model Information")
            parts.append("")
            for key, value in model_info.items():
                label = key.replace("_", " ").title()
                parts.append(f"- **{label}**: {value}")
            parts.append("")

        # Sections
        for section in sections:
            sec_title = section.get("title", "Section")
            content = section.get("content", "")
            table = section.get("table")
            plot = section.get("plot")

            parts.append(f"## {sec_title}")
            parts.append("")

            if content:
                parts.append(str(content))
                parts.append("")

            if table:
                parts.append(self._table_to_markdown(table))
                parts.append("")

            if plot:
                parts.append(f"![{sec_title}](data:image/png;base64,{plot})")
                parts.append("")

        # Footer
        parts.append("---")
        parts.append("")
        parts.append("*Generated by chronobox*")

        return "\n".join(parts)

    def _table_to_markdown(self, table: list[dict[str, Any]]) -> str:
        """Convert table data to Markdown table.

        Parameters
        ----------
        table : list[dict]
            Table rows.

        Returns
        -------
        str
            Markdown table.
        """
        if not table:
            return ""

        headers = list(table[0].keys())

        # Compute column widths
        widths: dict[str, int] = {}
        for h in headers:
            widths[h] = len(str(h))
            for row in table:
                val = row.get(h, "")
                val_str = f"{val:.4f}" if isinstance(val, float) else str(val)
                widths[h] = max(widths[h], len(val_str))

        # Header
        header_cells = [str(h).ljust(widths[h]) for h in headers]
        header_line = "| " + " | ".join(header_cells) + " |"

        # Separator
        sep_cells = []
        for h in headers:
            # Right-align numeric columns
            if table and isinstance(table[0].get(h), (int, float)):
                sep_cells.append("-" * (widths[h] - 1) + ":")
            else:
                sep_cells.append("-" * widths[h])
        sep_line = "| " + " | ".join(sep_cells) + " |"

        # Data rows
        data_lines = []
        for row in table:
            cells = []
            for h in headers:
                val = row.get(h, "")
                val_str = f"{val:.4f}" if isinstance(val, float) else str(val)
                cells.append(val_str.ljust(widths[h]))
            data_lines.append("| " + " | ".join(cells) + " |")

        return "\n".join([header_line, sep_line, *data_lines])
