"""Markdown reporter for DONE.md generation."""

import datetime
from pathlib import Path
from typing import Dict, Optional, Union

from .base import BaseReporter


class DoneMDReporter(BaseReporter):
    """Generates a DONE.md file with successfully executed commands."""

    def __init__(self, output_file: Optional[Union[str, Path]] = None):
        """Initialize the DONE.md reporter.

        Args:
            output_file: Path to the DONE.md file
        """
        super().__init__(output_file or "DONE.md")

    def generate_report(self, data: Dict) -> str:
        """Generate the DONE.md content.

        Args:
            data: Dictionary containing 'successful_commands' and other metadata

        Returns:
            Formatted markdown content
        """
        successful_commands = data.get("successful_commands", [])

        content = [
            "# ✅ DONE - Successfully Working Commands",
            "",
            "**🎉 Generated by TodoMD** - List of all working project commands",
            f"**Last Updated:** {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
            f"**Project:** {data.get('project_path', 'Unknown')}",
            f"**Total Working Commands:** {len(successful_commands)}",
            "",
            "---",
            "",
            "## 📊 Summary",
            "",
            f"✅ **{len(successful_commands)} commands are working correctly**",
            "",
            "These commands have been tested and are functioning properly.",
            "You can safely use them in your development workflow.",
            "",
            "---",
            "",
            "## 🟢 Working Commands",
            "",
        ]

        # Group commands by source for better organization
        by_source = {}
        for cmd in successful_commands:
            source = cmd.get("source", "Other")
            if source not in by_source:
                by_source[source] = []
            by_source[source].append(cmd)

        for source, source_commands in sorted(by_source.items()):
            content.extend([f"### 📄 From {source}", ""])

            for cmd in source_commands:
                execution_time = cmd.get("execution_time", 0)
                content.extend(
                    [
                        f"#### ✅ {cmd.get('description', 'Unnamed command')}",
                        "",
                        f"**Command:** `{cmd.get('command', '')}`",
                        f"**Execution Time:** {execution_time:.2f}s",
                        f"**Type:** {cmd.get('type', 'unknown')}",
                        "",
                        "**Status:** 🟢 **WORKING**",
                        "",
                        "---",
                        "",
                    ]
                )

        content.extend(
            [
                "",
                "## 🔄 Updating This File",
                "",
                "This file is automatically updated when commands are tested.",
                "To refresh the status:",
                "",
                "1. Run: `domd` to test all commands",
                "2. Working commands will appear here",
                "3. Failed commands will be moved to TODO.md for fixing",
                "",
                f"**Last test run:** {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
                "",
            ]
        )

        return "\n".join(content)
