#!/usr/bin/env python3
"""
PowerPoint Formatting Fix Script
Automatically fixes formatting issues in PowerPoint files by changing:
- Grey numbers with standard font → Brown numbers with correct font
"""

import os
import sys
from pptx import Presentation
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN
from pptx.util import Inches, Pt

def is_grey_color(color):
    """Check if a color is grey (RGB values are similar)"""
    if not color:
        return False
    
    # Get RGB values
    try:
        rgb = color.rgb
        if rgb:
            r, g, b = rgb.red, rgb.green, rgb.blue
            # Check if all RGB values are similar (grey)
            return abs(r - g) < 30 and abs(g - b) < 30 and abs(r - b) < 30
    except:
        pass
    return False

def is_standard_font(font_name):
    """Check if font is a standard/common font"""
    standard_fonts = {
        'Arial', 'Calibri', 'Times New Roman', 'Helvetica', 'Verdana', 
        'Tahoma', 'Georgia', 'Trebuchet MS', 'Comic Sans MS', 'Impact',
        'Lucida Sans Unicode', 'Lucida Grande', 'Palatino', 'Garamond',
        'Bookman', 'Courier New', 'Courier', 'Monaco', 'Monospace',
        'MS Sans Serif', 'MS Serif', 'Symbol', 'Zapf Dingbats'
    }
    return font_name in standard_fonts

def fix_text_formatting(shape):
    """Fix formatting for text in a shape"""
    if not hasattr(shape, 'text_frame'):
        return 0
    
    fixed_count = 0
    
    for paragraph in shape.text_frame.paragraphs:
        for run in paragraph.runs:
            # Check if text contains numbers
            if any(char.isdigit() for char in run.text):
                # Check if font is standard and color is grey
                font_name = run.font.name if run.font.name else 'Arial'
                color = run.font.color
                
                if is_standard_font(font_name) and is_grey_color(color):
                    # Change to brown color
                    run.font.color.rgb = RGBColor(139, 69, 19)  # Brown color
                    
                    # Change to a more appropriate font (you can modify this)
                    run.font.name = 'Georgia'  # or another preferred font
                    run.font.size = Pt(12)  # Adjust size as needed
                    
                    fixed_count += 1
                    print(f"Fixed: '{run.text}' - Changed from grey standard font to brown Georgia")
    
    return fixed_count

def fix_powerpoint_formatting(pptx_path, output_path=None):
    """Main function to fix PowerPoint formatting"""
    if not os.path.exists(pptx_path):
        print(f"Error: File '{pptx_path}' not found!")
        return False
    
    try:
        # Load the presentation
        print(f"Loading presentation: {pptx_path}")
        prs = Presentation(pptx_path)
        
        total_fixed = 0
        total_slides = len(prs.slides)
        
        print(f"Processing {total_slides} slides...")
        
        # Process each slide
        for slide_num, slide in enumerate(prs.slides, 1):
            slide_fixed = 0
            
            # Process shapes in the slide
            for shape in slide.shapes:
                slide_fixed += fix_text_formatting(shape)
                
                # Check for grouped shapes
                if hasattr(shape, 'shapes'):
                    for subshape in shape.shapes:
                        slide_fixed += fix_text_formatting(subshape)
            
            if slide_fixed > 0:
                print(f"Slide {slide_num}: Fixed {slide_fixed} text elements")
                total_fixed += slide_fixed
        
        # Save the presentation
        if output_path is None:
            # Create backup and modified version
            base_name = os.path.splitext(pptx_path)[0]
            output_path = f"{base_name}_fixed.pptx"
        
        print(f"Saving fixed presentation to: {output_path}")
        prs.save(output_path)
        
        print(f"\nSummary:")
        print(f"Total slides processed: {total_slides}")
        print(f"Total text elements fixed: {total_fixed}")
        print(f"Fixed presentation saved as: {output_path}")
        
        return True
        
    except Exception as e:
        print(f"Error processing presentation: {str(e)}")
        return False

def main():
    """Main function"""
    if len(sys.argv) < 2:
        print("Usage: python fix_powerpoint_formatting.py <input_file.pptx> [output_file.pptx]")
        print("\nExample:")
        print("python fix_powerpoint_formatting.py '25 05 12 Kunstbuch Lebenswerk Nina Nolte, Buch, gestrafft copia 2.pptx'")
        return
    
    input_file = sys.argv[1]
    output_file = sys.argv[2] if len(sys.argv) > 2 else None
    
    # Install required package if not available
    try:
        from pptx import Presentation
    except ImportError:
        print("Installing required package: python-pptx")
        os.system("pip install python-pptx")
        try:
            from pptx import Presentation
        except ImportError:
            print("Error: Could not install python-pptx. Please install it manually:")
            print("pip install python-pptx")
            return
    
    success = fix_powerpoint_formatting(input_file, output_file)
    
    if success:
        print("\n✅ Formatting fix completed successfully!")
    else:
        print("\n❌ Formatting fix failed!")

if __name__ == "__main__":
    main() 