#!/usr/bin/env python3
"""
Generate executive summary of PowerPoint presentation.
"""

import sys
import json
from pathlib import Path

def extract_presentation_data(pptx_path):
    """Extract data for summary generation."""
    try:
        from pptx import Presentation
    except ImportError:
        print("ERROR: python-pptx library not installed.")
        print("Install with: pip install python-pptx")
        return None
    
    try:
        prs = Presentation(pptx_path)
        
        presentation_data = {
            "filename": Path(pptx_path).name,
            "total_slides": len(prs.slides),
            "slides": [],
            "all_text": []
        }
        
        for i, slide in enumerate(prs.slides):
            slide_data = {
                "slide_number": i + 1,
                "title": "",
                "bullet_points": [],
                "key_points": []
            }
            
            # Extract title
            if slide.shapes.title:
                title_text = slide.shapes.title.text.strip()
                slide_data["title"] = title_text
                presentation_data["all_text"].append(f"Slide {i+1} Title: {title_text}")
            
            # Extract text content
            for shape in slide.shapes:
                if hasattr(shape, "text"):
                    text = shape.text.strip()
                    if text and (not slide.shapes.title or text != slide.shapes.title.text):
                        # Check if this looks like bullet points
                        lines = text.split('\n')
                        for line in lines:
                            line = line.strip()
                            if line:
                                presentation_data["all_text"].append(line)
                                
                                # Simple bullet point detection
                                if line.startswith(('•', '-', '*', '◦', '‣')) or any(word in line.lower() for word in ['key', 'important', 'critical', 'major', 'summary']):
                                    slide_data["key_points"].append(line)
                                elif len(line.split()) <= 15:  # Short lines might be bullet points
                                    slide_data["bullet_points"].append(line)
            
            presentation_data["slides"].append(slide_data)
        
        return presentation_data
        
    except Exception as e:
        print(f"ERROR processing {pptx_path}: {e}")
        return None

def generate_basic_summary(presentation_data):
    """Generate a basic summary without AI."""
    summary = []
    
    summary.append(f"📋 EXECUTIVE SUMMARY: {presentation_data['filename']}")
    summary.append(f"==============================================")
    summary.append(f"Total slides: {presentation_data['total_slides']}")
    summary.append("")
    
    # Identify likely sections
    summary.append(f"📑 LIKELY PRESENTATION STRUCTURE:")
    
    # Look for common section patterns
    sections = []
    for slide in presentation_data['slides']:
        title = slide['title'].lower() if slide['title'] else ""
        
        if any(word in title for word in ['agenda', 'contents', 'overview', 'outline']):
            sections.append(("📋 Agenda/Overview", slide['slide_number']))
        elif any(word in title for word in ['introduction', 'welcome', 'about']):
            sections.append(("👋 Introduction", slide['slide_number']))
        elif any(word in title for word in ['problem', 'challenge', 'issue', 'pain']):
            sections.append(("⚠️ Problem Statement", slide['slide_number']))
        elif any(word in title for word in ['solution', 'approach', 'method', 'strategy']):
            sections.append(("💡 Solution/Approach", slide['slide_number']))
        elif any(word in title for word in ['results', 'findings', 'data', 'analysis']):
            sections.append(("📈 Results/Analysis", slide['slide_number']))
        elif any(word in title for word in ['conclusion', 'summary', 'key takeaways', 'next steps']):
            sections.append(("🎯 Conclusion/Next Steps", slide['slide_number']))
        elif slide['title']:
            sections.append((f"📄 {slide['title']}", slide['slide_number']))
    
    if sections:
        for section_name, slide_num in sections:
            summary.append(f"  {section_name} (Slide {slide_num})")
    else:
        summary.append("  Could not detect clear section structure")
    summary.append("")
    
    # Extract key points
    summary.append(f"🔑 KEY POINTS IDENTIFIED:")
    key_points_found = False
    for slide in presentation_data['slides']:
        if slide['key_points']:
            key_points_found = True
            summary.append(f"  Slide {slide['slide_number']}: {slide['title'] or 'No title'}")
            for point in slide['key_points'][:3]:  # Limit to 3 per slide
                summary.append(f"    • {point}")
            if len(slide['key_points']) > 3:
                summary.append(f"    ... and {len(slide['key_points']) - 3} more points")
            summary.append("")
    
    if not key_points_found:
        # Fall back to first few bullet points
        for slide in presentation_data['slides'][:5]:  # First 5 slides
            if slide['bullet_points']:
                summary.append(f"  Slide {slide['slide_number']}: {slide['title'] or 'No title'}")
                for point in slide['bullet_points'][:2]:  # First 2 points
                    summary.append(f"    • {point[:80]}..." if len(point) > 80 else f"    • {point}")
                summary.append("")
    
    # Presentation metrics
    total_bullets = sum(len(slide['bullet_points']) for slide in presentation_data['slides'])
    total_key_points = sum(len(slide['key_points']) for slide in presentation_data['slides'])
    
    summary.append(f"📊 PRESENTATION METRICS:")
    summary.append(f"  • Total slides: {presentation_data['total_slides']}")
    summary.append(f"  • Total bullet points: {total_bullets}")
    summary.append(f"  • Key points identified: {total_key_points}")
    summary.append(f"  • Average bullets per slide: {total_bullets/presentation_data['total_slides']:.1f}" if presentation_data['total_slides'] > 0 else "  • Average bullets per slide: 0")
    summary.append("")
    
    summary.append(f"💡 RECOMMENDATIONS:")
    summary.append(f"  1. Consider adding more visual elements if presentation is text-heavy")
    summary.append(f"  2. Ensure each slide has a clear title")
    summary.append(f"  3. Use consistent formatting throughout")
    summary.append(f"  4. Consider adding a summary slide at the end")
    
    return "\n".join(summary)

def main():
    if len(sys.argv) < 2:
        print("Usage: python3 generate_pptx_summary.py <presentation.pptx> [output.txt]")
        sys.exit(1)
    
    pptx_path = sys.argv[1]
    output_path = sys.argv[2] if len(sys.argv) > 2 else None
    
    if not Path(pptx_path).exists():
        print(f"ERROR: File not found: {pptx_path}")
        sys.exit(1)
    
    presentation_data = extract_presentation_data(pptx_path)
    
    if presentation_data:
        summary = generate_basic_summary(presentation_data)
        print(summary)
        
        if output_path:
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(summary)
            print(f"\nSummary saved to: {output_path}")
            
            # Also save JSON data for potential AI enhancement
            json_path = output_path.replace('.txt', '.json') if output_path.endswith('.txt') else output_path + '.json'
            with open(json_path, 'w', encoding='utf-8') as f:
                json.dump(presentation_data, f, indent=2, ensure_ascii=False)
            print(f"Detailed data saved to: {json_path}")
    else:
        sys.exit(1)

if __name__ == "__main__":
    main()