import re
from client import get_openrouter_client

def analyze_slides_batch(client, slides_data, batch_size=1):
    """Process slides individually with specialized AI agents"""
    print(f"  Processing {len(slides_data)} slides individually...")
    
    all_results = {}
    
    for i, slide_data in enumerate(slides_data):
        slide_num = slide_data["page_num"]
        print(f"    🔍 Analyzing slide {slide_num} ({i+1}/{len(slides_data)})...")
        
        # Define specialized agents
        agents = {
            'content_extractor': {
                'name': 'Content Extractor',
                'prompt': 'Extract and summarize the key textual content from this slide. Focus on headlines, bullet points, and main messages.'
            },
            'visual_analyzer': {
                'name': 'Visual Analyzer', 
                'prompt': 'Analyze the visual design elements of this slide. Comment on layout, colors, typography, and visual hierarchy.'
            },
            'data_interpreter': {
                'name': 'Data Interpreter',
                'prompt': 'Identify and interpret any numerical data, charts, graphs, or metrics present on this slide.'
            },
            'message_evaluator': {
                'name': 'Message Evaluator',
                'prompt': 'Evaluate the effectiveness of the message delivery and communication strategy on this slide.'
            },
            'improvement_suggestor': {
                'name': 'Improvement Suggestor',
                'prompt': 'Suggest specific improvements for this slide in terms of clarity, impact, and effectiveness.'
            }
        }
        
        slide_analysis = {}
        
        # Analyze with each specialized agent
        for j, (agent_key, agent_config) in enumerate(agents.items()):
            print(f"      🤖 Running {agent_config['name']} ({j+1}/5)...")
            
            messages = [
                {
                    "role": "system",
                    "content": f"You are a {agent_config['name']} specialized in analyzing pitch deck slides. {agent_config['prompt']}"
                },
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": f"Analyze slide {slide_num}:"},
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:image/png;base64,{slide_data['base64']}"
                            }
                        }
                    ]
                }
            ]
            
            try:
                print(f"        📡 Sending API request...")
                response = client.chat.completions.create(
                    model="gpt-4o-mini",
                    messages=messages,
                    max_tokens=500
                )
                
                analysis = response.choices[0].message.content.strip()
                print(f"        ✅ {agent_config['name']} completed ({len(analysis)} chars)")
                
                slide_analysis[agent_key] = {
                    'agent': agent_config['name'],
                    'analysis': analysis
                }
                
            except Exception as e:
                print(f"        ❌ {agent_config['name']} failed: {str(e)}")
                slide_analysis[agent_key] = {
                    'agent': agent_config['name'],
                    'analysis': f"Error analyzing slide {slide_num}: {str(e)}"
                }
        
        all_results[slide_num] = slide_analysis
        print(f"    ✅ Slide {slide_num} analysis complete")
    
    print(f"  🎉 All {len(slides_data)} slides analyzed successfully!")
    return all_results
