# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/15_latex.__init__.ipynb.

# %% auto 0
__all__ = ['find_main_latex_file']

# %% ../../nbs/15_latex.__init__.ipynb 3
import os
from os import PathLike
import re
from pathlib import Path
from typing import Union

# %% ../../nbs/15_latex.__init__.ipynb 6
def find_main_latex_file(
        directory: PathLike
        ) -> Path: # The full path to the main LaTeX file if found; otherwise, raises an error.

    """
    Identify the main LaTeX file in a given directory.

    The main LaTeX file is determined based on the presence of:
    - A \documentclass command
    - A \begin{document} command

    Parameters:
    - directory: The path to the directory containing LaTeX files.

    Returns:
    - The full path to the main LaTeX file if found; otherwise, raises an error.
    
    Raises:
    - FileNotFoundError: If no suitable main LaTeX file is found.
    """
    # Convert directory to Path object
    directory = Path(directory)
    
    # List all .tex files in the directory
    latex_files = [f for f in directory.glob('*.tex')]
    
    for file_path in latex_files:
        with file_path.open('r', encoding='utf-8') as file:
            content = file.read()
            
            # Check for \documentclass and \begin{document}
            if re.search(r'\\documentclass', content) and re.search(r'\\begin\{document\}', content):
                return file_path  # Return the Path object of the main LaTeX file

    raise FileNotFoundError("No suitable main LaTeX file found in the directory.")

# Example usage
# directory_path = '/path/to/your/latex/files'
# try:
#     main_latex_file = find_main_latex_file(directory_path)
#     print(f"The main LaTeX file is: {main_latex_file}")
# except FileNotFoundError as e:
#     print(e)

