#!/usr/bin/env python3
"""
Test restaurant photo downloader with small batch
"""

import requests
import os
import uuid
import time
import re
from datetime import datetime
from urllib.parse import quote_plus
from sqlalchemy import create_engine, text
from typing import Dict

def test_photo_download():
    """Test photo download for a few restaurants"""
    print("🧪 Testing restaurant photo download...")
    
    # Database connection
    DATABASE_URL = f"postgresql://postgres:{quote_plus('F@f@k0s!!')}@localhost:5432/bookbeach"
    engine = create_engine(DATABASE_URL)
    
    # Photo directory
    photo_dir = "restaurant_photos"
    os.makedirs(photo_dir, exist_ok=True)
    
    try:
        with engine.connect() as db:
            # Get first 3 restaurants without photos
            restaurants = db.execute(text("""
                SELECT r.restaurant_id, r.restaurant_name, r.cuisine_type
                FROM restaurants r
                LEFT JOIN restaurant_photos rp ON r.restaurant_id = rp.restaurant_id
                WHERE rp.photo_id IS NULL
                LIMIT 3
            """)).fetchall()
            
            print(f"📊 Testing with {len(restaurants)} restaurants")
            
            if not restaurants:
                print("✅ No restaurants without photos found")
                return
            
            session = requests.Session()
            session.headers.update({
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            })
            
            for i, (restaurant_id, restaurant_name, cuisine_type) in enumerate(restaurants, 1):
                print(f"\n{i}. Processing: {restaurant_name}")
                
                # Simple photo URL (using a placeholder service)
                photo_url = f"https://picsum.photos/800/600?random={i * 100}"
                
                try:
                    # Download photo
                    print(f"   📷 Downloading from: {photo_url}")
                    response = session.get(photo_url, timeout=10)
                    response.raise_for_status()
                    
                    # Create filename
                    safe_name = re.sub(r'[^\w\s-]', '', restaurant_name)
                    safe_name = re.sub(r'[-\s]+', '_', safe_name.strip())[:30]
                    filename = f"{safe_name}_test_{i}.jpg"
                    filepath = os.path.join(photo_dir, filename)
                    
                    # Save photo
                    with open(filepath, 'wb') as f:
                        f.write(response.content)
                    
                    file_size = os.path.getsize(filepath)
                    print(f"   ✅ Downloaded: {filename} ({file_size} bytes)")
                    
                    # Save to database
                    photo_id = str(uuid.uuid4())
                    db.execute(text("""
                        INSERT INTO restaurant_photos (
                            photo_id, restaurant_id, photo_path, photo_url, photo_type,
                            file_size, is_primary, uploaded_at, created_at
                        ) VALUES (
                            :photo_id, :restaurant_id, :photo_path, :photo_url, :photo_type,
                            :file_size, :is_primary, NOW(), NOW()
                        )
                    """), {
                        'photo_id': photo_id,
                        'restaurant_id': str(restaurant_id),
                        'photo_path': filepath,
                        'photo_url': photo_url,
                        'photo_type': 'general',
                        'file_size': file_size,
                        'is_primary': True
                    })
                    
                    db.commit()
                    print(f"   💾 Saved to database: {photo_id}")
                    
                except Exception as e:
                    print(f"   ❌ Error: {e}")
                    continue
                
                time.sleep(1)  # Be polite
            
            # Check results
            print(f"\n📊 Verification:")
            result = db.execute(text("""
                SELECT COUNT(*) FROM restaurant_photos
            """)).fetchone()
            
            total_photos = result[0] if result else 0
            print(f"   📷 Total photos in database: {total_photos}")
            
            print(f"✅ Test completed successfully!")
            
    except Exception as e:
        print(f"❌ Test failed: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_photo_download()