"""
This file inserts the docs of each class and method into the pyi file for autocompletetion.
Before running make sure you have created the pyi according to the README.
You might need to change the pyi_path.
Then simply run this file.
After running all the docs should have been inserted but YOU'RE NOT DONE YET.
You need to fix the intedention at the two bottom function of the pyi file.
Now you're done and can enjoy working autocompletion of this library.
"""

import sys
import inspect
import re

sys.path.append('build/python-api-src')
import library

def update_pyi_with_docstrings(pyi_path):
    """
    Update the .pyi file with docstrings from the corresponding library.

    Args:
        pyi_path (str): The path to the .pyi file.

    Returns:
        None
    """
    with open(pyi_path, 'r') as file:
        lines = file.readlines()

    new_lines = []
    known_def = {} #To keep track of docs to class methods

    for i in range(len(lines)):
        line = lines[i]
        if line.strip().startswith('class '):
            new_lines.append(line)
            if not line.strip().endswith("ID:"):
                class_name = re.split(r'[\(: ]', line)[1]
                docstring = inspect.getdoc(getattr(library, class_name))
                new_lines.append(f'    """{docstring}"""\n')
                for func in dir(getattr(library, class_name)):
                    if func.startswith("__"):
                        continue
                    func_docs = inspect.getdoc(getattr(getattr(library, class_name), func))
                    known_def[func] = func_docs
                
        elif line.strip().startswith('def '):
            new_lines.append(line[:-4])
            func_name = re.split(r'[\(: ]', line.strip())[1]
            if func_name.startswith("__"):
                new_lines.append(f'    {line[-4:]}')
                continue
            elif func_name in known_def:
                new_lines.append(f'\n        """{known_def[func_name]}"""\n')
                new_lines.append(f'    {line[-4:]}')
                continue
            else:
                try:
                    func_doc = inspect.getdoc(getattr(library, func_name))
                    new_lines.append(f'\n        """{func_doc}"""\n')
                    new_lines.append(f'    {line[-4:]}')
                    continue
                except AttributeError:
                    new_lines.append(f'\n        """not found"""\n')
                    new_lines.append(f'    {line[-4:]}')
                    continue
        else:
            new_lines.append(line)
                

    # Write the updated content back to the .pyi file
    with open(pyi_path, 'w') as file:
        file.writelines(new_lines)


# Path to the generated .pyi file
pyi_file_path = 'build/python-api-src/library.pyi'
update_pyi_with_docstrings(pyi_file_path)