#!/usr/bin/env python3
"""
Test script to verify that the new photo models and relationships work correctly.
"""

import sys
from pathlib import Path

# Add the backend directory to the path
sys.path.append(str(Path(__file__).parent / 'backend'))

def test_photo_model_imports():
    """Test that the photo models can be imported without errors."""
    print("Testing photo model imports...")
    
    try:
        from app.models.business import MarketPhoto, AdventurePhoto, Market, Adventure
        print("✅ Successfully imported MarketPhoto and AdventurePhoto models")
        
        # Test that the models have the expected attributes
        market_photo_attrs = dir(MarketPhoto)
        adventure_photo_attrs = dir(AdventurePhoto)
        
        expected_attrs = ['photo_id', 'photo_path', 'photo_url', 'photo_caption', 'is_primary', 
                         'photo_type', 'file_size', 'width', 'height', 'uploaded_at', 'created_at']
        
        print("\nChecking MarketPhoto model attributes:")
        for attr in expected_attrs:
            if attr in market_photo_attrs:
                print(f"  ✅ {attr}: Found")
            else:
                print(f"  ❌ {attr}: Missing")
        
        print("\nChecking AdventurePhoto model attributes:")
        for attr in expected_attrs:
            if attr in adventure_photo_attrs:
                print(f"  ✅ {attr}: Found")
            else:
                print(f"  ❌ {attr}: Missing")
        
        # Test relationship attributes
        print("\nChecking MarketPhoto foreign key:")
        if 'market_id' in market_photo_attrs:
            print("  ✅ market_id: Found")
        else:
            print("  ❌ market_id: Missing")
            
        print("\nChecking AdventurePhoto foreign key:")
        if 'adventure_id' in adventure_photo_attrs:
            print("  ✅ adventure_id: Found")
        else:
            print("  ❌ adventure_id: Missing")
                
    except Exception as e:
        print(f"❌ Error importing photo models: {e}")
        return False
    
    return True

def test_photo_schema_imports():
    """Test that the photo schemas can be imported without errors."""
    print("\nTesting photo schema imports...")
    
    try:
        from app.schemas.business import (
            MarketPhoto, MarketPhotoCreate, MarketPhotoUpdate,
            AdventurePhoto, AdventurePhotoCreate, AdventurePhotoUpdate
        )
        print("✅ Successfully imported all photo schemas")
        
        # Test schema field definitions
        try:
            market_photo_fields = MarketPhoto.model_fields.keys()
            adventure_photo_fields = AdventurePhoto.model_fields.keys()
            
            expected_fields = ['photo_id', 'photo_path', 'photo_url', 'photo_caption', 'is_primary',
                             'photo_type', 'file_size', 'width', 'height', 'uploaded_at', 'created_at']
            
            print("\nChecking MarketPhoto schema fields:")
            for field in expected_fields:
                if field in market_photo_fields:
                    print(f"  ✅ {field}: Found")
                else:
                    print(f"  ❌ {field}: Missing")
            
            print("\nChecking AdventurePhoto schema fields:")
            for field in expected_fields:
                if field in adventure_photo_fields:
                    print(f"  ✅ {field}: Found")
                else:
                    print(f"  ❌ {field}: Missing")
                    
        except Exception as e:
            print(f"❌ Error checking schema fields: {e}")
            return False
            
    except Exception as e:
        print(f"❌ Error importing photo schemas: {e}")
        return False
    
    return True

def test_photo_model_instantiation():
    """Test that photo models can be instantiated correctly."""
    print("\nTesting photo model instantiation...")
    
    try:
        from app.models.business import MarketPhoto, AdventurePhoto
        import uuid
        
        # Test MarketPhoto instantiation
        market_photo = MarketPhoto(
            market_id=uuid.uuid4(),
            photo_path="/uploads/markets/test_market.jpg",
            photo_url="https://example.com/test_market.jpg",
            photo_caption="Test market photo",
            is_primary=True,
            photo_type="exterior",
            file_size=1024000,
            width=1920,
            height=1080
        )
        print("✅ MarketPhoto model instantiation successful")
        
        # Test AdventurePhoto instantiation
        adventure_photo = AdventurePhoto(
            adventure_id=uuid.uuid4(),
            photo_path="/uploads/adventures/test_adventure.jpg",
            photo_url="https://example.com/test_adventure.jpg",
            photo_caption="Test adventure photo",
            is_primary=True,
            photo_type="action",
            file_size=2048000,
            width=1920,
            height=1080
        )
        print("✅ AdventurePhoto model instantiation successful")
        
    except Exception as e:
        print(f"❌ Error testing photo model instantiation: {e}")
        return False
    
    return True

def test_photo_schema_validation():
    """Test that photo schemas work correctly for validation."""
    print("\nTesting photo schema validation...")
    
    try:
        from app.schemas.business import MarketPhotoCreate, AdventurePhotoCreate
        import uuid
        
        # Test MarketPhotoCreate schema
        market_photo_data = {
            "market_id": str(uuid.uuid4()),
            "photo_path": "/uploads/markets/test.jpg",
            "photo_caption": "Test photo",
            "is_primary": True,
            "photo_type": "products"
        }
        
        market_photo_schema = MarketPhotoCreate(**market_photo_data)
        print("✅ MarketPhotoCreate schema validation successful")
        
        # Test AdventurePhotoCreate schema
        adventure_photo_data = {
            "adventure_id": str(uuid.uuid4()),
            "photo_path": "/uploads/adventures/test.jpg", 
            "photo_caption": "Test adventure photo",
            "is_primary": False,
            "photo_type": "equipment"
        }
        
        adventure_photo_schema = AdventurePhotoCreate(**adventure_photo_data)
        print("✅ AdventurePhotoCreate schema validation successful")
        
    except Exception as e:
        print(f"❌ Error testing photo schema validation: {e}")
        return False
    
    return True

def test_relationship_setup():
    """Test that the relationships between models are set up correctly."""
    print("\nTesting model relationships...")
    
    try:
        from app.models.business import Market, Adventure, MarketPhoto, AdventurePhoto
        
        # Check that Market has photos relationship
        market_relationships = [rel.key for rel in Market.__mapper__.relationships]
        if 'photos' in market_relationships:
            print("✅ Market.photos relationship found")
        else:
            print("❌ Market.photos relationship missing")
            
        # Check that Adventure has photos relationship
        adventure_relationships = [rel.key for rel in Adventure.__mapper__.relationships]
        if 'photos' in adventure_relationships:
            print("✅ Adventure.photos relationship found")
        else:
            print("❌ Adventure.photos relationship missing")
            
        # Check that MarketPhoto has market relationship
        market_photo_relationships = [rel.key for rel in MarketPhoto.__mapper__.relationships]
        if 'market' in market_photo_relationships:
            print("✅ MarketPhoto.market relationship found")
        else:
            print("❌ MarketPhoto.market relationship missing")
            
        # Check that AdventurePhoto has adventure relationship  
        adventure_photo_relationships = [rel.key for rel in AdventurePhoto.__mapper__.relationships]
        if 'adventure' in adventure_photo_relationships:
            print("✅ AdventurePhoto.adventure relationship found")
        else:
            print("❌ AdventurePhoto.adventure relationship missing")
        
    except Exception as e:
        print(f"❌ Error testing relationships: {e}")
        return False
    
    return True

if __name__ == "__main__":
    print("🧪 TESTING NEW PHOTO MODELS AND RELATIONSHIPS")
    print("=" * 70)
    
    success = True
    success &= test_photo_model_imports()
    success &= test_photo_schema_imports()
    success &= test_photo_model_instantiation()
    success &= test_photo_schema_validation()
    success &= test_relationship_setup()
    
    print("\n" + "=" * 70)
    if success:
        print("✅ ALL PHOTO MODEL TESTS PASSED!")
        print("\nNew photo tables and models successfully created:")
        print("\n📸 Market Photos:")
        print("  • Table: market_photos")
        print("  • Model: MarketPhoto")
        print("  • Schemas: MarketPhotoCreate, MarketPhotoUpdate, MarketPhoto")
        print("  • Photo types: general, interior, exterior, products, logo")
        print("  • Relationship: Market.photos ↔ MarketPhoto.market")
        
        print("\n🏔️ Adventure Photos:")
        print("  • Table: adventure_photos")
        print("  • Model: AdventurePhoto") 
        print("  • Schemas: AdventurePhotoCreate, AdventurePhotoUpdate, AdventurePhoto")
        print("  • Photo types: general, equipment, location, action, logo")
        print("  • Relationship: Adventure.photos ↔ AdventurePhoto.adventure")
        
        print("\n🔧 Features:")
        print("  • UUID primary keys")
        print("  • Cascade delete when parent is deleted") 
        print("  • Primary photo designation (is_primary)")
        print("  • Photo metadata (file_size, width, height)")
        print("  • Upload and creation timestamps")
        print("  • Proper foreign key constraints and indexes")
    else:
        print("❌ SOME PHOTO MODEL TESTS FAILED")
        print("Please check the error messages above and fix the issues.")