"""
PROFESSIONAL IMAGE GENERATOR - ALL CATEGORIES VERSION
======================================================
Features:
✅ ALL Category Types Supported - No Restrictions
✅ Auto Model Selection Based on Category Keywords
✅ 100+ Category Types Enabled
✅ Intelligent Category Mapping
✅ 1920x1080 Full HD Resolution
✅ Professional Quality Output

Author: Professional Image Generation System
Date: 2025
"""

import requests
import json
import time
import hashlib
import random
import base64
from pathlib import Path
from datetime import datetime
from io import BytesIO
import sys
import re

# Install PIL if needed
try:
    from PIL import Image
except ImportError:
    print("📦 Installing Pillow...")
    import subprocess
    subprocess.check_call([sys.executable, "-m", "pip", "install", "pillow"])
    from PIL import Image
    print("✅ Pillow installed!\n")

print("="*80)
print("PROFESSIONAL IMAGE GENERATOR - ALL CATEGORIES VERSION V3.0")
print("="*80)
print("✅ Full HD 1920x1080 | ALL Categories Supported | Smart Model Selection")
print("="*80)
print()

# ============================================
# CONFIGURATION
# ============================================

# API Configuration
API_URL = "https://image.pollinations.ai/prompt/"
OUTPUT_FOLDER = "professional_images"

# Quality Settings
QUALITY_WIDTH = 1920
QUALITY_HEIGHT = 1080

# Safety Settings
SAFETY_ENABLED = True

# ============================================
# COMPREHENSIVE CATEGORY DEFINITIONS
# ============================================

# Main category configurations with model mappings
MAIN_CATEGORIES = {
    # REALISTIC STYLES
    'realistic': {
        'model': 'flux-realism',
        'keywords': ['realistic', 'photorealistic', 'hyperrealistic', 'photo', 'photography'],
        'suffix': 'ultra photorealistic, professional photography, extremely detailed, sharp focus, perfect lighting, 8K UHD, RAW photo, high quality, film grain, Fujifilm XT3, professional color grading, award winning photography',
        'negative': 'cartoon, anime, illustration, painting, drawing, art, sketch, 3d render, deformed, ugly',
    },
    
    # 3D & CGI STYLES
    '3d': {
        'model': 'flux-3d',
        'keywords': ['3d', 'cgi', 'render', 'rendered', '3d-render', 'octane'],
        'suffix': '3D render, octane render, unreal engine 5, ray tracing, ultra detailed 3D model, CGI, volumetric lighting, ambient occlusion, subsurface scattering, physically based rendering, 8K resolution, studio lighting',
        'negative': '2d, flat, cartoon, anime, painting, sketch, low poly, low quality',
    },
    
    # CARTOON & ANIMATION
    'cartoonistic': {
        'model': 'flux-cablyai',
        'keywords': ['cartoonistic', 'cartoon', 'animated', 'animation', 'disney', 'pixar', 'toon'],
        'suffix': 'cartoon style, disney pixar style, animated, colorful, clean lines, vibrant colors, professional animation, studio quality, character design, expressive, polished, high quality cartoon',
        'negative': 'realistic, photo, 3d render, dark, gritty, horror, ugly',
    },
    
    # COMIC & GRAPHIC
    'comic': {
        'model': 'flux-cartoon',
        'keywords': ['comic', 'comic-book', 'graphic-novel', 'pop-art', 'graphic', 'comics'],
        'suffix': 'comic book style, comic art, graphic novel, bold lines, vibrant colors, dynamic composition, pop art, professional comic illustration, ink and color, halftone dots',
        'negative': 'realistic, photo, 3d render, blurry, low quality',
    },
    
    # ANIME & MANGA
    'anime': {
        'model': 'flux-anime',
        'keywords': ['anime', 'manga', 'anime-style', 'manga-style', 'japanese-anime'],
        'suffix': 'anime style, manga art, japanese animation, cel shaded, vibrant colors, expressive eyes, detailed hair, professional anime artwork, studio quality, beautiful lighting',
        'negative': 'realistic, photo, western cartoon, 3d render, ugly, deformed',
    },
    
    # CINEMATIC & FILM
    'cinematic': {
        'model': 'flux',
        'keywords': ['cinematic', 'cinematic-shot', 'movie', 'film', 'hollywood', 'epic'],
        'suffix': 'cinematic shot, movie scene, cinematic lighting, epic composition, dramatic atmosphere, film photography, anamorphic lens, depth of field, color graded, professional production, blockbuster movie quality, 35mm film, IMAX quality',
        'negative': 'amateur, low quality, snapshot, boring composition',
    },
}

# Extended category mappings - maps any category to best model
EXTENDED_CATEGORIES = {
    # REALISTIC VARIATIONS
    'photorealistic': 'realistic',
    'hyperrealistic': 'realistic',
    'photo': 'realistic',
    'photography': 'realistic',
    'professional-photography': 'realistic',
    
    # 3D VARIATIONS
    'cgi': '3d',
    'render': '3d',
    '3d-render': '3d',
    'octane-render': '3d',
    'unreal-engine': '3d',
    
    # CARTOON VARIATIONS
    'cartoon': 'cartoonistic',
    'animated': 'cartoonistic',
    'animation': 'cartoonistic',
    'disney': 'cartoonistic',
    'pixar': 'cartoonistic',
    'toon': 'cartoonistic',
    
    # COMIC VARIATIONS
    'comic-book': 'comic',
    'graphic-novel': 'comic',
    'pop-art': 'comic',
    'comics': 'comic',
    
    # ANIME VARIATIONS
    'manga': 'anime',
    'anime-style': 'anime',
    'manga-style': 'anime',
    
    # CINEMATIC VARIATIONS
    'movie': 'cinematic',
    'film': 'cinematic',
    'hollywood': 'cinematic',
    'epic': 'cinematic',
    'cinematic-shot': 'cinematic',
    
    # ARTISTIC STYLES
    'artistic': 'cinematic',
    'art': 'cinematic',
    'painting': 'cinematic',
    'oil-painting': 'cinematic',
    'watercolor': 'cinematic',
    'digital-art': 'cinematic',
    'digital-painting': 'cinematic',
    'concept-art': 'cinematic',
    'illustration': 'cinematic',
    
    # FANTASY & SCI-FI
    'fantasy': 'cinematic',
    'sci-fi': 'cinematic',
    'science-fiction': 'cinematic',
    'futuristic': 'cinematic',
    'cyberpunk': 'cinematic',
    'steampunk': 'cinematic',
    'space': 'cinematic',
    
    # PORTRAIT & CHARACTER
    'portrait': 'realistic',
    'character': '3d',
    'character-design': '3d',
    'face': 'realistic',
    'headshot': 'realistic',
    
    # ARCHITECTURE & ENVIRONMENT
    'architectural': '3d',
    'architecture': '3d',
    'landscape': 'realistic',
    'nature': 'realistic',
    'cityscape': 'realistic',
    'environment': 'cinematic',
    
    # PRODUCT & COMMERCIAL
    'product': 'realistic',
    'product-photography': 'realistic',
    'commercial': 'realistic',
    'advertising': 'realistic',
    'marketing': 'realistic',
    
    # ABSTRACT & MODERN
    'abstract': 'cinematic',
    'modern': 'cinematic',
    'contemporary': 'cinematic',
    'minimalist': 'cinematic',
    'geometric': 'cinematic',
    
    # SKETCH & DRAWING
    'sketch': 'cinematic',
    'pencil': 'cinematic',
    'drawing': 'cinematic',
    'line-art': 'comic',
    
    # DARK & DRAMATIC
    'dark': 'cinematic',
    'horror': 'cinematic',
    'gothic': 'cinematic',
    'noir': 'cinematic',
    'dramatic': 'cinematic',
    
    # VINTAGE & RETRO
    'vintage': 'realistic',
    'retro': 'realistic',
    '80s': 'cartoonistic',
    '90s': 'cartoonistic',
    'old-school': 'realistic',
    
    # GAME STYLES
    'game': '3d',
    'game-art': '3d',
    'pixel-art': 'cartoonistic',
    'low-poly': '3d',
    'voxel': '3d',
    
    # FASHION & BEAUTY
    'fashion': 'realistic',
    'beauty': 'realistic',
    'glamour': 'realistic',
    'editorial': 'realistic',
    
    # TEXTURE & MATERIAL
    'texture': '3d',
    'material': '3d',
    'pbr': '3d',
    
    # SPECIFIC STYLES
    'impressionist': 'cinematic',
    'expressionist': 'cinematic',
    'surreal': 'cinematic',
    'surrealism': 'cinematic',
    'cubist': 'cinematic',
    'baroque': 'cinematic',
    'renaissance': 'realistic',
    
    # MOOD & ATMOSPHERE
    'moody': 'cinematic',
    'atmospheric': 'cinematic',
    'dreamy': 'cinematic',
    'ethereal': 'cinematic',
    'mystical': 'cinematic',
    'magical': 'cinematic',
    
    # TIME PERIODS
    'medieval': 'cinematic',
    'ancient': 'cinematic',
    'modern-day': 'realistic',
    'post-apocalyptic': 'cinematic',
    
    # CULTURAL STYLES
    'japanese': 'anime',
    'chinese': 'cinematic',
    'korean': 'realistic',
    'western': 'cinematic',
    'eastern': 'cinematic',
    
    # SPECIFIC SUBJECTS
    'animal': 'realistic',
    'wildlife': 'realistic',
    'food': 'realistic',
    'interior': 'realistic',
    'exterior': 'realistic',
    'vehicle': '3d',
    'weapon': '3d',
    'robot': '3d',
    'mecha': 'anime',
}

# Style enhancements for specific categories
CATEGORY_ENHANCEMENTS = {
    'fantasy': 'magical, mystical, enchanted, fantasy world, epic fantasy',
    'sci-fi': 'futuristic, advanced technology, space age, sci-fi elements',
    'cyberpunk': 'neon lights, cyberpunk aesthetic, futuristic city, blade runner style',
    'horror': 'dark, eerie, creepy, horror atmosphere, dramatic shadows',
    'watercolor': 'watercolor painting, soft colors, artistic brush strokes',
    'oil-painting': 'oil painting style, classical art, museum quality',
    'sketch': 'pencil sketch, hand drawn, artistic lines, sketch style',
    'portrait': 'professional portrait, studio lighting, shallow depth of field',
    'landscape': 'beautiful landscape, scenic view, nature photography',
    'product': 'product shot, clean background, professional lighting, commercial quality',
    'architectural': 'architectural photography, professional composition, clean lines',
    'fashion': 'fashion photography, haute couture, editorial style, magazine quality',
    'vintage': 'vintage style, retro aesthetic, aged look, nostalgic',
    'abstract': 'abstract art, artistic composition, creative design',
    'minimalist': 'minimalist design, clean composition, simple elegant',
    'dark': 'dark atmosphere, moody lighting, dramatic shadows',
    'pixel-art': 'pixel art style, retro gaming, 8-bit aesthetic',
    'steampunk': 'steampunk aesthetic, Victorian era, brass and copper, mechanical',
}

# ============================================
# INTELLIGENT CATEGORY DETECTION
# ============================================

def detect_category_type(category):
    """
    Intelligently detect which main category to use based on input
    
    Args:
        category: Input category string
    
    Returns:
        Main category name
    """
    category_lower = category.lower().strip()
    category_normalized = category_lower.replace(' ', '-').replace('_', '-')
    
    # Direct match in extended categories
    if category_normalized in EXTENDED_CATEGORIES:
        return EXTENDED_CATEGORIES[category_normalized]
    
    # Check if it's already a main category
    if category_normalized in MAIN_CATEGORIES:
        return category_normalized
    
    # Keyword matching - check if category contains keywords
    for main_cat, config in MAIN_CATEGORIES.items():
        for keyword in config['keywords']:
            if keyword in category_normalized or category_normalized in keyword:
                return main_cat
    
    # Default fallback based on common patterns
    if any(word in category_normalized for word in ['real', 'photo']):
        return 'realistic'
    elif any(word in category_normalized for word in ['3d', 'cgi', 'render']):
        return '3d'
    elif any(word in category_normalized for word in ['cartoon', 'anim', 'disney']):
        return 'cartoonistic'
    elif any(word in category_normalized for word in ['comic', 'manga']):
        return 'comic'
    elif any(word in category_normalized for word in ['anime', 'manga']):
        return 'anime'
    elif any(word in category_normalized for word in ['cinema', 'movie', 'film']):
        return 'cinematic'
    
    # If no match, default to cinematic (most versatile)
    print(f"   ℹ️ Unknown category '{category}', using 'cinematic' as default")
    return 'cinematic'


def enhance_prompt_for_category(prompt, category):
    """
    Enhance prompt based on category with intelligent additions
    
    Args:
        prompt: Original user prompt
        category: Selected category
    
    Returns:
        Enhanced prompt string
    """
    category_lower = category.lower().strip().replace(' ', '-').replace('_', '-')
    
    # Detect main category
    main_category = detect_category_type(category)
    category_config = MAIN_CATEGORIES[main_category]
    
    # Base quality prefix
    quality_prefix = "masterpiece, best quality, ultra detailed, professional, perfect composition"
    
    # Get main category suffix
    style_suffix = category_config['suffix']
    
    # Add specific category enhancement if available
    extra_enhancement = ""
    if category_lower in CATEGORY_ENHANCEMENTS:
        extra_enhancement = f", {CATEGORY_ENHANCEMENTS[category_lower]}"
    
    # Technical enhancers
    technical = "perfect anatomy, perfect perspective, golden ratio composition"
    
    # Build enhanced prompt
    enhanced = f"{quality_prefix}, {prompt}, {style_suffix}{extra_enhancement}, {technical}"
    
    # Add category-specific camera/render details
    if main_category == 'realistic':
        enhanced += ", shot on Canon EOS R5, 85mm lens, f/1.4, professional photography"
    elif main_category == '3d':
        enhanced += ", rendered in Octane, global illumination, HDRI lighting, 8K quality"
    elif main_category == 'cinematic':
        enhanced += ", cinematic composition, film grain, anamorphic lens"
    elif main_category == 'anime':
        enhanced += ", trending on pixiv, studio quality"
    elif main_category == 'cartoonistic':
        enhanced += ", Disney animation studios, Pixar quality"
    elif main_category == 'comic':
        enhanced += ", professional comic artist, Marvel style"
    
    return enhanced


def get_negative_prompt(category):
    """
    Get negative prompt based on category
    
    Args:
        category: Category name
    
    Returns:
        Negative prompt string
    """
    main_category = detect_category_type(category)
    return MAIN_CATEGORIES[main_category].get('negative', '')


def get_model_for_category(category):
    """
    Get the best model for a given category
    
    Args:
        category: Category name
    
    Returns:
        Model name
    """
    main_category = detect_category_type(category)
    return MAIN_CATEGORIES[main_category]['model']


def get_optimized_seed(category, prompt):
    """
    Generate optimized seed based on category and prompt
    
    Args:
        category: Category name
        prompt: Prompt text
    
    Returns:
        Optimized seed value
    """
    main_category = detect_category_type(category)
    
    # Seed ranges for different categories
    seed_ranges = {
        'realistic': (1000, 5000),
        '3d': (5000, 10000),
        'cartoonistic': (10000, 15000),
        'comic': (15000, 20000),
        'anime': (20000, 25000),
        'cinematic': (25000, 30000),
    }
    
    min_seed, max_seed = seed_ranges.get(main_category, (1000, 30000))
    prompt_hash = int(hashlib.md5(prompt.encode()).hexdigest()[:8], 16)
    random_component = random.randint(0, 1000)
    base_seed = (prompt_hash + random_component) % (max_seed - min_seed)
    optimized_seed = min_seed + base_seed
    
    return optimized_seed


# ============================================
# IMAGE GENERATOR CLASS
# ============================================
class ProfessionalImageGenerator:
    """Professional image generation system supporting ALL category types"""
    
    def __init__(self):
        self.generation_count = 0
        self.create_output_folders()
        print("✅ ProfessionalImageGenerator initialized")
        print(f"📁 Output folder: {OUTPUT_FOLDER}/")
        print(f"🎨 ALL Categories Supported - No Restrictions")
        print(f"🤖 Intelligent Model Selection Enabled")
    
    def create_output_folders(self):
        """Create organized output folder structure"""
        base_path = Path(OUTPUT_FOLDER)
        base_path.mkdir(exist_ok=True)
        
        # Create folders for main categories
        for category in MAIN_CATEGORIES.keys():
            (base_path / category).mkdir(exist_ok=True)
        
        # Create general folder for other categories
        (base_path / "other").mkdir(exist_ok=True)
        (base_path / "metadata").mkdir(exist_ok=True)
        (base_path / "tests").mkdir(exist_ok=True)
    
    def generate_single_image_bytes(self, prompt, category, model_name, width=None, height=None):
        """
        Generate single image and return bytes for FastAPI
        Accepts ANY category type - no restrictions

        Args:
            prompt: The text prompt
            category: ANY category name (used for prompt enhancement)
            model_name: Specific model to use (flux, nano-banana, turbo)
            width: Image width (default 1920)
            height: Image height (default 1080)

        Returns:
            Image bytes or None if failed
        """
        # Use default dimensions if not specified
        if width is None:
            width = QUALITY_WIDTH
        if height is None:
            height = QUALITY_HEIGHT

        self.generation_count += 1

        # Normalize category
        category = category.lower().strip()

        # Detect main category for prompt enhancement
        main_category = detect_category_type(category)

        # Use provided model_name directly
        model = model_name

        # Enhance prompt
        enhanced_prompt = enhance_prompt_for_category(prompt, category)
        negative_prompt = get_negative_prompt(category)

        # Generate optimized seed
        seed = get_optimized_seed(category, prompt)

        # Build URL
        url = f"{API_URL}{requests.utils.quote(enhanced_prompt)}"

        # Build parameters
        params = {
            'width': width,
            'height': height,
            'model': model,
            'seed': seed,
            'nologo': 'true',
            'enhance': 'true',
            'safe': str(SAFETY_ENABLED).lower(),
            'nofeed': 'true'
        }

        if negative_prompt:
            params['negative_prompt'] = negative_prompt

        print(f"\n🎨 Generating Image #{self.generation_count}")
        print(f"   Category: {category.upper()} → Main: {main_category.upper()}")
        print(f"   Model: {model}")
        print(f"   Resolution: {width}x{height}")
        print(f"   Seed: {seed}")
        print(f"   Prompt: {prompt[:60]}...")
        print(f"   ⏳ Processing (15-30 seconds)...")

        try:
            response = requests.get(url, params=params, timeout=120)

            if response.status_code == 200:
                # Load and process image
                image = Image.open(BytesIO(response.content))

                # Convert to RGB if needed
                if image.mode != 'RGB':
                    image = image.convert('RGB')

                # Save to BytesIO
                output = BytesIO()
                image.save(output, format='PNG', quality=100, optimize=False)
                output.seek(0)

                image_bytes = output.getvalue()
                image_size_mb = len(image_bytes) / (1024 * 1024)

                print(f"   ✅ SUCCESS")
                print(f"   📊 Size: {image_size_mb:.2f} MB")
                print(f"   🎯 Quality: Professional HD")

                return image_bytes

            else:
                print(f"   ❌ API Error: HTTP {response.status_code}")
                print(f"   Response: {response.text[:200]}")
                return None

        except requests.exceptions.Timeout:
            print(f"   ❌ Timeout: Request took longer than 120 seconds")
            return None
        except Exception as e:
            print(f"   ❌ Generation Failed: {str(e)}")
            import traceback
            traceback.print_exc()
            return None

    def generate_multiple_images(self, prompt, category, model_name, width=None, height=None, image_count=1):
        """
        Generate multiple images and return list with names and base64 data

        Args:
            prompt: The text prompt
            category: Category name for enhancement
            model_name: Model to use
            width: Image width
            height: Image height
            image_count: Number of images to generate

        Returns:
            List of dicts with 'name' and 'base64' keys
        """
        images = []

        for i in range(image_count):
            print(f"\n📸 Generating image {i+1}/{image_count}")

            # Generate image bytes
            image_bytes = self.generate_single_image_bytes(
                prompt=prompt,
                category=category,
                model_name=model_name,
                width=width,
                height=height
            )

            if image_bytes is None:
                print(f"   ❌ Failed to generate image {i+1}")
                continue

            # Generate unique name
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]
            prompt_hash = hashlib.md5(f"{prompt}_{i}".encode()).hexdigest()[:6]
            prompt_words = prompt.split()[:3]
            prompt_brief = "_".join(prompt_words).lower().replace(",", "").replace(".", "")[:15]
            image_name = f"{category}_{prompt_brief}_{timestamp}_{i+1}_{prompt_hash}"

            # Convert to base64
            base64_data = base64.b64encode(image_bytes).decode('utf-8')

            images.append({
                "name": image_name,
                "base64": base64_data
            })

            print(f"   ✅ Generated: {image_name}")

            # Small delay between generations
            if i < image_count - 1:
                time.sleep(1)

        return images

    def generate_and_save_image(self, prompt, category, model_name="flux", width=None, height=None):
        """
        Generate image and save to disk

        Args:
            prompt: The text prompt
            category: Category name
            model_name: Model to use
            width: Image width
            height: Image height

        Returns:
            Dictionary with result info
        """
        if width is None:
            width = QUALITY_WIDTH
        if height is None:
            height = QUALITY_HEIGHT

        image_bytes = self.generate_single_image_bytes(prompt, category, model_name, width, height)
        
        if image_bytes is None:
            return {"success": False, "error": "Image generation failed"}
        
        # Determine folder
        main_category = detect_category_type(category)
        if main_category in MAIN_CATEGORIES:
            folder = main_category
        else:
            folder = "other"
        
        # Generate filename
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]
        prompt_hash = hashlib.md5(prompt.encode()).hexdigest()[:6]
        prompt_words = prompt.split()[:3]
        prompt_brief = "_".join(prompt_words).lower().replace(",", "").replace(".", "")[:20]
        filename = f"{category}_{prompt_brief}_{timestamp}_{prompt_hash}.png"
        
        # Save to disk
        output_path = Path(OUTPUT_FOLDER) / folder / filename
        with open(output_path, 'wb') as f:
            f.write(image_bytes)
        
        # Save metadata
        metadata = {
            "generation_info": {
                "timestamp": datetime.now().isoformat(),
                "generation_number": self.generation_count,
            },
            "prompt_data": {
                "original": prompt,
                "enhanced": enhance_prompt_for_category(prompt, category),
                "negative": get_negative_prompt(category)
            },
            "technical_details": {
                "category": category,
                "main_category": main_category,
                "model": get_model_for_category(category),
                "resolution": f"{width}x{height}",
                "file_size_mb": len(image_bytes) / (1024 * 1024),
                "seed": get_optimized_seed(category, prompt)
            }
        }
        
        metadata_path = Path(OUTPUT_FOLDER) / "metadata" / f"{filename.replace('.png', '.json')}"
        with open(metadata_path, 'w') as f:
            json.dump(metadata, f, indent=2)
        
        print(f"   💾 Saved: {output_path}")
        print(f"   📄 Metadata: {metadata_path}")
        
        return {
            "success": True,
            "path": str(output_path),
            "metadata_path": str(metadata_path),
            "metadata": metadata
        }
    
    def get_all_categories_info(self):
        """Get information about all supported categories"""
        return {
            "main_categories": {
                name: {
                    "model": config['model'],
                    "description": config.get('description', ''),
                    "keywords": config['keywords']
                }
                for name, config in MAIN_CATEGORIES.items()
            },
            "extended_categories": EXTENDED_CATEGORIES,
            "total_supported": len(EXTENDED_CATEGORIES) + len(MAIN_CATEGORIES),
            "message": "All category types are supported. Unknown categories will be intelligently mapped to the best model."
        }
    
    def test_multiple_categories(self, prompt, categories_list):
        """
        Test generation with multiple categories
        
        Args:
            prompt: Prompt to use
            categories_list: List of categories to test
        
        Returns:
            List of results
        """
        print("\n" + "="*80)
        print(f"🧪 TESTING {len(categories_list)} CATEGORIES")
        print("="*80)
        print(f"📝 Prompt: {prompt}")
        print("="*80)
        
        results = []
        
        for idx, category in enumerate(categories_list, 1):
            print(f"\n[{idx}/{len(categories_list)}] Testing: {category}")
            print("-" * 60)
            
            result = self.generate_and_save_image(prompt, category)
            results.append({
                "category": category,
                "result": result
            })
            
            if idx < len(categories_list):
                print("\n⏳ Waiting 2 seconds...")
                time.sleep(2)
        
        # Summary
        successful = sum(1 for r in results if r['result'].get('success', False))
        print("\n" + "="*80)
        print("✅ TEST COMPLETE")
        print("="*80)
        print(f"Success: {successful}/{len(results)}")
        print(f"Failed: {len(results) - successful}/{len(results)}")
        print("="*80)
        
        return results


# ============================================
# TESTING FUNCTIONS
# ============================================

def test_popular_categories():
    """Test most popular categories"""
    
    print("="*80)
    print("TESTING POPULAR CATEGORIES")
    print("="*80)
    
    generator = ProfessionalImageGenerator()
    
    test_cases = [
        {"prompt": "A beautiful sunset over mountains", "category": "realistic"},
        {"prompt": "A futuristic robot character", "category": "3d"},
        {"prompt": "A cute cartoon dog playing", "category": "cartoonistic"},
        {"prompt": "A superhero in action pose", "category": "comic"},
        {"prompt": "An anime girl with blue hair", "category": "anime"},
        {"prompt": "An epic battle scene", "category": "cinematic"},
        {"prompt": "A magical fantasy castle", "category": "fantasy"},
        {"prompt": "A cyberpunk city at night", "category": "cyberpunk"},
        {"prompt": "A professional portrait photo", "category": "portrait"},
        {"prompt": "A watercolor painting of flowers", "category": "watercolor"},
    ]
    
    results = []
    
    for idx, test in enumerate(test_cases, 1):
        print(f"\n[{idx}/{len(test_cases)}] {test['category'].upper()}")
        print(f"Prompt: {test['prompt']}")
        print("-" * 60)
        
        result = generator.generate_and_save_image(
            prompt=test['prompt'],
            category=test['category']
        )
        
        results.append(result)
        
        if idx < len(test_cases):
            print("\n⏳ Waiting 2 seconds...")
            time.sleep(2)
    
    successful = sum(1 for r in results if r.get('success', False))
    print("\n" + "="*80)
    print("✅ POPULAR CATEGORIES TEST COMPLETE")
    print("="*80)
    print(f"Success: {successful}/{len(results)}")
    print("="*80)


def test_all_category_types():
    """Test various category types to demonstrate flexibility"""
    
    print("="*80)
    print("TESTING ALL CATEGORY TYPES")
    print("="*80)
    
    generator = ProfessionalImageGenerator()
    
    # Test diverse categories
    test_categories = [
        "realistic", "3d", "cartoonistic", "comic", "anime", "cinematic",
        "fantasy", "sci-fi", "cyberpunk", "watercolor", "oil-painting",
        "sketch", "portrait", "landscape", "product", "architectural",
        "horror", "vintage", "pixel-art", "fashion"
    ]
    
    prompt = "A majestic dragon in a mystical setting"
    
    results = generator.test_multiple_categories(prompt, test_categories)
    
    return results


def quick_test():
    """Quick test with 3 different styles"""
    print("="*80)
    print("QUICK TEST - 3 CATEGORIES")
    print("="*80)
    
    generator = ProfessionalImageGenerator()
    
    test_cases = [
        {"prompt": "A red sports car", "category": "realistic"},
        {"prompt": "A cute robot character", "category": "3d"},
        {"prompt": "A magical forest scene", "category": "fantasy"}
    ]
    
    for idx, test in enumerate(test_cases, 1):
        print(f"\n[{idx}/{len(test_cases)}] {test['category'].upper()}")
        result = generator.generate_and_save_image(
            prompt=test['prompt'],
            category=test['category']
        )
        
        if idx < len(test_cases):
            time.sleep(2)
    
    print("\n" + "="*80)
    print("✅ QUICK TEST COMPLETE")
    print("="*80)


def test_custom_categories():
    """Test with completely custom category names"""
    print("="*80)
    print("TESTING CUSTOM CATEGORY NAMES")
    print("="*80)
    print("Testing system's ability to handle any category name...")
    print("="*80)
    
    generator = ProfessionalImageGenerator()
    
    custom_categories = [
        "epic-battle-scene",
        "professional-headshot",
        "game-character-design",
        "book-cover-art",
        "movie-poster",
        "album-cover",
        "t-shirt-design",
        "logo-design",
        "children-book-illustration",
        "scientific-diagram"
    ]
    
    prompt = "A creative and professional design"
    
    results = generator.test_multiple_categories(prompt, custom_categories)
    
    return results


# ============================================
# MAIN FUNCTION
# ============================================

def main():
    """Main function with interactive menu"""
    
    print("\n" + "="*80)
    print("PROFESSIONAL IMAGE GENERATOR - ALL CATEGORIES VERSION")
    print("="*80)
    print("\n✅ ALL CATEGORY TYPES SUPPORTED")
    print("✅ NO RESTRICTIONS - ANY CATEGORY NAME ACCEPTED")
    print("✅ INTELLIGENT MODEL SELECTION")
    print("✅ 100+ CATEGORY MAPPINGS")
    
    print("\n" + "="*80)
    print("AVAILABLE MAIN CATEGORIES")
    print("="*80)
    for name, config in MAIN_CATEGORIES.items():
        print(f"  • {name.upper()}: {config['model']}")
    
    print("\n" + "="*80)
    print("EXAMPLE SUPPORTED CATEGORIES")
    print("="*80)
    example_categories = [
        "realistic", "3d", "cartoonistic", "comic", "anime", "cinematic",
        "fantasy", "sci-fi", "cyberpunk", "watercolor", "oil-painting",
        "sketch", "portrait", "landscape", "horror", "vintage", "pixel-art",
        "fashion", "product", "architectural", "steampunk", "dark", "retro",
        "abstract", "minimalist", "game", "manga", "disney", "pixar"
    ]
    print(", ".join(example_categories))
    print("\n...and MANY MORE! System accepts ANY category name.")
    
    print("\n" + "="*80)
    print("TESTING MENU")
    print("="*80)
    print("1️⃣  Quick Test (3 images)")
    print("2️⃣  Test Popular Categories (10 images)")
    print("3️⃣  Test All Category Types (20 images)")
    print("4️⃣  Test Custom Categories (10 images)")
    print("5️⃣  Custom Single Generation")
    print("6️⃣  Show All Supported Categories")
    print("7️⃣  Exit")
    print("="*80)
    
    choice = input("\nSelect option (1-7): ").strip()
    
    if choice == '1':
        quick_test()
    elif choice == '2':
        test_popular_categories()
    elif choice == '3':
        test_all_category_types()
    elif choice == '4':
        test_custom_categories()
    elif choice == '5':
        prompt = input("\nEnter prompt: ").strip()
        category = input("Enter category (any name): ").strip()
        generator = ProfessionalImageGenerator()
        generator.generate_and_save_image(prompt, category)
    elif choice == '6':
        generator = ProfessionalImageGenerator()
        info = generator.get_all_categories_info()
        print("\n" + "="*80)
        print("ALL SUPPORTED CATEGORIES")
        print("="*80)
        print(f"\nMain Categories: {len(info['main_categories'])}")
        for name in info['main_categories'].keys():
            print(f"  • {name}")
        print(f"\nExtended Categories: {len(info['extended_categories'])}")
        categories_list = list(info['extended_categories'].keys())
        for i in range(0, len(categories_list), 5):
            print(f"  {', '.join(categories_list[i:i+5])}")
        print(f"\n{info['message']}")
        print("="*80)
    elif choice == '7':
        print("\n👋 Goodbye!")
        return
    else:
        print("\n❌ Invalid option")
        return
    
    print("\n" + "="*80)
    print("🎉 OPERATION COMPLETE")
    print(f"📁 Check images in: {OUTPUT_FOLDER}/")
    print("="*80)


if __name__ == "__main__":
    main()