#!/usr/bin/env python3
"""
Build documentation
"""
import os
import shutil
import subprocess
import sys

def run_command(cmd, description, cwd=None):
    """Run a command and exit if it fails"""
    print(f"Running: {description}")
    result = subprocess.run(cmd, shell=True, cwd=cwd, capture_output=True, text=True)
    
    if result.returncode != 0:
        print(f"Error: {description} failed with exit code {result.returncode}")
        if result.stdout:
            print("STDOUT:", result.stdout)
        if result.stderr:
            print("STDERR:", result.stderr)
        sys.exit(result.returncode)
    
    print(f"Success: {description}")
    return result

def main():
    script_dir = os.path.dirname(os.path.realpath(__file__))
    
    # Change to script directory and run config-toml-to-md.py
    print("Building configuration documentation...")
    run_command('python3 config-toml-to-md.py > ../doc/configuration.md', 
                "config-toml-to-md.py", cwd=script_dir)
    
    # Change to parent directory and copy README.md
    print("Copying README.md to doc/index.md...")
    parent_dir = os.path.join(script_dir, "..")
    shutil.copy('README.md', os.path.join('doc', 'index.md'))
    
    # Build mkdocs
    print("Building mkdocs documentation...")
    run_command('mkdocs build', "mkdocs build", cwd=parent_dir)
    
    print("Documentation build completed successfully!")

if __name__ == "__main__":
    main()
