import importlib
import pkgutil
import logging
import os

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

class ImportVerifier:
    """
    Verifies all Python imports within a given directory.
    """

    def __init__(self, base_path):
        """
        Initializes the ImportVerifier with the base path to scan.

        Args:
            base_path (str): The root directory to start the import verification from.
        """
        self.base_path = base_path
        self.broken_imports = []

    def verify_imports(self):
        """
        Verifies all Python imports within the base path.
        """
        self.broken_imports = []
        for module_name in self._find_modules(self.base_path):
            try:
                importlib.import_module(module_name)
                logging.debug(f"Successfully imported: {module_name}")
            except ImportError as e:
                logging.error(f"Failed to import {module_name}: {e}")
                self.broken_imports.append((module_name, str(e)))
            except Exception as e:
                logging.error(f"Unexpected error importing {module_name}: {e}")
                self.broken_imports.append((module_name, str(e))) # Capture other exceptions

    def _find_modules(self, path):
        """
        Finds all Python modules within a given path.

        Args:
            path (str): The directory to search for modules.

        Yields:
            str: The fully qualified name of a Python module.
        """
        for importer, modname, ispkg in pkgutil.walk_packages(path):
            full_module_name = self._build_module_name(importer.path, path, modname)
            yield full_module_name
            if ispkg:  # Handle packages recursively
                package_path = os.path.join(path, modname)
                yield from self._find_modules(package_path)

    def _build_module_name(self, importer_path, base_path, modname):
       """
       Builds the fully qualified module name.

       Args:
           importer_path (str): Path where the module is located
           base_path (str): Base path from where the scan started
           modname (str): Module name

       Returns:
           str: Fully qualified module name
       """
       relative_path = os.path.relpath(importer_path, base_path)
       module_path = relative_path.replace(os.sep, '.')
       if module_path == '.':
           return modname  # Top-level module
       else:
           return f"{module_path}.{modname}"


    def generate_report(self, report_path):
        """
        Generates a report of broken imports.

        Args:
            report_path (str): The path to save the report.
        """
        with open(report_path, "w") as f:
            f.write("# Import Verification Report\n\n")
            if self.broken_imports:
                f.write("## Broken Imports\n\n")
                for module_name, error_message in self.broken_imports:
                    f.write(f"- **Module:** {module_name}\n")
                    f.write(f"  **Error:** {error_message}\n\n")
            else:
                f.write("All imports verified successfully.\n")

    def run_verification(self, report_path="import_report.md"):
        """
        Runs the import verification process and generates a report.

        Args:
            report_path (str, optional): The path to save the report. Defaults to "import_report.md".
        """
        logging.info("Starting import verification...")
        self.verify_imports()
        self.generate_report(report_path)
        logging.info(f"Import verification complete. Report saved to {report_path}")

if __name__ == '__main__':
    # Example usage:
    verifier = ImportVerifier("/mnt/e/genesis-system")  # Replace with your base path
    verifier.run_verification("/mnt/e/genesis-system/core/validators/import_report.md")  # Specify your desired report path