import os
import json
import logging
from typing import List, Dict

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def get_all_files_in_directory(directory: str) -> List[str]:
    """
    Recursively retrieves all file paths within a given directory.

    Args:
        directory (str): The root directory to search.

    Returns:
        List[str]: A list of absolute file paths.
    """
    file_paths = []
    for root, _, files in os.walk(directory):
        for file in files:
            file_paths.append(os.path.join(root, file))
    return file_paths


def analyze_file(file_path: str) -> Dict:
    """
    Analyzes a file to extract relevant information (e.g., docstrings, imports).

    Args:
        file_path (str): The path to the file.

    Returns:
        Dict: A dictionary containing analysis results.
    """
    analysis = {}
    try:
        with open(file_path, 'r') as f:
            content = f.read()
            # Simple docstring extraction (can be improved with AST)
            if '\"\"\"' in content:
                docstring_start = content.find('\"\"\"') + 3
                docstring_end = content.find('\"\"\"', docstring_start)
                if docstring_end != -1:
                    analysis['docstring'] = content[docstring_start:docstring_end].strip()
                else:
                    analysis['docstring'] = 'No complete docstring found'
            else:
                analysis['docstring'] = 'No docstring found'
            # Simple import extraction (can be improved with AST)
            imports = []
            for line in content.splitlines():
                if line.startswith('import') or line.startswith('from'):
                    imports.append(line.strip())
            analysis['imports'] = imports
    except Exception as e:
        logging.error(f"Error analyzing file {file_path}: {e}")
        analysis['error'] = str(e)
    return analysis


def generate_component_documentation(root_directory: str, output_file: str) -> None:
    """
    Generates component documentation by analyzing files in a directory.

    Args:
        root_directory (str): The root directory containing the components.
        output_file (str): The path to the output Markdown file.
    """
    all_files = get_all_files_in_directory(root_directory)
    component_files = [f for f in all_files if f.endswith('.py')]  # Consider only Python files
    
    documentation = "# Component Documentation\n\n"

    for file_path in component_files:
        documentation += f"## File: `{file_path.replace(root_directory, '')}`\n\n"
        analysis = analyze_file(file_path)

        if 'error' in analysis:
            documentation += f"**Error**: {analysis['error']}\n\n"
        else:
            documentation += f"**Docstring**:\n```\n{analysis.get('docstring', 'No docstring')}\n```\n\n"
            imports_str = "\n".join(analysis.get('imports', []))
            documentation += f"**Imports**:\n```python\n{imports_str}\n```\n\n"

    try:
        with open(output_file, 'w') as f:
            f.write(documentation)
        logging.info(f"Component documentation generated at {output_file}")
    except Exception as e:
        logging.error(f"Error writing to file {output_file}: {e}")


if __name__ == '__main__':
    root_directory = '/mnt/e/genesis-system'
    output_file = '/mnt/e/genesis-system/docs/components.md'
    generate_component_documentation(root_directory, output_file)