import os
import json
from pathlib import Path
from typing import Optional, Dict, Any, List
from dataclasses import dataclass
from datetime import datetime

# For PowerPoint generation
try:
    from pptx import Presentation
    from pptx.util import Inches, Pt
    from pptx.enum.text import MSO_ANCHOR, MSO_AUTO_SIZE
    from pptx.dml.color import RGBColor
    from pptx.enum.text import PP_ALIGN
    PPTX_AVAILABLE = True
except ImportError:
    PPTX_AVAILABLE = False
    print("⚠️ python-pptx not installed. Run: pip install python-pptx")

# Import from content analyzer
from content_analyzer import AnalyzedContent, SlideContent, TranscriptAnalysisManager


@dataclass
class SlideTheme:
    """Theme configuration for slides"""
    name: str
    background_color: str
    title_color: str
    text_color: str
    accent_color: str
    title_font_size: int = 32
    content_font_size: int = 18
    bullet_font_size: int = 16


class SlideGenerator:
    """Generates presentation slides from analyzed content"""
    
    def __init__(self, output_dir: str = "presentations"):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True)
        
        # Define themes
        self.themes = {
            'professional': SlideTheme(
                name="Professional",
                background_color="#FFFFFF",
                title_color="#1F4E79",
                text_color="#2F2F2F",
                accent_color="#0066CC"
            ),
            'modern': SlideTheme(
                name="Modern",
                background_color="#F8F9FA",
                title_color="#212529",
                text_color="#495057",
                accent_color="#007BFF"
            ),
            'dark': SlideTheme(
                name="Dark",
                background_color="#2F3349",
                title_color="#FFFFFF",
                text_color="#E9ECEF",
                accent_color="#FFC107"
            ),
            'corporate': SlideTheme(
                name="Corporate",
                background_color="#FFFFFF",
                title_color="#003366",
                text_color="#333333",
                accent_color="#FF6B35"
            )
        }
    
    def hex_to_rgb(self, hex_color: str) -> tuple:
        """Convert hex color to RGB tuple"""
        hex_color = hex_color.lstrip('#')
        return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
    
    def create_powerpoint(self, analyzed_content: AnalyzedContent, theme_name: str = 'professional') -> Optional[str]:
        """Create PowerPoint presentation from analyzed content"""
        
        if not PPTX_AVAILABLE:
            print("❌ Cannot create PowerPoint: python-pptx not installed")
            return None
        
        if not analyzed_content.success:
            print("❌ Cannot create presentation: analysis failed")
            return None
        
        try:
            # Get theme
            theme = self.themes.get(theme_name, self.themes['professional'])
            
            # Create presentation
            prs = Presentation()
            
            # Set slide size (16:9 aspect ratio)
            prs.slide_width = Inches(13.33)
            prs.slide_height = Inches(7.5)
            
            print(f"🎨 Creating PowerPoint with {theme.name} theme...")
            
            # Title slide
            self.create_title_slide(prs, analyzed_content, theme)
            
            # Content slides
            for slide_content in analyzed_content.slides:
                self.create_content_slide(prs, slide_content, theme)
            
            # Thank you slide
            self.create_thank_you_slide(prs, analyzed_content, theme)
            
            # Save presentation
            filename = f"{analyzed_content.video_id}_{theme_name}_presentation.pptx"
            filepath = self.output_dir / filename
            
            prs.save(str(filepath))
            
            print(f"✅ PowerPoint created: {filepath}")
            return str(filepath)
            
        except Exception as e:
            print(f"❌ Failed to create PowerPoint: {str(e)}")
            return None
    
    def create_title_slide(self, prs: Presentation, analyzed_content: AnalyzedContent, theme: SlideTheme):
        """Create title slide"""
        slide_layout = prs.slide_layouts[0]  # Title slide layout
        slide = prs.slides.add_slide(slide_layout)
        
        # Set background color
        background = slide.background
        fill = background.fill
        fill.solid()
        fill.fore_color.rgb = RGBColor(*self.hex_to_rgb(theme.background_color))
        
        # Title
        title = slide.shapes.title
        title.text = analyzed_content.video_title
        title_frame = title.text_frame
        title_paragraph = title_frame.paragraphs[0]
        title_paragraph.font.size = Pt(theme.title_font_size + 8)
        title_paragraph.font.color.rgb = RGBColor(*self.hex_to_rgb(theme.title_color))
        title_paragraph.font.bold = True
        title_paragraph.alignment = PP_ALIGN.CENTER
        
        # Subtitle
        subtitle = slide.placeholders[1]
        subtitle_text = f"""
{analyzed_content.main_topic}

{analyzed_content.total_slides} Key Insights
Estimated Time: {analyzed_content.estimated_presentation_time:.1f} minutes

Generated from YouTube Video Analysis
        """.strip()
        
        subtitle.text = subtitle_text
        subtitle_frame = subtitle.text_frame
        for paragraph in subtitle_frame.paragraphs:
            paragraph.font.size = Pt(theme.content_font_size)
            paragraph.font.color.rgb = RGBColor(*self.hex_to_rgb(theme.text_color))
            paragraph.alignment = PP_ALIGN.CENTER
    
    def create_content_slide(self, prs: Presentation, slide_content: SlideContent, theme: SlideTheme):
        """Create content slide"""
        slide_layout = prs.slide_layouts[1]  # Title and content layout
        slide = prs.slides.add_slide(slide_layout)
        
        # Set background color
        background = slide.background
        fill = background.fill
        fill.solid()
        fill.fore_color.rgb = RGBColor(*self.hex_to_rgb(theme.background_color))
        
        # Title
        title = slide.shapes.title
        title.text = f"{slide_content.slide_number}. {slide_content.title}"
        title_frame = title.text_frame
        title_paragraph = title_frame.paragraphs[0]
        title_paragraph.font.size = Pt(theme.title_font_size)
        title_paragraph.font.color.rgb = RGBColor(*self.hex_to_rgb(theme.title_color))
        title_paragraph.font.bold = True
        
        # Content
        content = slide.placeholders[1]
        content_frame = content.text_frame
        content_frame.clear()
        
        # Add main points
        if slide_content.main_points:
            for i, point in enumerate(slide_content.main_points):
                p = content_frame.add_paragraph() if i > 0 else content_frame.paragraphs[0]
                p.text = f"• {point}"
                p.font.size = Pt(theme.content_font_size)
                p.font.color.rgb = RGBColor(*self.hex_to_rgb(theme.text_color))
                p.space_after = Pt(6)
        
        # Add supporting details if there's space
        if slide_content.supporting_details and len(slide_content.main_points) <= 3:
            # Add a line break
            p = content_frame.add_paragraph()
            p.text = ""
            p.space_after = Pt(3)
            
            for detail in slide_content.supporting_details[:2]:  # Max 2 details
                p = content_frame.add_paragraph()
                p.text = f"  ◦ {detail}"
                p.font.size = Pt(theme.bullet_font_size)
                p.font.color.rgb = RGBColor(*self.hex_to_rgb(theme.accent_color))
                p.space_after = Pt(3)
        
        # Add timestamp info
        if slide_content.timestamp_range:
            start_min = int(slide_content.timestamp_range[0] // 60)
            start_sec = int(slide_content.timestamp_range[0] % 60)
            
            # Add timestamp at bottom
            timestamp_box = slide.shapes.add_textbox(
                Inches(0.5), Inches(6.8), Inches(12), Inches(0.5)
            )
            timestamp_frame = timestamp_box.text_frame
            timestamp_p = timestamp_frame.paragraphs[0]
            timestamp_p.text = f"📹 Video timestamp: {start_min:02d}:{start_sec:02d}"
            timestamp_p.font.size = Pt(12)
            timestamp_p.font.color.rgb = RGBColor(*self.hex_to_rgb(theme.accent_color))
            timestamp_p.alignment = PP_ALIGN.RIGHT
    
    def create_thank_you_slide(self, prs: Presentation, analyzed_content: AnalyzedContent, theme: SlideTheme):
        """Create thank you/summary slide"""
        slide_layout = prs.slide_layouts[1]
        slide = prs.slides.add_slide(slide_layout)
        
        # Set background color
        background = slide.background
        fill = background.fill
        fill.solid()
        fill.fore_color.rgb = RGBColor(*self.hex_to_rgb(theme.background_color))
        
        # Title
        title = slide.shapes.title
        title.text = "Thank You!"
        title_frame = title.text_frame
        title_paragraph = title_frame.paragraphs[0]
        title_paragraph.font.size = Pt(theme.title_font_size + 8)
        title_paragraph.font.color.rgb = RGBColor(*self.hex_to_rgb(theme.title_color))
        title_paragraph.font.bold = True
        title_paragraph.alignment = PP_ALIGN.CENTER
        
        # Summary content
        content = slide.placeholders[1]
        summary_text = f"""
Key Takeaways:
• {', '.join(analyzed_content.key_themes[:3])}

📊 Presentation Summary:
• {analyzed_content.total_slides} slides covering {analyzed_content.main_topic.lower()}
• Generated from {analyzed_content.analysis_metadata.get('original_word_count', 0):,} words
• Original video duration: {analyzed_content.analysis_metadata.get('original_word_count', 0) // 150:.1f} minutes

🎬 Source: YouTube Video Analysis
📅 Generated: {datetime.now().strftime('%B %d, %Y')}
        """.strip()
        
        content.text = summary_text
        content_frame = content.text_frame
        for paragraph in content_frame.paragraphs:
            paragraph.font.size = Pt(theme.content_font_size)
            paragraph.font.color.rgb = RGBColor(*self.hex_to_rgb(theme.text_color))
            paragraph.alignment = PP_ALIGN.CENTER
    
    def create_html_preview(self, analyzed_content: AnalyzedContent, theme_name: str = 'professional') -> Optional[str]:
        """Create HTML preview of the presentation"""
        
        if not analyzed_content.success:
            return None
        
        try:
            theme = self.themes.get(theme_name, self.themes['professional'])
            
            html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{analyzed_content.video_title} - Presentation Preview</title>
    <style>
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f0f2f5;
            margin: 0;
            padding: 20px;
        }}
        
        .presentation {{
            max-width: 1000px;
            margin: 0 auto;
        }}
        
        .slide {{
            background-color: {theme.background_color};
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            min-height: 400px;
        }}
        
        .slide-title {{
            color: {theme.title_color};
            font-size: {theme.title_font_size}px;
            font-weight: bold;
            margin-bottom: 20px;
            border-bottom: 3px solid {theme.accent_color};
            padding-bottom: 10px;
        }}
        
        .slide-content {{
            color: {theme.text_color};
            font-size: {theme.content_font_size}px;
            line-height: 1.6;
        }}
        
        .main-points {{
            margin-bottom: 20px;
        }}
        
        .main-points li {{
            margin-bottom: 10px;
            color: {theme.text_color};
        }}
        
        .supporting-details {{
            margin-left: 20px;
            margin-bottom: 15px;
        }}
        
        .supporting-details li {{
            color: {theme.accent_color};
            font-size: {theme.bullet_font_size}px;
            margin-bottom: 5px;
        }}
        
        .timestamp {{
            color: {theme.accent_color};
            font-size: 12px;
            text-align: right;
            margin-top: 20px;
            font-style: italic;
        }}
        
        .title-slide {{
            text-align: center;
            background: linear-gradient(135deg, {theme.background_color} 0%, #f8f9fa 100%);
        }}
        
        .title-slide h1 {{
            font-size: {theme.title_font_size + 8}px;
            margin-bottom: 30px;
        }}
        
        .slide-counter {{
            position: absolute;
            top: 10px;
            right: 15px;
            background: {theme.accent_color};
            color: white;
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
        }}
        
        .summary-box {{
            background: #f8f9fa;
            border-left: 4px solid {theme.accent_color};
            padding: 15px;
            margin: 20px 0;
        }}
    </style>
</head>
<body>
    <div class="presentation">
        <!-- Title Slide -->
        <div class="slide title-slide">
            <div class="slide-counter">Title</div>
            <h1 class="slide-title">{analyzed_content.video_title}</h1>
            <div class="slide-content">
                <h2>{analyzed_content.main_topic}</h2>
                <p><strong>{analyzed_content.total_slides} Key Insights</strong></p>
                <p>Estimated Time: {analyzed_content.estimated_presentation_time:.1f} minutes</p>
                <div class="summary-box">
                    <strong>Key Themes:</strong> {', '.join(analyzed_content.key_themes[:5])}
                </div>
            </div>
        </div>
"""
            
            # Content slides
            for slide_content in analyzed_content.slides:
                timestamp_start = int(slide_content.timestamp_range[0])
                timestamp_display = f"{timestamp_start//60}:{timestamp_start%60:02d}"
                
                html_content += f"""
        <!-- Slide {slide_content.slide_number} -->
        <div class="slide">
            <div class="slide-counter">{slide_content.slide_number}/{analyzed_content.total_slides}</div>
            <h2 class="slide-title">{slide_content.slide_number}. {slide_content.title}</h2>
            <div class="slide-content">
"""
                
                if slide_content.main_points:
                    html_content += """
                <div class="main-points">
                    <ul>
"""
                    for point in slide_content.main_points:
                        html_content += f"                        <li>{point}</li>\n"
                    
                    html_content += """
                    </ul>
                </div>
"""
                
                if slide_content.supporting_details:
                    html_content += """
                <div class="supporting-details">
                    <ul>
"""
                    for detail in slide_content.supporting_details:
                        html_content += f"                        <li>{detail}</li>\n"
                    
                    html_content += """
                    </ul>
                </div>
"""
                
                html_content += f"""
                <div class="timestamp">📹 Video timestamp: {timestamp_display}</div>
            </div>
        </div>
"""
            
            # Thank you slide
            html_content += f"""
        <!-- Thank You Slide -->
        <div class="slide title-slide">
            <div class="slide-counter">End</div>
            <h1 class="slide-title">Thank You!</h1>
            <div class="slide-content">
                <div class="summary-box">
                    <strong>Key Takeaways:</strong><br>
                    {', '.join(analyzed_content.key_themes[:3])}
                </div>
                <p><strong>Presentation Summary:</strong></p>
                <p>{analyzed_content.total_slides} slides covering {analyzed_content.main_topic.lower()}</p>
                <p>Generated from {analyzed_content.analysis_metadata.get('original_word_count', 0):,} words</p>
                <p><small>🎬 Source: YouTube Video Analysis | 📅 Generated: {datetime.now().strftime('%B %d, %Y')}</small></p>
            </div>
        </div>
    </div>
</body>
</html>
"""
            
            # Save HTML file
            filename = f"{analyzed_content.video_id}_{theme_name}_preview.html"
            filepath = self.output_dir / filename
            
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(html_content)
            
            print(f"✅ HTML preview created: {filepath}")
            return str(filepath)
            
        except Exception as e:
            print(f"❌ Failed to create HTML preview: {str(e)}")
            return None
    
    def generate_presentation(self, video_id: str, theme_name: str = 'professional', 
                            create_html: bool = True, create_pptx: bool = True) -> Dict[str, Any]:
        """Generate presentation files from analyzed content"""
        
        # Load analysis
        manager = TranscriptAnalysisManager()
        analyzed_content = manager.load_analysis(video_id)
        
        if not analyzed_content:
            return {
                'success': False,
                'error': 'No analysis found for video ID',
                'files': []
            }
        
        if not analyzed_content.success:
            return {
                'success': False,
                'error': 'Analysis failed',
                'files': []
            }
        
        print(f"🎨 Generating presentation for: {analyzed_content.video_title}")
        print(f"📊 Theme: {theme_name}")
        print(f"📋 Slides: {analyzed_content.total_slides}")
        
        files_created = []
        
        # Create HTML preview
        if create_html:
            html_file = self.create_html_preview(analyzed_content, theme_name)
            if html_file:
                files_created.append({
                    'type': 'html',
                    'path': html_file,
                    'description': 'HTML Preview'
                })
        
        # Create PowerPoint
        if create_pptx and PPTX_AVAILABLE:
            pptx_file = self.create_powerpoint(analyzed_content, theme_name)
            if pptx_file:
                files_created.append({
                    'type': 'pptx',
                    'path': pptx_file,
                    'description': 'PowerPoint Presentation'
                })
        
        return {
            'success': len(files_created) > 0,
            'video_title': analyzed_content.video_title,
            'theme': theme_name,
            'slides_count': analyzed_content.total_slides,
            'files': files_created,
            'estimated_time': analyzed_content.estimated_presentation_time
        }


def main():
    """Main function to demonstrate slide generation"""
    
    # Initialize generator
    generator = SlideGenerator()
    
    # List available themes
    print("🎨 Available Themes:")
    for theme_name, theme in generator.themes.items():
        print(f"   • {theme_name}: {theme.name}")
    
    # Find available analyses
    manager = TranscriptAnalysisManager()
    transcripts = manager.list_available_transcripts()
    
    if not transcripts:
        print("\n❌ No transcripts found. Run content analysis first.")
        return
    
    # Use the first successful transcript
    successful_transcripts = [t for t in transcripts if t['success']]
    
    if not successful_transcripts:
        print("\n❌ No successful transcripts found.")
        return
    
    video_id = successful_transcripts[0]['video_id']
    video_title = successful_transcripts[0]['title']
    
    print(f"\n🎬 Generating presentation for: {video_title}")
    
    # Generate with different themes
    themes_to_try = ['professional', 'modern']
    
    for theme in themes_to_try:
        print(f"\n🎨 Creating {theme} theme presentation...")
        
        result = generator.generate_presentation(
            video_id=video_id,
            theme_name=theme,
            create_html=True,
            create_pptx=True
        )
        
        if result['success']:
            print(f"✅ Success! Created {len(result['files'])} files:")
            for file_info in result['files']:
                print(f"   📄 {file_info['description']}: {file_info['path']}")
        else:
            print(f"❌ Failed: {result.get('error', 'Unknown error')}")
    
    print(f"\n🎉 Presentation generation complete!")
    print(f"📁 Files saved in: {generator.output_dir}")


if __name__ == "__main__":
    main()