#!/usr/bin/env python3
"""
Review and selectively delete problematic images
"""

import os
import glob

def list_all_images():
    """List all generated images for review"""
    base_dir = '/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images'
    
    all_images = []
    
    # Find all image files
    for subfolder in ['violations', 'chains', 'cuisine', 'summaries']:
        folder_path = os.path.join(base_dir, subfolder)
        if os.path.exists(folder_path):
            pattern = os.path.join(folder_path, '*.jpg')
            images = glob.glob(pattern)
            for img in images:
                all_images.append({
                    'path': img,
                    'filename': os.path.basename(img),
                    'subfolder': subfolder,
                    'size': os.path.getsize(img) if os.path.exists(img) else 0
                })
    
    return all_images

def delete_specific_images(image_list):
    """Delete specific images from a list"""
    deleted = []
    
    for img_path in image_list:
        try:
            if os.path.exists(img_path):
                os.remove(img_path)
                deleted.append(img_path)
                print(f"✓ Deleted: {img_path}")
            else:
                print(f"⚠ File not found: {img_path}")
        except Exception as e:
            print(f"✗ Error deleting {img_path}: {e}")
    
    return deleted

def interactive_review():
    """Interactively review images"""
    images = list_all_images()
    
    if not images:
        print("No images found to review")
        return
    
    print(f"Found {len(images)} images to review")
    print("\nImages by category:")
    
    by_category = {}
    for img in images:
        cat = img['subfolder']
        if cat not in by_category:
            by_category[cat] = []
        by_category[cat].append(img)
    
    for category, imgs in by_category.items():
        print(f"\n{category.upper()}: {len(imgs)} images")
        for img in imgs:
            print(f"  - {img['filename']} ({img['size']:,} bytes)")
    
    return images

def main():
    """Main review interface"""
    print("=== Image Review Tool ===")
    print("Options:")
    print("1. List all images")
    print("2. Delete all images and start fresh")
    print("3. Delete specific images (you provide list)")
    print("4. Just show count by category")
    
    choice = input("\nChoice (1-4): ")
    
    if choice == '1':
        images = interactive_review()
        
    elif choice == '2':
        print("\n⚠️  WARNING: This will delete ALL generated images!")
        confirm = input("Type 'DELETE ALL' to confirm: ")
        
        if confirm == 'DELETE ALL':
            base_dir = '/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images'
            deleted_count = 0
            
            for subfolder in ['violations', 'chains', 'cuisine', 'summaries']:
                folder_path = os.path.join(base_dir, subfolder)
                if os.path.exists(folder_path):
                    pattern = os.path.join(folder_path, '*.jpg')
                    images = glob.glob(pattern)
                    for img in images:
                        try:
                            os.remove(img)
                            deleted_count += 1
                            print(f"✓ Deleted: {os.path.basename(img)}")
                        except Exception as e:
                            print(f"✗ Error: {e}")
            
            print(f"\n✓ Deleted {deleted_count} images")
            
            # Also delete metadata files
            metadata_files = [
                os.path.join(base_dir, 'generation_metadata.json'),
                os.path.join(base_dir, 'generation_metadata_v2.json')
            ]
            
            for meta_file in metadata_files:
                if os.path.exists(meta_file):
                    os.remove(meta_file)
                    print(f"✓ Deleted metadata: {os.path.basename(meta_file)}")
        else:
            print("Cancelled")
    
    elif choice == '3':
        images = interactive_review()
        print("\nTo delete specific images, provide filenames separated by spaces")
        print("Example: rodent_1.jpg closure_3.jpg temperature_2.jpg")
        
        filenames = input("\nFilenames to delete: ").strip().split()
        
        if filenames:
            base_dir = '/var/www/twin-digital-media/public_html/_sites/cleankitchens/assets/images'
            to_delete = []
            
            for filename in filenames:
                # Find the file in any subfolder
                found = False
                for subfolder in ['violations', 'chains', 'cuisine', 'summaries']:
                    filepath = os.path.join(base_dir, subfolder, filename)
                    if os.path.exists(filepath):
                        to_delete.append(filepath)
                        found = True
                        break
                
                if not found:
                    print(f"⚠ File not found: {filename}")
            
            if to_delete:
                print(f"\nWill delete {len(to_delete)} files:")
                for path in to_delete:
                    print(f"  - {path}")
                
                confirm = input("\nProceed? (y/n): ")
                if confirm.lower() == 'y':
                    deleted = delete_specific_images(to_delete)
                    print(f"\n✓ Deleted {len(deleted)} files")
    
    elif choice == '4':
        images = list_all_images()
        by_category = {}
        total_size = 0
        
        for img in images:
            cat = img['subfolder']
            if cat not in by_category:
                by_category[cat] = {'count': 0, 'size': 0}
            by_category[cat]['count'] += 1
            by_category[cat]['size'] += img['size']
            total_size += img['size']
        
        print(f"\nImage Summary:")
        for category, stats in by_category.items():
            size_mb = stats['size'] / (1024 * 1024)
            print(f"{category}: {stats['count']} images ({size_mb:.1f} MB)")
        
        print(f"\nTotal: {len(images)} images ({total_size / (1024 * 1024):.1f} MB)")

if __name__ == "__main__":
    main()