"""
Module: server
Description: Local documentation server with MCP endpoint

Implements:
    - docs/guides/developer-environment.md#documentation-server
"""

import logging
import subprocess
from pathlib import Path
from typing import Any, Optional

logger = logging.getLogger(__name__)


class DocsServer:
    """Local documentation server.

    Serves docs from github.com/Huitzo-Inc/docs at localhost:8124
    Provides MCP endpoint for AI agents.
    """

    def __init__(self, docs_dir: Optional[Path] = None, port: int = 8124) -> None:
        """Initialize docs server.

        Args:
            docs_dir: Directory containing docs (default: cloned from GitHub)
            port: Port to serve docs on
        """
        self.port = port
        self.docs_dir = docs_dir or Path.home() / ".huitzo" / "docs"
        self.process: Optional[subprocess.Popen[bytes]] = None

    def ensure_docs(self) -> Path:
        """Ensure docs are available locally.

        Clones from GitHub if not already present.

        Returns:
            Path to docs directory
        """
        if not self.docs_dir.exists():
            self.docs_dir.parent.mkdir(parents=True, exist_ok=True)

            try:
                subprocess.run(
                    [
                        "git",
                        "clone",
                        "https://github.com/Huitzo-Inc/docs.git",
                        str(self.docs_dir),
                    ],
                    check=True,
                    capture_output=True,
                )
            except subprocess.CalledProcessError as e:
                raise RuntimeError(f"Failed to clone docs: {e}")
        else:
            # Update existing docs
            result = subprocess.run(
                ["git", "-C", str(self.docs_dir), "pull"],
                check=False,
                capture_output=True,
            )
            if result.returncode != 0:
                logger.warning(
                    "docs update failed (exit %d), using cached version", result.returncode
                )

        return self.docs_dir

    def start(self) -> None:
        """Start docs server.

        Raises:
            RuntimeError: If server fails to start
        """
        docs_dir = self.ensure_docs()

        try:
            # Start simple HTTP server
            self.process = subprocess.Popen(
                [
                    "python",
                    "-m",
                    "http.server",
                    str(self.port),
                    "--bind",
                    "127.0.0.1",
                    "--directory",
                    str(docs_dir),
                ],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
        except FileNotFoundError as e:
            raise RuntimeError(f"Failed to start server: {e}")

    def stop(self) -> None:
        """Stop docs server."""
        if self.process:
            self.process.terminate()
            try:
                self.process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                self.process.kill()
            self.process = None

    def get_mcp_manifest(self) -> dict[str, Any]:
        """Get MCP manifest for AI integration.

        Returns:
            MCP manifest for documentation access
        """
        return {
            "name": "Huitzo Documentation Server",
            "version": "1.0",
            "url": f"http://localhost:{self.port}",
            "endpoints": {
                "files": f"http://localhost:{self.port}/files",
            },
        }

    def is_running(self) -> bool:
        """Check if server is running.

        Returns:
            True if server is running, False otherwise
        """
        if self.process is None:
            return False
        return self.process.poll() is None
