#!/usr/bin/env python3

import argparse
import os
import shutil
from contextlib import contextmanager
from sphinx.cmd.build import build_main
import tempfile
import logging

logging.basicConfig(level=logging.INFO, format='[sphinx-versioning] %(message)s')

def find_conf_file(start_dir):
    """
    Search for conf.py in the current directory and one level down.
    Return its path if found, otherwise return None.
    """
    conf_file = 'conf.py'
    # Check in the current directory
    if os.path.exists(os.path.join(start_dir, conf_file)):
        return os.path.join(start_dir, conf_file)
    
    # Check one level deeper
    for subdir in os.listdir(start_dir):
        subdir_path = os.path.join(start_dir, subdir)
        if os.path.isdir(subdir_path) and os.path.exists(os.path.join(subdir_path, conf_file)):
            return os.path.join(subdir_path, conf_file)
    
    return None


@contextmanager
def set_version_build_env():
    os.environ["SPHINX_VERSIONING_PLUGIN"] = "1"
    try:
        yield
    finally:
        del os.environ["SPHINX_VERSIONING_PLUGIN"]


parser = argparse.ArgumentParser(description='Manage Sphinx versioned documentation.')
parser.add_argument('-v', '--version', type=str, required=True, help='Version to manage')
parser.add_argument('-d', '--delete', action='store_true', help='Delete the version')

args = parser.parse_args()

conf_file_path = find_conf_file(os.getcwd())

if not conf_file_path:
    logging.error("[ERROR] conf.py not found")
    exit(1)

docs_dir = os.path.dirname(conf_file_path)
parent_dir = os.path.dirname(docs_dir)

logging.info(f"Detected Sphinx directory at {docs_dir}")

if args.delete:
    if not os.path.exists(os.path.join(docs_dir, f"_static/sphinx_versioning_plugin/{args.version}")):
        logging.error(f"[ERROR] {args.version} is not found!")
        exit(1)

    # Delete version
    shutil.rmtree(os.path.join(docs_dir, f"_static/sphinx_versioning_plugin/{args.version}"))

# Add a new version
else:
    # Create a temporary directory
    with tempfile.TemporaryDirectory(dir=parent_dir) as temp_dir:

        # Copy the documentation source to the temporary directory
        shutil.copytree(docs_dir, temp_dir, dirs_exist_ok=True)

        # Remove the versions directory from the temporary directory
        shutil.rmtree(os.path.join(temp_dir, '_static/sphinx_versioning_plugin'), ignore_errors=True)

        with set_version_build_env():
            # Build the docs using the temporary directory as the source
            result = build_main(["-b", "html", temp_dir, os.path.join(docs_dir, f"_static/sphinx_versioning_plugin/{args.version}")])

        if result == 2:
            logging.info(f"[ERROR] Failed to build the version {args.version}")
            exit(1)
        
        logging.info(f"Version {args.version} is added. Run sphinx build to see the version on the sidebar")
