#!/usr/bin/env python3
"""
Test script to verify the pipeline fixes work correctly
"""

import sys
import os
import traceback
from typing import Dict, Any

# Add the project root to the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def test_pipeline_fixes():
    """Test the pipeline with improved error handling"""
    
    print("๐Ÿงช Testing Monster Generation Pipeline Fixes")
    print("=" * 50)
    
    try:
        # Import the pipeline
        from core.ai_pipeline import MonsterGenerationPipeline
        print("โœ… Successfully imported MonsterGenerationPipeline")
        
        # Initialize pipeline
        print("๐Ÿ”ง Initializing pipeline...")
        pipeline = MonsterGenerationPipeline(device="cpu")  # Use CPU for testing
        print("โœ… Pipeline initialized successfully")
        
        # Test with a simple text input
        print("\n๐Ÿš€ Testing monster generation...")
        test_input = "Create a friendly fire monster with wings"
        
        result = pipeline.generate_monster(
            text_input=test_input,
            user_id="test_user"
        )
        
        print(f"\n๐Ÿ“Š Generation Result:")
        print(f"Status: {result.get('status', 'unknown')}")
        print(f"Success: {result.get('generation_log', {}).get('success', False)}")
        print(f"Stages completed: {result.get('generation_log', {}).get('stages_completed', [])}")
        print(f"Fallbacks used: {result.get('generation_log', {}).get('fallbacks_used', [])}")
        print(f"Errors: {result.get('generation_log', {}).get('errors', [])}")
        
        if result.get('traits'):
            print(f"Monster name: {result.get('traits', {}).get('name', 'Unknown')}")
            print(f"Monster element: {result.get('traits', {}).get('element', 'Unknown')}")
        
        if result.get('dialogue'):
            print(f"Monster dialogue: {result.get('dialogue', '')}")
        
        print(f"Download files: {result.get('download_files', [])}")
        
        # Clean up
        pipeline.cleanup()
        print("\n๐Ÿงน Pipeline cleaned up successfully")
        
        return True
        
    except Exception as e:
        print(f"โŒ Test failed with error: {e}")
        print(f"Error type: {type(e).__name__}")
        print("Full traceback:")
        traceback.print_exc()
        return False

def test_fallback_manager():
    """Test the fallback manager"""
    
    print("\n๐Ÿงช Testing Fallback Manager")
    print("=" * 30)
    
    try:
        from utils.fallbacks import FallbackManager
        
        fallback = FallbackManager()
        
        # Test text generation fallback
        print("๐Ÿ“ Testing text generation fallback...")
        traits, dialogue = fallback.handle_text_gen_failure("Create a water monster")
        print(f"โœ… Generated traits: {traits.get('name', 'Unknown')}")
        print(f"โœ… Generated dialogue: {dialogue}")
        
        # Test image generation fallback
        print("๐ŸŽจ Testing image generation fallback...")
        image = fallback.handle_image_gen_failure("Create a fire monster")
        print(f"โœ… Generated image: {type(image)}")
        
        # Test 3D generation fallback
        print("๐Ÿ”ฒ Testing 3D generation fallback...")
        model_3d = fallback.handle_3d_gen_failure(image)
        print(f"โœ… Generated 3D model: {type(model_3d)}")
        
        print("โœ… All fallback tests passed!")
        return True
        
    except Exception as e:
        print(f"โŒ Fallback test failed: {e}")
        traceback.print_exc()
        return False

def main():
    """Main test function"""
    
    print("๐Ÿ” Starting Pipeline Fix Verification")
    print("=" * 50)
    
    # Test fallback manager first (doesn't require heavy models)
    fallback_success = test_fallback_manager()
    
    # Test full pipeline (may fail due to missing models, but should show better error handling)
    pipeline_success = test_pipeline_fixes()
    
    print("\n" + "=" * 50)
    print("๐Ÿ“‹ Test Results Summary:")
    print(f"Fallback Manager: {'โœ… PASSED' if fallback_success else 'โŒ FAILED'}")
    print(f"Pipeline: {'โœ… PASSED' if pipeline_success else 'โŒ FAILED'}")
    
    if fallback_success and pipeline_success:
        print("\n๐ŸŽ‰ All tests passed! Pipeline fixes are working correctly.")
    elif fallback_success:
        print("\nโš ๏ธ Fallback manager works, but pipeline may need model dependencies.")
        print("This is expected if models aren't installed.")
    else:
        print("\nโŒ Some tests failed. Check the error messages above.")
    
    return fallback_success and pipeline_success

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)