"""Doc command implementation for MakePython."""

from __future__ import annotations

from typing import TYPE_CHECKING

from ...core.executor import execute_command_with_context
from ...interfaces.command import CommandResult, CommandType, ValidatableCommand

if TYPE_CHECKING:
    from ...core.context import ExecutionContext


class DocCommand(ValidatableCommand):
    """Generate Sphinx HTML documentation including API docs."""

    name = "doc"
    alias = "doc"
    description = "Generate Sphinx HTML documentation including API docs"
    command_type = CommandType.UTIL

    def validate(self, context: ExecutionContext) -> bool:
        """Validate doc command prerequisites.

        Args:
            context: Execution context

        Returns
        -------
            True if validation passes, False otherwise
        """
        # Check if sphinx is available
        result = execute_command_with_context(["sphinx-build", "--version"], context)
        if not result.success:
            self.logger.warning("Sphinx not found")
            self.logger.info("Install with: pip install sphinx sphinx-autodoc-typehints")
            return False

        return True

    def _generate_api_docs(self, context: ExecutionContext) -> bool:
        """Generate API documentation using sphinx-apidoc.

        Args:
            context: Execution context

        Returns
        -------
            True if successful, False otherwise
        """
        try:
            # Find project package directory
            project_root = context.project_root or context.cwd

            # Look for main package (directory with __init__.py)
            packages = []
            for item in project_root.iterdir():
                if item.is_dir() and not item.name.startswith((".", "_")):
                    if (item / "__init__.py").exists():
                        packages.append(item)

            if not packages:
                self.logger.warning("No Python package found for API doc generation")
                return False

            # Generate API docs for first package found
            package_dir = packages[0]
            docs_dir = project_root / "docs" / "api"

            self.logger.info(f"Generating API docs for {package_dir.name}...")

            result = execute_command_with_context(
                ["sphinx-apidoc", "-o", str(docs_dir), str(package_dir), "--force"], context
            )

            if result.success:
                self.logger.info(f"API docs generated in {docs_dir}")
                return True
            self.logger.warning("API doc generation had issues")
            return False

        except Exception as e:
            self.logger.error(f"API doc generation failed: {e}")
            return False

    def execute(self, context: ExecutionContext) -> CommandResult:
        """Execute doc command.

        Args:
            context: Execution context

        Returns
        -------
            CommandResult with execution status
        """
        if not self.validate(context):
            return CommandResult(success=False, message="Validation failed")

        self.logger.info("Generating Sphinx documentation...")

        project_root = context.project_root or context.cwd
        docs_dir = project_root / "docs"

        # Check if docs directory exists
        if not docs_dir.exists():
            self.logger.info("Creating docs directory...")
            docs_dir.mkdir(parents=True, exist_ok=True)

            # Create basic conf.py if it doesn't exist
            conf_path = docs_dir / "conf.py"
            if not conf_path.exists():
                self.logger.info("Creating basic Sphinx configuration...")
                conf_content = """# Sphinx configuration
project = 'Project'
extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
    'sphinx_autodoc_typehints',
]
html_theme = 'alabaster'
"""
                conf_path.write_text(conf_content, encoding="utf-8")

        # Generate API docs
        self._generate_api_docs(context)

        # Build HTML documentation
        build_dir = docs_dir / "_build"

        self.logger.info("Building HTML documentation...")
        result = execute_command_with_context(["sphinx-build", "-b", "html", str(docs_dir), str(build_dir)], context)

        if result.success:
            self.logger.info(f"Documentation built successfully in {build_dir}")

            # Try to open in browser
            index_html = build_dir / "index.html"
            if index_html.exists():
                import webbrowser
                from urllib.request import pathname2url

                webbrowser.open("file://" + pathname2url(str(index_html)))
                self.logger.info("Documentation opened in browser")

            return CommandResult(success=True, message="Documentation generated successfully")
        self.logger.error("Documentation build failed")
        return CommandResult(success=False, message="Documentation build failed")
