import os
import re
import logging
from typing import List, Tuple

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

def find_api_endpoints(root_dir: str) -> List[Tuple[str, str]]:
    """
    Recursively searches for potential API endpoints in Python files within a directory.

    Args:
        root_dir: The root directory to start the search from.

    Returns:
        A list of tuples, where each tuple contains the file path and the endpoint/handler found.
    """
    endpoints: List[Tuple[str, str]] = []
    for root, _, files in os.walk(root_dir):
        for file in files:
            if file.endswith(".py"):
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, "r") as f:
                        for line in f:
                            # Example patterns to identify API endpoints/handlers
                            if "@app.route" in line:
                                match = re.search(r"@app\.route\(['\"](.*?)['\"]", line)
                                if match:
                                    endpoint = match.group(1)
                                    endpoints.append((file_path, f"Route: {endpoint}"))
                            elif "webhook_handler" in line:
                                match = re.search(r"def\s+(webhook_handler\w+)", line)
                                if match:
                                    handler_name = match.group(1)
                                    endpoints.append((file_path, f"Webhook Handler: {handler_name}"))
                            elif "api_call" in line:
                                match = re.search(r"def\s+(api_call\w+)", line)
                                if match:
                                    function_name = match.group(1)
                                    endpoints.append((file_path, f"API Call: {function_name}"))
                except Exception as e:
                    logging.error(f"Error processing file {file_path}: {e}")
    return endpoints

def write_api_catalog(endpoints: List[Tuple[str, str]], output_file: str) -> None:
    """
    Writes the API endpoint catalog to a Markdown file.

    Args:
        endpoints: A list of tuples, where each tuple contains the file path and the endpoint/handler.
        output_file: The path to the output Markdown file.
    """
    try:
        with open(output_file, "w") as f:
            f.write("# API Endpoint Catalog\n\n")
            for file_path, endpoint in endpoints:
                f.write(f"- **File:** {file_path}\n")
                f.write(f"  - **Endpoint/Handler:** {endpoint}\n\n")
        logging.info(f"API catalog written to {output_file}")
    except Exception as e:
        logging.error(f"Error writing to file {output_file}: {e}")

def main() -> None:
    """
    Main function to find API endpoints and write the catalog.
    """
    root_directory = "/mnt/e/genesis-system"  # Replace with actual root directory
    output_file = "/mnt/e/genesis-system/docs/API_CATALOG.md"
    endpoints = find_api_endpoints(root_directory)
    write_api_catalog(endpoints, output_file)

if __name__ == "__main__":
    main()