# AUTO-GENERATED FILE - DO NOT EDIT
# This file was automatically generated by the XDK build tool.
# Any manual changes will be overwritten on the next generation.
#!/usr/bin/env python3
"""
AUTO-GENERATED FILE - DO NOT EDIT
This file was automatically generated by the XDK build tool.
Any manual changes will be overwritten on the next generation.

Generate API documentation for the Python SDK using Sphinx with markdown output.
"""

import os
import sys
import shutil
import subprocess
from pathlib import Path

print("🚀 Generating X API SDK Documentation...")

# Try to use virtual environment if available
venv_python = Path(".venv") / "bin" / "python"
if venv_python.exists():
    print("📦 Using virtual environment...")
    python_exe = str(venv_python)
else:
    python_exe = sys.executable

# Configuration
DOCS_DIR = Path("docs")
SPHINX_SOURCE_DIR = Path("docs_source")
SPHINX_BUILD_DIR = DOCS_DIR / "_build"
SPHINX_MARKDOWN_DIR = DOCS_DIR

# Clean up old docs
if DOCS_DIR.exists():
    shutil.rmtree(DOCS_DIR)
DOCS_DIR.mkdir(parents=True, exist_ok=True)

# Clean up old source
if SPHINX_SOURCE_DIR.exists():
    shutil.rmtree(SPHINX_SOURCE_DIR)

# Create Sphinx source directory structure
SPHINX_SOURCE_DIR.mkdir(parents=True, exist_ok=True)
(SPHINX_SOURCE_DIR / "_static").mkdir(exist_ok=True)
(SPHINX_SOURCE_DIR / "_templates").mkdir(exist_ok=True)

# Copy conf.py from root (should be generated)
conf_py_path = Path("conf.py")
if conf_py_path.exists():
    shutil.copy(conf_py_path, SPHINX_SOURCE_DIR / "conf.py")
else:
    print("⚠️  Warning: conf.py not found. Sphinx may not work correctly.")

try:
    # Use sphinx-apidoc to auto-generate API documentation
    print("📚 Running sphinx-apidoc to generate API documentation structure...")
    apidoc_cmd = [
        python_exe,
        "-m",
        "sphinx.ext.apidoc",
        "-o",
        str(SPHINX_SOURCE_DIR),
        "-f",  # Force overwrite
        "--separate",  # Put each module in its own file
        "xdk",  # Source package
    ]

    subprocess.run(apidoc_cmd, check=True, capture_output=True, text=True)

    # Create or update index.rst
    index_content = """X API SDK Documentation
==========================

Welcome to the X API SDK documentation.

.. toctree::
   :maxdepth: 2
   :caption: API Reference:

   modules

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
"""

    (SPHINX_SOURCE_DIR / "index.rst").write_text(index_content)

    # Run Sphinx with markdown builder
    print("📚 Running Sphinx to generate markdown documentation...")

    sphinx_cmd = [
        python_exe,
        "-m",
        "sphinx",
        "-b",
        "markdown",  # Use markdown builder
        str(SPHINX_SOURCE_DIR),
        str(SPHINX_MARKDOWN_DIR),
    ]

    result = subprocess.run(sphinx_cmd, check=True, capture_output=True, text=True)
    print("✅ Documentation generated successfully in docs/")

    # Clean up build directory
    if SPHINX_BUILD_DIR.exists():
        shutil.rmtree(SPHINX_BUILD_DIR)

    # Clean up source directory
    if SPHINX_SOURCE_DIR.exists():
        shutil.rmtree(SPHINX_SOURCE_DIR)

except subprocess.CalledProcessError as e:
    print(f"❌ Documentation generation failed: {e}")
    if e.stdout:
        print(f"stdout: {e.stdout}")
    if e.stderr:
        print(f"stderr: {e.stderr}")
    sys.exit(1)
except FileNotFoundError:
    print("❌ Sphinx not found.")
    print("💡 Installing dependencies...")
    try:
        # Try to install using uv if available
        if shutil.which("uv"):
            subprocess.run(
                ["uv", "pip", "install", "-e", ".[dev]"], check=True, shell=False
            )
        else:
            # Fallback to pip
            subprocess.run(
                [
                    sys.executable,
                    "-m",
                    "pip",
                    "install",
                    "sphinx",
                    "myst-parser",
                    "sphinx-markdown-builder",
                ],
                check=True,
            )
        print("✅ Dependencies installed. Please run the script again.")
    except subprocess.CalledProcessError:
        print("❌ Failed to install dependencies automatically.")
        print("💡 Please install manually with:")
        print("   uv pip install -e '.[dev]'")
        print("   or")
        print("   pip install sphinx myst-parser sphinx-markdown-builder")
    sys.exit(1)
except ImportError as e:
    if "myst_parser" in str(e) or "myst-parser" in str(e):
        print("❌ myst-parser not found.")
        print("💡 Installing dependencies...")
        try:
            if shutil.which("uv"):
                subprocess.run(
                    ["uv", "pip", "install", "-e", ".[dev]"], check=True, shell=False
                )
            else:
                subprocess.run(
                    [
                        sys.executable,
                        "-m",
                        "pip",
                        "install",
                        "myst-parser",
                        "sphinx-markdown-builder",
                    ],
                    check=True,
                )
            print("✅ Dependencies installed. Please run the script again.")
        except subprocess.CalledProcessError:
            print("❌ Failed to install dependencies automatically.")
            print("💡 Please install manually with:")
            print("   uv pip install -e '.[dev]'")
    else:
        raise
    sys.exit(1)
