# build_docs.py
import os
import sys
import subprocess

def build_documentation():
    """Build Sphinx documentation."""
    
    print("=" * 60)
    print("Building Rapha-Bethel BNPS Documentation")
    print("=" * 60)
    
    # Paths
    base_dir = os.path.dirname(os.path.abspath(__file__))
    docs_dir = os.path.join(base_dir, 'docs')
    source_dir = os.path.join(docs_dir, 'source')
    
    # Ensure source directory exists
    os.makedirs(source_dir, exist_ok=True)
    
    # Create minimal conf.py
    conf_path = os.path.join(source_dir, 'conf.py')
    print(f"📝 Creating {conf_path}...")
    with open(conf_path, 'w', encoding='utf-8') as f:
        f.write('''
# Minimal Sphinx configuration
import os
import sys
from pathlib import Path

# Add project to path
BASE_DIR = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(BASE_DIR))

project = 'Rapha-Bethel BNPS'
copyright = '2026, Vi-2s-Dk Foundation'
author = 'Vi-2s-Dk Foundation'
release = '1.0.0'

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
    'sphinx_rtd_theme',
]

# Mock all Django and app imports
autodoc_mock_imports = [
    'django',
    'django.db',
    'django.contrib',
    'django.utils',
    'django.conf',
    'PIL',
    'core',
    'students',
    'staff',
    'academics',
    'finance',
    'communication',
    'parents',
    'reports',
]

# Napoleon settings
napoleon_google_docstring = True
napoleon_include_init_with_doc = True

# HTML output
html_theme = 'sphinx_rtd_theme'
html_static_path = ['_static']
''')
    
    # Create index.rst
    index_path = os.path.join(source_dir, 'index.rst')
    print(f"📝 Creating {index_path}...")
    with open(index_path, 'w', encoding='utf-8') as f:
        f.write('''
Rapha-Bethel BNPS Documentation
===============================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   modules/index
''')
    
    # Create modules directory
    modules_dir = os.path.join(source_dir, 'modules')
    os.makedirs(modules_dir, exist_ok=True)
    
    # Create modules/index.rst
    modules_index = os.path.join(modules_dir, 'index.rst')
    print(f"📝 Creating {modules_index}...")
    with open(modules_index, 'w', encoding='utf-8') as f:
        f.write('''
Models Documentation
====================

Core Models
-----------

.. automodule:: core.models
   :members:
   :undoc-members:
   :show-inheritance:

Student Models
--------------

.. automodule:: students.models
   :members:
   :undoc-members:
   :show-inheritance:

Staff Models
------------

.. automodule:: staff.models
   :members:
   :undoc-members:
   :show-inheritance:

Academics Models
----------------

.. automodule:: academics.models
   :members:
   :undoc-members:
   :show-inheritance:

Finance Models
--------------

.. automodule:: finance.models
   :members:
   :undoc-members:
   :show-inheritance:

Communication Models
--------------------

.. automodule:: communication.models
   :members:
   :undoc-members:
   :show-inheritance:

Parent Portal Models
--------------------

.. automodule:: parents.models
   :members:
   :undoc-members:
   :show-inheritance:

Reports Models
--------------

.. automodule:: reports.models
   :members:
   :undoc-members:
   :show-inheritance:
''')
    
    # Remove any existing api directory that might be causing issues
    api_dir = os.path.join(source_dir, 'api')
    if os.path.exists(api_dir):
        print(f"🗑️ Removing problematic {api_dir}...")
        import shutil
        shutil.rmtree(api_dir)
    
    # Run sphinx-build
    try:
        build_dir = os.path.join(docs_dir, 'build', 'html')
        os.makedirs(build_dir, exist_ok=True)
        
        cmd = ['sphinx-build', '-b', 'html', source_dir, build_dir]
        print(f"🚀 Running: {' '.join(cmd)}")
        
        result = subprocess.run(cmd, capture_output=True, text=True)
        
        if result.returncode == 0:
            print("\n✅ Documentation built successfully!")
            print(f"📁 Output: {os.path.join(build_dir, 'index.html')}")
            print(f"🌐 Open in browser: file://{os.path.join(build_dir, 'index.html')}")
        else:
            print("\n❌ Build failed with errors:")
            print(result.stderr)
            
    except FileNotFoundError:
        print("❌ sphinx-build not found. Please install Sphinx:")
        print("   pip install sphinx sphinx-rtd-theme")
    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    build_documentation()