#!/usr/bin/env python3
"""
Test script to download a few sample images
"""

import sqlite3
import requests
import os
import time
import hashlib
from pathlib import Path
import logging

def test_download():
    """Test downloading a few sample images"""
    db_path = '/var/www/vynex.org/urls.db'
    images_folder = Path('/var/www/vynex.org/images')
    
    # Create images folder if it doesn't exist
    images_folder.mkdir(exist_ok=True)
    
    # Setup logging
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    logger = logging.getLogger(__name__)
    
    # Get first 3 URLs for testing
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    cursor.execute('''
        SELECT id, url, filename FROM urls 
        WHERE processed = 0 
        ORDER BY id 
        LIMIT 3
    ''')
    
    test_urls = cursor.fetchall()
    conn.close()
    
    if not test_urls:
        print("No URLs found for testing!")
        return
    
    print(f"Testing download with {len(test_urls)} URLs...")
    
    session = requests.Session()
    session.headers.update({
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    })
    
    for i, (url_id, url, original_filename) in enumerate(test_urls, 1):
        print(f"\nTest {i}/{len(test_urls)}: {url}")
        
        try:
            # Generate filename
            url_hash = hashlib.md5(url.encode()).hexdigest()[:8]
            ext = original_filename.split('.')[-1] if original_filename and '.' in original_filename else 'jpg'
            filename = f"test_{url_hash}_{original_filename or 'image'}.{ext}"
            
            # Download
            response = session.get(url, timeout=30, stream=True)
            response.raise_for_status()
            
            # Check content type
            content_type = response.headers.get('content-type', '')
            print(f"  Content-Type: {content_type}")
            
            if not content_type.startswith('image/'):
                print(f"  WARNING: Not an image file!")
                continue
            
            # Save file
            file_path = images_folder / filename
            with open(file_path, 'wb') as f:
                for chunk in response.iter_content(chunk_size=8192):
                    f.write(chunk)
            
            file_size = file_path.stat().st_size
            print(f"  Downloaded: {filename} ({file_size} bytes)")
            
            # Mark as processed in database
            conn = sqlite3.connect(db_path)
            cursor = conn.cursor()
            cursor.execute('UPDATE urls SET processed = 1 WHERE id = ?', (url_id,))
            conn.commit()
            conn.close()
            
            print(f"  Marked as processed in database")
            
        except Exception as e:
            print(f"  ERROR: {e}")
        
        # Wait 3 seconds between downloads
        if i < len(test_urls):
            print("  Waiting 3 seconds...")
            time.sleep(3)
    
    print(f"\nTest completed! Check the {images_folder} folder for downloaded images.")

if __name__ == "__main__":
    test_download()
