#!/usr/bin/env python
"""
BaoLife Extracurricular Activity Image Generator

Generates AI images for extracurricular activities in education_manager.py.

Usage:
    python generate_extracurriculars.py --all
    python generate_extracurriculars.py --preview
"""

import argparse
import asyncio
import logging
from image_generation import ImageGenerator, generate_and_cache_image

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# ============================================================
# Extracurricular Activity Prompts
# ============================================================

EXTRACURRICULAR_PROMPTS = [
    {
        "name": "Debate Team",
        "prompt": "high school debate team classroom with podiums and students debating",
        "event_type": "debate_team",
        "priority": 7
    },
    {
        "name": "Robotics Team",
        "prompt": "high school robotics team workshop with students building robots and technology equipment",
        "event_type": "robotics_team",
        "priority": 7
    },
    {
        "name": "Baseball",
        "prompt": "high school baseball team on field with players in uniforms",
        "event_type": "baseball_team",
        "priority": 7
    },
    {
        "name": "Basketball",
        "prompt": "high school basketball team on indoor court with players practicing",
        "event_type": "basketball_team",
        "priority": 7
    },
    {
        "name": "Soccer",
        "prompt": "high school soccer team on outdoor field with players in uniforms",
        "event_type": "soccer_team",
        "priority": 7
    },
    {
        "name": "Football",
        "prompt": "high school american football team on field with players in uniforms and equipment",
        "event_type": "football_team",
        "priority": 7
    },
]


# ============================================================
# Generation Functions
# ============================================================

async def generate_all_extracurriculars(provider: str = 'imagen4', preview: bool = False):
    """Generate all extracurricular activity images"""
    total = len(EXTRACURRICULAR_PROMPTS)

    logger.info(f"{'='*70}")
    logger.info(f"Extracurricular Activity Image Generation")
    logger.info(f"Provider: {provider.upper()}")
    logger.info(f"Total activities: {total}")
    logger.info(f"{'='*70}\n")

    if preview:
        logger.info("PREVIEW MODE - Showing what will be generated:\n")
        for i, activity in enumerate(EXTRACURRICULAR_PROMPTS, 1):
            logger.info(f"{i}. {activity['name']}")
            logger.info(f"   Prompt: {activity['prompt']}")
            logger.info(f"   Event Type: {activity['event_type']}")
            logger.info(f"   Category: education_extracurricular\n")

        logger.info(f"{'='*70}")
        logger.info(f"To generate these {total} images, run:")
        logger.info(f"  python generate_extracurriculars.py --all")
        logger.info(f"{'='*70}")
        return

    # Generate images
    success_count = 0
    failed = []

    for i, activity in enumerate(EXTRACURRICULAR_PROMPTS, 1):
        logger.info(f"\n[{i}/{total}] Generating: {activity['name']}")
        logger.info(f"Prompt: {activity['prompt']}")

        try:
            image_url = await generate_and_cache_image(
                prompt=activity['prompt'],
                event_type=activity['event_type'],
                event_category='education_extracurricular',
                style='cozy_cartoon',
                use_cache=True,
                priority=activity['priority'],
                provider=provider
            )

            if image_url:
                logger.info(f"✓ Success: {image_url[:80]}...")
                success_count += 1
            else:
                logger.error(f"✗ Failed to generate image")
                failed.append(activity['name'])

        except Exception as e:
            logger.error(f"✗ Error: {e}")
            failed.append(activity['name'])

        # Rate limiting
        if i < total:
            logger.info("Waiting 3 seconds before next request...")
            await asyncio.sleep(3)

    # Summary
    logger.info(f"\n{'='*70}")
    logger.info(f"GENERATION COMPLETE")
    logger.info(f"{'='*70}")
    logger.info(f"Total: {total} activities")
    logger.info(f"Success: {success_count}")
    logger.info(f"Failed: {len(failed)}")

    if failed:
        logger.warning(f"\nFailed activities:")
        for name in failed:
            logger.warning(f"  - {name}")

    logger.info(f"\n{'='*70}")
    logger.info(f"Next steps:")
    logger.info(f"1. Verify images in database:")
    logger.info(f"   SELECT * FROM generated_images WHERE event_category = 'education_extracurricular';")
    logger.info(f"2. Update education_manager.py:")
    logger.info(f"   python update_asset_urls.py --update --backup")
    logger.info(f"{'='*70}")


# ============================================================
# Main
# ============================================================

async def main():
    parser = argparse.ArgumentParser(
        description="Generate AI images for BaoLife extracurricular activities"
    )

    parser.add_argument(
        '--provider',
        choices=['imagen4', 'flux', 'dalle3'],
        default='imagen4',
        help='Image generation provider (default: imagen4)'
    )

    parser.add_argument(
        '--all',
        action='store_true',
        help='Generate all extracurricular activity images'
    )

    parser.add_argument(
        '--preview',
        action='store_true',
        help='Preview what will be generated without actually generating'
    )

    args = parser.parse_args()

    # Default to preview if no action specified
    if not args.all and not args.preview:
        args.preview = True

    try:
        await generate_all_extracurriculars(
            provider=args.provider,
            preview=args.preview
        )
    except Exception as e:
        logger.error(f"Error: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    asyncio.run(main())
