"""CLI for documentation: ``pycharter docs serve`` and ``pycharter docs build``.

Delegates to MkDocs. Run from the project root (where mkdocs.yml lives), or set
DOCS_ROOT to that directory. Requires: pip install pycharter[docs]
"""

from __future__ import annotations

import os
import subprocess
import sys
from pathlib import Path


def _get_docs_root() -> Path | None:
    """Return the directory containing mkdocs.yml, or None if not found."""
    env_root = os.environ.get("DOCS_ROOT")
    if env_root:
        p = Path(env_root).resolve()
        if (p / "mkdocs.yml").exists():
            return p
        return None

    cwd = Path.cwd()
    if (cwd / "mkdocs.yml").exists():
        return cwd

    try:
        import pycharter

        start = Path(pycharter.__file__).resolve().parent
    except (ImportError, AttributeError):
        return None

    current = start
    for _ in range(10):
        if (current / "mkdocs.yml").exists():
            return current
        parent = current.parent
        if parent == current:
            break
        current = parent

    return None


# Default port for ``docs serve``; aligned with API (8002) and UI (3002).
DEFAULT_DOCS_PORT = 5002


def cmd_docs_serve(host: str = "127.0.0.1", port: int = DEFAULT_DOCS_PORT) -> int:
    """Run ``mkdocs serve`` for local preview."""
    root = _get_docs_root()
    if not root:
        print(
            "❌ mkdocs.yml not found. Run from the project root (where mkdocs.yml lives), "
            "or set DOCS_ROOT to that directory.",
            file=sys.stderr,
        )
        return 1

    try:
        subprocess.run(
            [sys.executable, "-m", "mkdocs", "serve", "-a", f"{host}:{port}"],
            cwd=str(root),
            check=True,
        )
    except FileNotFoundError:
        print(
            "❌ MkDocs not found. Install with: pip install pycharter[docs]",
            file=sys.stderr,
        )
        return 1
    except subprocess.CalledProcessError as e:
        return e.returncode

    return 0


def cmd_docs_build() -> int:
    """Run ``mkdocs build`` to produce the static site."""
    root = _get_docs_root()
    if not root:
        print(
            "❌ mkdocs.yml not found. Run from the project root (where mkdocs.yml lives), "
            "or set DOCS_ROOT to that directory.",
            file=sys.stderr,
        )
        return 1

    try:
        subprocess.run(
            [sys.executable, "-m", "mkdocs", "build"],
            cwd=str(root),
            check=True,
        )
    except FileNotFoundError:
        print(
            "❌ MkDocs not found. Install with: pip install pycharter[docs]",
            file=sys.stderr,
        )
        return 1
    except subprocess.CalledProcessError as e:
        return e.returncode

    return 0
