#!/usr/bin/env python3
''' Creates a module file `dummy_globals.py` that is used to trick a Python linter
    into knowing the canvas globals that are injected
'''
if True: #__name__ == '__main__':
    import ast

    print('Creating globals')
    def parse_class_methods_with_docs(file_path, class_name):
        with open(file_path, "r") as f:
            tree = ast.parse(f.read())

        method_info = []

        # Find the class in the file
        for node in ast.walk(tree):
            if isinstance(node, ast.ClassDef) and node.name == class_name:
                for n in node.body:
                    if isinstance(n, ast.FunctionDef) and '__' not in n.name and n.name[0] != '_':
                        # Get method name
                        method_name = n.name
                        # Get docstring (if exists)
                        docstring = ast.get_docstring(n) or ""
                        args = [arg.arg for arg in n.args.args if arg.arg != 'self']
                        is_property = any(
                            isinstance(decorator, ast.Name) and decorator.id == 'property'
                            for decorator in n.decorator_list
                        )
                        if n.args.vararg:
                            args.append('*' + n.args.vararg.arg)
                        method_info.append((method_name, args, is_property,
                                            docstring))

        return method_info

    method_info = parse_class_methods_with_docs('canvas.py', 'Canvas')
    method_info += parse_class_methods_with_docs('run_sketch.py', 'Sketch')

    with open('dummy_globals.py', 'w') as f:
        f.write(f"# Autogenerated canvas/sketch methods as globals to trick the linter\n\n")
        for method_name, args, is_property, docstring in method_info:
            if is_property:
                if docstring:
                    #f.write(f'# {docstring}\n')
                    f.write("%s = '%s'\n\n"%(method_name, docstring))
                else:
                    f.write("%s = ''\n\n"%(method_name))
            else:
                if args:
                    f.write('def %s(*args):\n'%method_name)
                else:
                    f.write('def %s():\n'%method_name)
                if docstring:
                    f.write(f'    """{docstring} """\n')
                f.write(f"    pass  # Dummy method for linter\n\n")
