#!/usr/bin/env python3
"""Test that all engine modules can be imported without errors."""

import sys
import os
import traceback


def test_module_import(module_name):
    """Try importing a module and return (ok, error_msg)."""
    try:
        __import__(module_name)
        return True, None
    except Exception as e:
        return False, f"{type(e).__name__}: {e}\n{traceback.format_exc()}"


def test_engine_import():
    """Test that all modules import without errors."""
    errors = []

    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

    modules_to_test = [
        ('engine_lib.paths', ['BASE_DIR', 'SESSION_DIR', 'CHAR_PATH', 'LOG_PATH', 'LLM_LOG_PATH']),
        ('engine_lib.models', ['TurnResult']),
        ('engine_lib.prompts', ['SYSTEM_PROMPT']),
        ('engine_lib.config', ['load_config', 'save_config', 'get_model']),
        ('engine_lib.context', ['build_system_prompt']),
        ('engine_lib.state', ['read_file', 'apply_state', 'append_log', 'append_llm_log', 'next_turn_number']),
        ('engine_lib.tools_handler', ['execute_tool', 'extract_tool_calls', 'TOOL_REGISTRY']),
        ('engine_lib.llm', ['call_llm']),
        ('engine_lib.validation', ['validate_turn']),
        ('engine_lib.parsing', ['log_turn_details']),
        ('engine', ['GameEngine']),
    ]

    for mod_name, expected_attrs in modules_to_test:
        ok, err = test_module_import(mod_name)
        if not ok:
            errors.append(f"Import error ({mod_name}): {err}")
            continue
        print(f"✓ {mod_name} module imported successfully")

        mod = sys.modules[mod_name]
        for attr in expected_attrs:
            if not hasattr(mod, attr):
                errors.append(f"{mod_name}: {attr} not found")
            else:
                print(f"  ✓ {mod_name}.{attr} exists")

    import engine
    if hasattr(engine.GameEngine, 'generate_turn'):
        print(f"✓ engine.GameEngine.generate_turn method found")
    else:
        errors.append("engine.GameEngine.generate_turn method not found")

    return errors


if __name__ == '__main__':
    errors = test_engine_import()
    if errors:
        print("ERROR: Runtime errors detected:")
        for error in errors:
            print(f"  - {error}")
        sys.exit(1)
    else:
        print("\n✓ All modules validated successfully")
        sys.exit(0)
