#!/usr/bin/env python3

import os
import sys
import psycopg2
from urllib.parse import urlparse

# Database configuration
DATABASE_URL = "postgresql://postgres:123456@localhost:5432/bookbeach"

def check_restaurant_photos():
    """Check restaurant photos in the database"""
    try:
        # Parse database URL
        parsed = urlparse(DATABASE_URL)
        
        # Connect to database
        conn = psycopg2.connect(
            host=parsed.hostname,
            port=parsed.port,
            user=parsed.username,
            password=parsed.password,
            database=parsed.path[1:]  # Remove leading slash
        )
        
        cursor = conn.cursor()
        
        # Check total number of restaurant photos
        cursor.execute("SELECT COUNT(*) FROM restaurant_photos")
        total_photos = cursor.fetchone()[0]
        print(f"Total restaurant photos: {total_photos}")
        
        # Check how many restaurants have photos
        cursor.execute("""
            SELECT COUNT(DISTINCT restaurant_id) 
            FROM restaurant_photos
        """)
        restaurants_with_photos = cursor.fetchone()[0]
        print(f"Restaurants with photos: {restaurants_with_photos}")
        
        # Check primary photos
        cursor.execute("SELECT COUNT(*) FROM restaurant_photos WHERE is_primary = true")
        primary_photos = cursor.fetchone()[0]
        print(f"Primary photos: {primary_photos}")
        
        # Sample some restaurant photos
        cursor.execute("""
            SELECT r.restaurant_name, rp.photo_path, rp.is_primary
            FROM restaurant_photos rp
            JOIN restaurants r ON r.restaurant_id = rp.restaurant_id
            ORDER BY rp.created_at DESC
            LIMIT 10
        """)
        
        sample_photos = cursor.fetchall()
        print(f"\nSample restaurant photos:")
        for restaurant_name, photo_path, is_primary in sample_photos:
            print(f"  {restaurant_name}: {photo_path} (Primary: {is_primary})")
        
        # Check if photo files exist
        print(f"\nChecking if photo files exist...")
        cursor.execute("SELECT DISTINCT photo_path FROM restaurant_photos LIMIT 5")
        photo_paths = cursor.fetchall()
        
        for (photo_path,) in photo_paths:
            if photo_path:
                # Remove leading slash and construct full path
                clean_path = photo_path.lstrip('/')
                full_path = os.path.join('d:', 'bookbeach', 'backend', clean_path)
                exists = os.path.exists(full_path)
                print(f"  {photo_path} -> {full_path} (Exists: {exists})")
        
        conn.close()
        
    except Exception as e:
        print(f"Error checking restaurant photos: {e}")

if __name__ == "__main__":
    check_restaurant_photos()