#!/usr/bin/env python3
"""
Photo Collection Monitor
Monitors the ongoing photo collection process
"""

import time
import os
from sqlalchemy import create_engine, text
from urllib.parse import quote_plus
from datetime import datetime

def get_quick_status():
    """Get quick status without complex queries"""
    DATABASE_URL = f"postgresql://postgres:{quote_plus('F@f@k0s!!')}@localhost:5432/bookbeach"
    engine = create_engine(DATABASE_URL)
    company_id = "c35388d2-0028-4002-bcc4-db4d7ed2042e"
    
    try:
        with engine.connect() as db:
            # Total beaches
            total_result = db.execute(text("""
                SELECT COUNT(*) FROM beach_places 
                WHERE company_id = :company_id
            """), {"company_id": company_id}).fetchone()
            total_beaches = total_result[0] if total_result else 0
            
            # Beaches with photos
            photos_result = db.execute(text("""
                SELECT COUNT(DISTINCT bp.beach_place_id) 
                FROM beach_places bp
                JOIN beach_places_photos bpp ON bp.beach_place_id = bpp.beach_place_id
                WHERE bp.company_id = :company_id
            """), {"company_id": company_id}).fetchone()
            beaches_with_photos = photos_result[0] if photos_result else 0
            
            return {
                'total': total_beaches,
                'with_photos': beaches_with_photos,
                'without_photos': total_beaches - beaches_with_photos,
                'completion_rate': (beaches_with_photos / total_beaches * 100) if total_beaches > 0 else 0
            }
            
    except Exception as e:
        return {'error': str(e)}

def count_photo_files():
    """Count photo files on disk"""
    upload_dir = "D:/bookbeach/backend/uploads/beach_photos"
    if not os.path.exists(upload_dir):
        return 0
    return len([f for f in os.listdir(upload_dir) if f.lower().endswith(('.jpg', '.jpeg', '.png'))])

def main():
    """Monitor collection progress"""
    print("📡 PHOTO COLLECTION MONITOR")
    print("=" * 60)
    
    last_count = 0
    start_time = datetime.now()
    
    try:
        while True:
            current_time = datetime.now()
            elapsed = current_time - start_time
            
            # Get current status
            status = get_quick_status()
            file_count = count_photo_files()
            
            if 'error' in status:
                print(f"❌ Database error: {status['error']}")
                time.sleep(30)
                continue
            
            # Clear screen and show current status
            os.system('cls' if os.name == 'nt' else 'clear')
            
            print("📡 PHOTO COLLECTION MONITOR")
            print("=" * 60)
            print(f"🕐 Monitoring time: {current_time.strftime('%H:%M:%S')}")
            print(f"⏱️ Collection running for: {elapsed}")
            print()
            
            print("📊 CURRENT PROGRESS:")
            print(f"   • Total beaches: {status['total']:,}")
            print(f"   • With photos: {status['with_photos']:,}")
            print(f"   • Files on disk: {file_count:,}")
            print(f"   • Remaining: {status['without_photos']:,}")
            print(f"   • Completion: {status['completion_rate']:.1f}%")
            
            # Progress bar
            completion_rate = status.get('completion_rate', 0)
            progress = int(completion_rate / 2) if isinstance(completion_rate, (int, float)) else 0  # Scale to 50 chars
            bar = "█" * progress + "░" * (50 - progress)
            print(f"   • Progress: [{bar}] {completion_rate:.1f}%")
            print()
            
            # Calculate rate of collection
            current_photos = status.get('with_photos', 0)
            current_photos = current_photos if isinstance(current_photos, int) else 0
            new_photos = current_photos - (last_count if isinstance(last_count, int) else 0)
            if new_photos > 0:
                print(f"🚀 NEW PHOTOS: +{new_photos} in last minute")
                print(f"📈 Collection rate: ~{new_photos * 60:.0f} photos/hour")
                
                # Estimate completion time
                remaining_beaches = status.get('without_photos', 0)
                if isinstance(remaining_beaches, int) and new_photos > 0:
                    remaining_time = remaining_beaches / new_photos  # minutes
                    hours = int(remaining_time // 60)
                    minutes = int(remaining_time % 60)
                    print(f"⏰ ETA: ~{hours}h {minutes}m at current rate")
            else:
                print("⏸️ No new photos in last minute")
            
            print()
            print("💡 TIPS:")
            print("   • Press Ctrl+C to stop monitoring")
            print("   • Collection continues in background")
            print("   • Check admin panel to verify photo quality")
            
            last_count = current_photos
            time.sleep(60)  # Update every minute
            
    except KeyboardInterrupt:
        print("\n👋 Monitoring stopped. Collection continues in background.")
    except Exception as e:
        print(f"\n❌ Monitor error: {e}")

if __name__ == "__main__":
    main()