import os
import inspect
import logging
import pytest
from typing import List

# Configure logging
logging.basicConfig(level=logging.INFO)


def generate_test_file_name(module_file_path: str) -> str:
    """Generates the test file name from the module file path."""
    module_name = os.path.basename(module_file_path).replace(".py", "")
    test_file_name = f"test_{module_name}.py"
    return os.path.join("/mnt/e/genesis-system/tests/knowledge/", test_file_name)


def extract_function_names(module_file_path: str) -> List[str]:
    """Extracts function names from a Python module."""
    function_names = []
    try:
        with open(module_file_path, "r") as f:
            source_code = f.read()

        # Execute the code in a safe environment to inspect it
        local_namespace = {}
        exec(source_code, local_namespace)

        for name, obj in local_namespace.items():
            if inspect.isfunction(obj):
                function_names.append(name)
    except FileNotFoundError:
        logging.error(f"File not found: {module_file_path}")
    except Exception as e:
        logging.error(f"Error extracting function names from {module_file_path}: {e}")
    return function_names


def generate_test_code(module_file_path: str) -> str:
    """Generates pytest test code for a Python module."""
    function_names = extract_function_names(module_file_path)
    module_name = os.path.basename(module_file_path).replace(".py", "")
    test_code = f"""
import pytest
from core.knowledge import {module_name}

def test_placeholder():
    assert True
"""
    if function_names:
        test_code = f"""
import pytest
from core.knowledge import {module_name}

"""
        for function_name in function_names:
            test_code += f"""
def test_{function_name}():
    # Placeholder test for {function_name}
    result = {module_name}.{function_name}()
    assert result is not None  # Replace with a meaningful assertion
"""
    return test_code


def create_test_file(module_file_path: str) -> None:
    """Creates a pytest test file for a given module."""
    test_file_path = generate_test_file_name(module_file_path)
    test_code = generate_test_code(module_file_path)
    try:
        with open(test_file_path, "w") as f:
            f.write(test_code)
        logging.info(f"Test file created: {test_file_path}")
    except Exception as e:
        logging.error(f"Error creating test file {test_file_path}: {e}")


def generate_tests_for_modules(module_directory: str, test_directory: str) -> None:
    """Generates pytest test files for all Python modules in a directory."""

    # Create the test directory if it doesn't exist
    if not os.path.exists(test_directory):
        try:
            os.makedirs(test_directory)
            logging.info(f"Created test directory: {test_directory}")
        except OSError as e:
            logging.error(f"Error creating test directory {test_directory}: {e}")
            return

    try:
        for filename in os.listdir(module_directory):
            if filename.endswith(".py"):
                module_file_path = os.path.join(module_directory, filename)
                create_test_file(module_file_path)
    except FileNotFoundError:
        logging.error(f"Directory not found: {module_directory}")
    except Exception as e:
        logging.error(f"Error processing modules in {module_directory}: {e}")


if __name__ == "__main__":
    module_directory = "/mnt/e/genesis-system/core/knowledge/"
    test_directory = "/mnt/e/genesis-system/tests/knowledge/"
    generate_tests_for_modules(module_directory, test_directory)