#!/usr/bin/env python3
"""
Progress Monitor for Beach Photo Collection
Tracks the ongoing photo collection process
"""

import os
import time
from sqlalchemy import create_engine, text
from urllib.parse import quote_plus

def get_collection_status():
    """Get current collection status"""
    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_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
            
            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 in uploads directory"""
    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 progress"""
    print("📡 BEACH PHOTO COLLECTION PROGRESS MONITOR")
    print("=" * 60)
    
    last_count = 0
    start_time = time.time()
    
    try:
        while True:
            # Clear screen (works on Windows and Unix)
            os.system('cls' if os.name == 'nt' else 'clear')
            
            print("📡 BEACH PHOTO COLLECTION PROGRESS MONITOR")
            print("=" * 60)
            print(f"🕐 Last updated: {time.strftime('%Y-%m-%d %H:%M:%S')}")
            print()
            
            # Get status
            status = get_collection_status()
            file_count = count_photo_files()
            
            if 'error' in status:
                print(f"❌ Database error: {status['error']}")
            else:
                print("📊 COLLECTION 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}%")
                
                # Calculate rate
                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:
                    elapsed_minutes = (time.time() - start_time) / 60
                    if elapsed_minutes > 0:
                        rate = new_photos / elapsed_minutes
                        print(f"   • Rate: {rate:.1f} photos/minute")
                        
                        # ETA
                        if rate > 0:
                            remaining_beaches = status.get('without_photos', 0)
                            remaining_beaches = remaining_beaches if isinstance(remaining_beaches, int) else 0
                            remaining_minutes = remaining_beaches / rate if isinstance(rate, (int, float)) and rate > 0 else 0
                            hours = int(remaining_minutes // 60)
                            minutes = int(remaining_minutes % 60)
                            print(f"   • ETA: ~{hours}h {minutes}m")
                
                last_count = status['with_photos']
            
            print()
            print("💡 TIPS:")
            print("   • Photos are being collected from Wikimedia Commons")
            print("   • Process runs in batches of 5 beaches")
            print("   • 3-second delay between batches to be respectful")
            print("   • Press Ctrl+C to stop monitoring (collection continues)")
            
            # Wait 5 minutes before next update
            time.sleep(300)
            
    except KeyboardInterrupt:
        print("\n👋 Monitoring stopped. Collection continues in background.")
    except Exception as e:
        print(f"\n❌ Monitor error: {e}")

if __name__ == "__main__":
    main()