#!/usr/bin/env python3
"""Test that all module imports work correctly."""

import sys
import os
import ast

MODULES = [
    'engine.py',
    'engine_lib/paths.py',
    'engine_lib/models.py',
    'engine_lib/prompts.py',
    'engine_lib/config.py',
    'engine_lib/context.py',
    'engine_lib/state.py',
    'engine_lib/tools_handler.py',
    'engine_lib/llm.py',
    'engine_lib/validation.py',
    'engine_lib/parsing.py',
]

def check_missing_imports():
    """Check for missing imports that would cause NameError."""
    errors = []
    tool_dir = os.path.dirname(__file__)

    for mod_file in MODULES:
        mod_path = os.path.join(tool_dir, mod_file)
        if not os.path.exists(mod_path):
            errors.append(f"Module not found: {mod_file}")
            continue
        with open(mod_path, 'r') as f:
            content = f.read()

        tree = ast.parse(content)

        names_used = set()
        for node in ast.walk(tree):
            if isinstance(node, ast.Name):
                names_used.add(node.id)

        common_modules = {
            'random',
            're',
            'json',
            'traceback',
            'datetime',
            'time',
            'os',
            'sys',
            'pathlib',
            'functools',
            'collections',
            'typing',
            'io',
            'string',
        }

        for module in common_modules:
            if module in names_used and not hasattr(sys.modules.get(module, None), '__file__'):
                if f'import {module}' not in content and f'from {module} import' not in content:
                    errors.append(f"{mod_file}: Missing import: {module}")

    return errors

if __name__ == '__main__':
    errors = check_missing_imports()
    if errors:
        print("ERROR: Missing imports detected:")
        for error in errors:
            print(f"  - {error}")
        sys.exit(1)
    else:
        print("✓ All imports present across all modules")
        sys.exit(0)
