"""Export manager for history data — Markdown and JSON formats."""

from __future__ import annotations

import json
import logging
import os
import time
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from .history import HistoryEntry

log = logging.getLogger(__name__)


class ExportManager:
    """Manages exporting history entries to Markdown and JSON files.

    Supports:
        - Markdown (.md): Human-readable with headers, timestamps, template names
        - JSON (.json): Machine-readable, full data including metadata
    """

    def __init__(self, entries: list[HistoryEntry] | None = None) -> None:
        self._entries = entries or []

    def set_entries(self, entries: list[HistoryEntry]) -> None:
        """Update the entries list (e.g. from HistoryManager.get_all())."""
        self._entries = entries

    @property
    def entries(self) -> list[HistoryEntry]:
        return list(self._entries)

    def to_markdown(self) -> str:
        """Export history entries as a Markdown string."""
        now = time.strftime("%Y-%m-%d %H:%M")
        count = len(self._entries)

        lines: list[str] = [
            "# MuraveyChina — Processing History",
            "",
            f"Exported: {now}",
            f"Entries: {count}",
            "",
            "---",
        ]

        for i, entry in enumerate(self._entries, start=1):
            template = entry.get("template", "unknown")
            provider = entry.get("provider", "unknown")
            entry_time = entry.get("time", "—")
            text = entry.get("text", "")
            result = entry.get("result", "")

            lines.append("")
            lines.append(f"## {i}. [{template}] — {provider}")
            lines.append(f"**Time:** {entry_time}")
            lines.append(f"**Input:** {text}")
            lines.append(f"**Output:** {result}")
            lines.append("")
            lines.append("---")

        lines.append("")
        return "\n".join(lines)

    def to_json(self) -> str:
        """Export history entries as a JSON string."""
        return json.dumps(self._entries, ensure_ascii=False, indent=2)

    def export_to_file(self, path: str, fmt: str = "md") -> str:
        """Write export to file.

        Args:
            path: File path to write to.
            fmt: Export format — "md" for Markdown, "json" for JSON.

        Returns:
            Path to the saved file.
        """
        from .utils.atomic_io import atomic_write_text

        if not path.endswith(f".{fmt}"):
            path = f"{path}.{fmt}"

        content = self.to_json() if fmt == "json" else self.to_markdown()
        atomic_write_text(path, content)
        log.info("History exported to %s (%d entries)", path, len(self._entries))
        return path

    @staticmethod
    def default_export_path(fmt: str = "md") -> str:
        """Get default export path in user's home directory."""
        ext = "json" if fmt == "json" else "md"
        filename = f"muravey_export_{time.strftime('%Y%m%d_%H%M%S')}.{ext}"
        return os.path.join(os.path.expanduser("~"), filename)
