#!/usr/bin/env python3
"""
Advanced PowerPoint Formatting Fix Script
Automatically fixes formatting issues in PowerPoint files with multiple options
"""

import os
import sys
import argparse
from pathlib import Path

def install_requirements():
    """Install required packages"""
    try:
        import pptx
        return True
    except ImportError:
        print("Installing required package: python-pptx")
        os.system("pip install python-pptx")
        try:
            import pptx
            return True
        except ImportError:
            print("Error: Could not install python-pptx. Please install it manually:")
            print("pip install python-pptx")
            return False

def fix_powerpoint_advanced(input_file, output_file=None, target_color='brown', target_font='Georgia'):
    """Advanced PowerPoint formatting fix with configurable options"""
    
    if not install_requirements():
        return False
    
    from pptx import Presentation
    from pptx.dml.color import RGBColor
    from pptx.util import Pt
    
    # Color definitions
    colors = {
        'brown': RGBColor(139, 69, 19),
        'dark_brown': RGBColor(101, 67, 33),
        'light_brown': RGBColor(160, 82, 45),
        'black': RGBColor(0, 0, 0),
        'dark_grey': RGBColor(64, 64, 64),
        'blue': RGBColor(0, 0, 139),
        'green': RGBColor(0, 100, 0)
    }
    
    target_rgb = colors.get(target_color.lower(), colors['brown'])
    
    def is_grey_color(color):
        """Check if a color is grey (RGB values are similar)"""
        if not color:
            return False
        
        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 target color
                        run.font.color.rgb = target_rgb
                        
                        # Change to target font
                        run.font.name = target_font
                        
                        # Preserve original size or set default
                        if not run.font.size:
                            run.font.size = Pt(12)
                        
                        fixed_count += 1
                        print(f"Fixed: '{run.text}' - Changed from grey {font_name} to {target_color} {target_font}")
        
        return fixed_count
    
    if not os.path.exists(input_file):
        print(f"Error: File '{input_file}' not found!")
        return False
    
    try:
        # Load the presentation
        print(f"Loading presentation: {input_file}")
        prs = Presentation(input_file)
        
        total_fixed = 0
        total_slides = len(prs.slides)
        
        print(f"Processing {total_slides} slides...")
        print(f"Target color: {target_color}")
        print(f"Target font: {target_font}")
        
        # 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_file is None:
            # Create backup and modified version
            base_name = os.path.splitext(input_file)[0]
            output_file = f"{base_name}_fixed_{target_color}_{target_font}.pptx"
        
        print(f"Saving fixed presentation to: {output_file}")
        prs.save(output_file)
        
        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_file}")
        
        return True
        
    except Exception as e:
        print(f"Error processing presentation: {str(e)}")
        return False

def main():
    """Main function with command line arguments"""
    parser = argparse.ArgumentParser(description='Fix PowerPoint formatting issues')
    parser.add_argument('input_file', help='Input PowerPoint file path')
    parser.add_argument('-o', '--output', help='Output file path (optional)')
    parser.add_argument('-c', '--color', default='brown', 
                       choices=['brown', 'dark_brown', 'light_brown', 'black', 'dark_grey', 'blue', 'green'],
                       help='Target color for numbers (default: brown)')
    parser.add_argument('-f', '--font', default='Georgia',
                       help='Target font for numbers (default: Georgia)')
    
    args = parser.parse_args()
    
    success = fix_powerpoint_advanced(args.input_file, args.output, args.color, args.font)
    
    if success:
        print("\n✅ Formatting fix completed successfully!")
    else:
        print("\n❌ Formatting fix failed!")

if __name__ == "__main__":
    main() 