"""Markdown exporter for daily plans."""

import logging
from datetime import datetime
from pathlib import Path

import aiofiles

from ...domain.models.planning import Plan, ScheduleItem

logger = logging.getLogger(__name__)


class MarkdownExporter:
    """Export plans to Markdown format with checkboxes for manual tracking."""

    def _format_date_header(self, date_str: str) -> str:
        """Convert YYYY-MM-DD to human-readable format."""
        try:
            date = datetime.strptime(date_str, "%Y-%m-%d")
            return date.strftime("%B %d, %Y")  # e.g., "January 22, 2026"
        except ValueError:
            return date_str

    def _format_duration(self, minutes: int | None) -> str:
        """Format minutes as human-readable duration."""
        if not minutes:
            return ""
        hours = minutes // 60
        mins = minutes % 60
        if hours > 0 and mins > 0:
            return f"{hours}h {mins}m"
        elif hours > 0:
            return f"{hours}h"
        else:
            return f"{mins}m"

    def _format_priority_tag(self, priority: str) -> str:
        """Format priority as a tag."""
        priority = priority.lower()
        if priority == "high":
            return "[high]"
        elif priority == "medium":
            return "[medium]"
        elif priority == "low":
            return "[low]"
        return f"[{priority}]"

    def _format_schedule_item(self, item: ScheduleItem) -> str:
        """Format a single schedule item as a Markdown checkbox line."""
        parts = [f"- [ ] **{item.time}**", f"- {item.task}"]

        # Add duration estimate if available
        duration = item.estimated_minutes or item.extract_duration()
        if duration:
            parts.append(f"(~{self._format_duration(duration)})")

        # Add priority tag
        if item.priority and item.priority != "medium":
            parts.append(self._format_priority_tag(item.priority))

        return " ".join(parts)

    def to_string(self, plan: Plan, date_str: str | None = None) -> str:
        """
        Convert plan to Markdown string with checkboxes.

        Args:
            plan: Plan to export
            date_str: Date string (YYYY-MM-DD) for the header

        Returns:
            Markdown-formatted string
        """
        lines = []

        # Header
        if date_str:
            date_header = self._format_date_header(date_str)
            lines.append(f"# Daily Plan - {date_header}")
        else:
            lines.append("# Daily Plan")
        lines.append("")

        # Schedule section
        lines.append("## Schedule")
        lines.append("")

        if plan.schedule:
            for item in plan.schedule:
                lines.append(self._format_schedule_item(item))
        else:
            lines.append("*No tasks scheduled*")
        lines.append("")

        # Priorities section
        lines.append("## Top Priorities")
        lines.append("")

        if plan.priorities:
            for i, priority in enumerate(plan.priorities, 1):
                lines.append(f"{i}. {priority}")
        else:
            lines.append("*No priorities set*")
        lines.append("")

        # Notes section
        lines.append("## Notes")
        lines.append("")

        if plan.notes:
            lines.append(plan.notes)
        else:
            lines.append("*No notes*")
        lines.append("")

        # Footer
        lines.append("---")
        lines.append("*Generated by Daily Planning Assistant*")

        # Add total estimated time
        total_duration = plan.calculate_total_duration()
        if total_duration:
            lines.append(f"*Total estimated time: {self._format_duration(total_duration)}*")

        return "\n".join(lines)

    async def export(self, plan: Plan, output_path: Path, date_str: str | None = None) -> Path:
        """
        Export plan to Markdown file.

        Args:
            plan: Plan to export
            output_path: Path to write the file
            date_str: Date string for the header

        Returns:
            Path to the created file
        """
        # Ensure parent directory exists
        output_path.parent.mkdir(parents=True, exist_ok=True)

        # Generate markdown content
        content = self.to_string(plan, date_str)

        # Write to file
        async with aiofiles.open(output_path, "w", encoding="utf-8") as f:
            await f.write(content)

        logger.info(f"Exported plan to {output_path}")
        return output_path
