print('🟡 ANALYSIS.PY: Starting import...', flush=True)
import re
from client import get_openrouter_client
print('🟡 ANALYSIS.PY: Import complete!', flush=True)

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...", flush=True)
    
    all_results = {}
    
    for i, slide_data in enumerate(slides_data):
        slide_num = slide_data["page_num"]
        print(f"    🔍 Starting analysis of slide {slide_num} ({i+1}/{len(slides_data)})...", flush=True)
        
        # Define specialized agents with critical pitch deck questions
        agents = {
            'problem_analyzer': {
                'name': 'Problem Analysis',
                'prompt': '''Analyze this slide focusing on these critical questions:
                
1. What's the core pain point being addressed?
2. Is it backed by data or evidence?
3. How big is the market impact of this problem?
4. Why do existing solutions fail to solve this?

Provide clear, specific answers to each question based on what you see in the slide.'''
            },
            'solution_evaluator': {
                'name': 'Solution Evaluation',
                'prompt': '''Evaluate this slide focusing on these critical questions:

1. How does this solution outperform competitors?
2. Is there proof of value (metrics, testimonials, case studies)?
3. Can it scale effectively?
4. Is the solution clearly explained and understandable?

Provide clear, specific answers to each question based on what you see in the slide.'''
            },
            'market_opportunity_assessor': {
                'name': 'Market Opportunity Assessment',
                'prompt': '''Assess this slide focusing on these critical questions:

1. What's the market size (TAM/SAM/SOM)?
2. Is the market growing or declining?
3. Are target customers clearly defined?
4. Will customers actually pay for this?

Provide clear, specific answers to each question based on what you see in the slide.'''
            },
            'traction_evaluator': {
                'name': 'Traction Evaluation',
                'prompt': '''Evaluate this slide focusing on these critical questions:

1. What metrics demonstrate market demand?
2. Is the traction sustainable or just a one-time spike?
3. How will funding accelerate this growth?
4. Is growth trending upward consistently?

Provide clear, specific answers to each question based on what you see in the slide.'''
            },
            'funding_analyzer': {
                'name': 'Funding & Ask Analysis',
                'prompt': '''Analyze this slide focusing on these critical questions:

1. How much funding is being raised?
2. How will the funds be allocated and used?
3. What specific milestones are targeted with this funding?
4. Is the valuation justified based on traction and market?

Provide clear, specific answers to each question based on what you see in the slide.'''
            }
        }
        
        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) for slide {slide_num}...", flush=True)
            
            messages = [
                {
                    "role": "system",
                    "content": f"You are a pitch deck analyst specialized in {agent_config['name']}. Answer the critical questions based on what you observe in the slide. If a question doesn't apply to this slide, say 'Not applicable to this slide' and briefly explain why."
                },
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": f"Analyze slide {slide_num} and answer these critical questions:\n\n{agent_config['prompt']}"},
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:image/png;base64,{slide_data['base64']}"
                            }
                        }
                    ]
                }
            ]
            
            try:
                print(f"        📡 Sending API request to {agent_config['name']}...", flush=True)
                response = client.chat.completions.create(
                    model="gpt-4o-mini",
                    messages=messages,
                    max_tokens=800
                )
                
                analysis = response.choices[0].message.content.strip()
                print(f"        ✅ {agent_config['name']} completed for slide {slide_num} ({len(analysis)} chars)", flush=True)
                
                slide_analysis[agent_key] = {
                    'agent': agent_config['name'],
                    'analysis': analysis
                }
                
            except Exception as e:
                print(f"        ❌ {agent_config['name']} failed for slide {slide_num}: {str(e)}", flush=True)
                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 - {len(slide_analysis)} agents finished", flush=True)
    
    print(f"  🎉 All {len(slides_data)} slides analyzed successfully!", flush=True)
    return all_results
