#!/usr/bin/env python3
"""
Test Nano Banana editing with a real image from the database
"""
import asyncio
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from app.database import SessionLocal
from app.models.asset import Asset
from app.services.image_generator import _generate_nano_banana

async def test_edit():
    """Test editing an existing asset"""
    db = SessionLocal()
    
    try:
        # Get the most recent image asset
        asset = db.query(Asset).filter(
            Asset.mime_type.like('image/%')
        ).order_by(Asset.created_at.desc()).first()
        
        if not asset:
            print("❌ No image assets found in database")
            return
            
        print(f"✓ Found asset: {asset.original_filename} ({asset.mime_type})")
        print(f"  Asset ID: {asset.id}")
        
        # Read the image data
        if not os.path.exists(asset.file_path):
            print(f"❌ File not found: {asset.file_path}")
            return
            
        with open(asset.file_path, 'rb') as f:
            image_data = f.read()
            
        print(f"✓ Loaded image data: {len(image_data)} bytes")
        
        # Test edit
        input_data = {
            "prompt": "add a beautiful sunset with orange and pink colors in the sky",
            "aspect_ratio": "16:9",
            "image_size": "2K"
        }
        
        print(f"\n🎨 Testing edit with prompt: '{input_data['prompt']}'")
        print("⏳ Calling Nano Banana API...")
        
        result_bytes, filename = await _generate_nano_banana(
            input_data=input_data,
            image_data=image_data,
            mime_type=asset.mime_type
        )
        
        if result_bytes:
            print(f"✅ SUCCESS! Generated: {filename}")
            print(f"   Size: {len(result_bytes)} bytes")
            
            # Save to temp file
            output_path = f"/tmp/{filename}"
            with open(output_path, 'wb') as f:
                f.write(result_bytes)
            print(f"   Saved to: {output_path}")
        else:
            print("❌ FAILED: No image data returned")
            
    except Exception as e:
        print(f"❌ ERROR: {e}")
        import traceback
        traceback.print_exc()
    finally:
        db.close()

if __name__ == "__main__":
    asyncio.run(test_edit())
