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

import datetime
from pathlib import Path
from typing import 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 _get_relative_path(
        self, path: str, base_path: Optional[Union[str, Path]] = None
    ) -> str:
        """Convert absolute path to relative path for display.

        Args:
            path: The path to convert
            base_path: Base path to make relative to (defaults to current directory)

        Returns:
            Relative path as string
        """
        if not path:
            return "unknown"

        try:
            path_obj = Path(path)
            base_path = Path(base_path) if base_path else Path.cwd()

            # If it's already a relative path, return as is
            if not path_obj.is_absolute():
                return str(path_obj)

            # Try to make it relative to the project
            rel_path = path_obj.relative_to(base_path)
            return str(rel_path)
        except (ValueError, TypeError):
            # If we can't make it relative, return just the filename
            return str(Path(path).name) if path else "unknown"

    def _format_source_link(
        self, source: str, base_path: Optional[Union[str, Path]] = None
    ) -> str:
        """Format source as a markdown link if it's a markdown file.

        Args:
            source: Source path to format
            base_path: Base path for relative paths

        Returns:
            Formatted source string with markdown link if applicable
        """
        if not source or source == "unknown":
            return source

        rel_path = self._get_relative_path(source, base_path)

        # Only create links for markdown files
        if str(rel_path).lower().endswith(".md"):
            return f"[{rel_path}]({rel_path})"
        return rel_path

    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", [])
        project_path = data.get("project_path")

        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"**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()):
            # Format source path for display
            display_source = self._format_source_link(source, project_path)
            content.extend([f"### 📄 From {display_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](TODO.md) for fixing",
                "",
                f"**Last test run:** {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
                "",
            ]
        )

        return "\n".join(content)
