#!/usr/bin/env python3
"""
Test runner that sets up Blender mocking before running pytest.
This ensures bpy is available when test modules are imported.
"""

import sys
import os
from unittest.mock import Mock

def setup_blender_mocks():
    """Set up comprehensive Blender module mocks"""
    print("[Test Setup] Setting up Blender mocks...")
    
    # Create main bpy mock
    mock_bpy = Mock()
    mock_bmesh = Mock()
    
    # Create mock types with all necessary attributes
    mock_types = Mock()
    mock_types.Operator = Mock
    mock_types.Panel = Mock
    mock_types.PropertyGroup = Mock
    mock_types.UIList = Mock
    mock_types.Scene = Mock()
    mock_types.NODE_MT_add = Mock()
    mock_types.VIEW3D_MT_add = Mock()
    mock_types.VIEW3D_MT_mesh_add = Mock()
    mock_types.NODE_MT_node = Mock()
    mock_types.IMAGE_MT_image = Mock()
    
    # Create mock props
    mock_props = Mock()
    mock_props.StringProperty = Mock
    mock_props.IntProperty = Mock
    mock_props.FloatVectorProperty = Mock
    mock_props.FloatProperty = Mock
    mock_props.BoolProperty = Mock
    mock_props.EnumProperty = Mock
    mock_props.CollectionProperty = Mock
    mock_props.PointerProperty = Mock
    
    # Create mock utils
    mock_utils = Mock()
    mock_utils.register_class = Mock()
    mock_utils.unregister_class = Mock()
    
    # Create mock app
    mock_app = Mock()
    mock_app.handlers = Mock()
    mock_app.handlers.load_post = []
    mock_app.handlers.persistent = lambda f: f
    
    # Create mock context and data
    mock_context = Mock()
    mock_context.window_manager = Mock()
    mock_context.scene = Mock()
    
    mock_data = Mock()
    mock_images = Mock()
    mock_data.images = mock_images
    
    # Attach all attributes to main bpy mock
    mock_bpy.types = mock_types
    mock_bpy.props = mock_props
    mock_bpy.utils = mock_utils
    mock_bpy.app = mock_app
    mock_bpy.context = mock_context
    mock_bpy.data = mock_data
    
    # Install mocks in sys.modules BEFORE any imports
    sys.modules['bpy'] = mock_bpy
    sys.modules['bmesh'] = mock_bmesh
    sys.modules['bpy.types'] = mock_types
    sys.modules['bpy.props'] = mock_props
    sys.modules['bpy.utils'] = mock_utils
    sys.modules['bpy.app'] = mock_app
    sys.modules['bpy.context'] = mock_context
    sys.modules['bpy.data'] = mock_data
    
    print("[Test Setup] Blender mocks installed successfully")
    return mock_bpy

def main():
    """Main test runner"""
    print("[Test Runner] Starting Text Texture Generator test suite")
    
    # Set up mocks before any imports
    setup_blender_mocks()
    
    # Add current directory to Python path
    current_dir = os.path.dirname(os.path.abspath(__file__))
    if current_dir not in sys.path:
        sys.path.insert(0, current_dir)
    
    # Import and run pytest
    try:
        import pytest
        print("[Test Runner] Running pytest with comprehensive test suite...")
        
        # Run pytest with verbose output (disable strict markers to avoid configuration issues)
        pytest_args = [
            'tests/',
            '-v',
            '--tb=short'
        ]
        
        # Add any additional arguments passed to this script
        if len(sys.argv) > 1:
            pytest_args.extend(sys.argv[1:])
        
        exit_code = pytest.main(pytest_args)
        
        if exit_code == 0:
            print("[Test Runner] ✅ All tests completed successfully!")
        else:
            print(f"[Test Runner] ❌ Tests failed with exit code: {exit_code}")
        
        return exit_code
        
    except Exception as e:
        print(f"[Test Runner] ❌ Error running tests: {e}")
        import traceback
        traceback.print_exc()
        return 1

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)