#!/usr/bin/env python3

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
import json

class BrandwatchDeckRedesigner:
    def __init__(self):
        # Load credentials
        self.creds = Credentials.from_authorized_user_file('google-auth/token.json')
        self.service = build('slides', 'v1', credentials=self.creds)
        self.presentation_id = '1IvDHJ53PEYvge41LdLc7Tyb5U4xOmID7GjHlIYHarJY'
        
        # EMU conversion (1 inch = 914400 EMU)
        self.EMU_PER_INCH = 914400
        
        # CE Brand Colors (RGB 0-1 format for Google Slides API)
        self.colors = {
            'white': {'red': 1.0, 'green': 1.0, 'blue': 1.0},
            'red': {'red': 0.8, 'green': 0.0, 'blue': 0.0},  # #cc0000
            'black': {'red': 0.102, 'green': 0.102, 'blue': 0.102},  # #1a1a1a
            'grey': {'red': 0.4, 'green': 0.4, 'blue': 0.4},  # #666666
            'light': {'red': 0.6, 'green': 0.6, 'blue': 0.6}  # #999999
        }
        
    def get_presentation(self):
        """Get current presentation state"""
        return self.service.presentations().get(presentationId=self.presentation_id).execute()
    
    def create_text_style_request(self, object_id, start_index, end_index, font_family, font_size, color, bold=False):
        """Helper to create text styling requests"""
        return {
            'updateTextStyle': {
                'objectId': object_id,
                'style': {
                    'fontFamily': font_family,
                    'fontSize': {'magnitude': font_size, 'unit': 'PT'},
                    'foregroundColor': {'opaqueColor': {'rgbColor': color}},
                    'bold': bold
                },
                'textRange': {
                    'type': 'FIXED_RANGE',
                    'startIndex': start_index,
                    'endIndex': end_index
                },
                'fields': 'fontFamily,fontSize,foregroundColor,bold'
            }
        }
    
    def step_1_cleanup_and_create_slides(self):
        """Remove duplicate slide and create new Deliverables and Engine slides"""
        print("Step 1: Cleaning up and creating new slides...")
        
        # Get current presentation
        presentation = self.get_presentation()
        slides = presentation.get('slides', [])
        
        requests = []
        
        # Remove the duplicate opportunity slide (g3cf700453b9_1_28)
        duplicate_slide_id = None
        for slide in slides:
            if slide['objectId'] == 'g3cf700453b9_1_28':
                duplicate_slide_id = slide['objectId']
                break
        
        if duplicate_slide_id:
            requests.append({
                'deleteObject': {
                    'objectId': duplicate_slide_id
                }
            })
        
        # Create Deliverables slide (should be inserted after Operators - position 3)
        requests.append({
            'createSlide': {
                'objectId': 'slide_deliverables',
                'insertionIndex': 3,
                'slideLayoutReference': {
                    'predefinedLayout': 'BLANK'
                }
            }
        })
        
        # Create Engine slide (should be inserted after Deliverables - position 4)  
        requests.append({
            'createSlide': {
                'objectId': 'slide_engine',
                'insertionIndex': 4,
                'slideLayoutReference': {
                    'predefinedLayout': 'BLANK'
                }
            }
        })
        
        # Execute batch update
        if requests:
            self.service.presentations().batchUpdate(
                presentationId=self.presentation_id,
                body={'requests': requests}
            ).execute()
            print(f"✓ Removed duplicate slide and created 2 new slides")
    
    def step_2_add_content_to_new_slides(self):
        """Add content to Deliverables and Engine slides"""
        print("Step 2: Adding content to new slides...")
        
        requests = []
        
        # === DELIVERABLES SLIDE CONTENT ===
        # Section label
        requests.append({
            'createShape': {
                'objectId': 'deliverables_label',
                'shapeType': 'TEXT_BOX',
                'elementProperties': {
                    'pageObjectId': 'slide_deliverables',
                    'size': {
                        'height': {'magnitude': 0.5 * self.EMU_PER_INCH, 'unit': 'EMU'},
                        'width': {'magnitude': 8 * self.EMU_PER_INCH, 'unit': 'EMU'}
                    },
                    'transform': {
                        'scaleX': 1.0,
                        'scaleY': 1.0,
                        'translateX': 1 * self.EMU_PER_INCH,
                        'translateY': 0.8 * self.EMU_PER_INCH,
                        'unit': 'EMU'
                    }
                }
            }
        })
        
        requests.append({
            'insertText': {
                'objectId': 'deliverables_label',
                'insertionIndex': 0,
                'text': 'DELIVERABLES'
            }
        })
        
        # Main heading
        requests.append({
            'createShape': {
                'objectId': 'deliverables_heading',
                'shapeType': 'TEXT_BOX',
                'elementProperties': {
                    'pageObjectId': 'slide_deliverables',
                    'size': {
                        'height': {'magnitude': 1 * self.EMU_PER_INCH, 'unit': 'EMU'},
                        'width': {'magnitude': 8 * self.EMU_PER_INCH, 'unit': 'EMU'}
                    },
                    'transform': {
                        'scaleX': 1.0,
                        'scaleY': 1.0,
                        'translateX': 1 * self.EMU_PER_INCH,
                        'translateY': 1.3 * self.EMU_PER_INCH,
                        'unit': 'EMU'
                    }
                }
            }
        })
        
        requests.append({
            'insertText': {
                'objectId': 'deliverables_heading',
                'insertionIndex': 0,
                'text': 'What the system produces'
            }
        })
        
        # Deliverables list
        deliverables_text = """01 Strategy Brief
Data-driven positioning strategy with specific campaign directions

02 Campaign Architecture  
Channel-by-channel blueprint teams can execute from

03 Production-Ready Assets
Finished creative loaded directly into Publish and Advertise

04 Multi-Market Localization
Regional data transformed into market-specific campaigns

05 Execution Playbook
What to publish when, what to track in Brandwatch Measure"""
        
        requests.append({
            'createShape': {
                'objectId': 'deliverables_list',
                'shapeType': 'TEXT_BOX',
                'elementProperties': {
                    'pageObjectId': 'slide_deliverables',
                    'size': {
                        'height': {'magnitude': 3 * self.EMU_PER_INCH, 'unit': 'EMU'},
                        'width': {'magnitude': 8 * self.EMU_PER_INCH, 'unit': 'EMU'}
                    },
                    'transform': {
                        'scaleX': 1.0,
                        'scaleY': 1.0,
                        'translateX': 1 * self.EMU_PER_INCH,
                        'translateY': 2.3 * self.EMU_PER_INCH,
                        'unit': 'EMU'
                    }
                }
            }
        })
        
        requests.append({
            'insertText': {
                'objectId': 'deliverables_list',
                'insertionIndex': 0,
                'text': deliverables_text
            }
        })
        
        # === ENGINE SLIDE CONTENT ===
        # Section label  
        requests.append({
            'createShape': {
                'objectId': 'engine_label',
                'shapeType': 'TEXT_BOX',
                'elementProperties': {
                    'pageObjectId': 'slide_engine',
                    'size': {
                        'height': {'magnitude': 0.5 * self.EMU_PER_INCH, 'unit': 'EMU'},
                        'width': {'magnitude': 8 * self.EMU_PER_INCH, 'unit': 'EMU'}
                    },
                    'transform': {
                        'scaleX': 1.0,
                        'scaleY': 1.0,
                        'translateX': 1 * self.EMU_PER_INCH,
                        'translateY': 0.8 * self.EMU_PER_INCH,
                        'unit': 'EMU'
                    }
                }
            }
        })
        
        requests.append({
            'insertText': {
                'objectId': 'engine_label',
                'insertionIndex': 0,
                'text': 'THE ENGINE'
            }
        })
        
        # Main heading
        requests.append({
            'createShape': {
                'objectId': 'engine_heading',
                'shapeType': 'TEXT_BOX',
                'elementProperties': {
                    'pageObjectId': 'slide_engine',
                    'size': {
                        'height': {'magnitude': 1 * self.EMU_PER_INCH, 'unit': 'EMU'},
                        'width': {'magnitude': 8 * self.EMU_PER_INCH, 'unit': 'EMU'}
                    },
                    'transform': {
                        'scaleX': 1.0,
                        'scaleY': 1.0,
                        'translateX': 1 * self.EMU_PER_INCH,
                        'translateY': 1.3 * self.EMU_PER_INCH,
                        'unit': 'EMU'
                    }
                }
            }
        })
        
        requests.append({
            'insertText': {
                'objectId': 'engine_heading',
                'insertionIndex': 0,
                'text': 'Every hour in CE is an hour in Brandwatch.'
            }
        })
        
        # Engine capabilities
        engine_text = """01 Cultural Intelligence
Real-time trend detection from social and cultural signals

02 Production System  
Campaign creation at scale, from strategy to finished assets

03 Quality Architecture
Multi-layer review ensuring brand consistency and effectiveness"""
        
        requests.append({
            'createShape': {
                'objectId': 'engine_list',
                'shapeType': 'TEXT_BOX',
                'elementProperties': {
                    'pageObjectId': 'slide_engine',
                    'size': {
                        'height': {'magnitude': 2.5 * self.EMU_PER_INCH, 'unit': 'EMU'},
                        'width': {'magnitude': 8 * self.EMU_PER_INCH, 'unit': 'EMU'}
                    },
                    'transform': {
                        'scaleX': 1.0,
                        'scaleY': 1.0,
                        'translateX': 1 * self.EMU_PER_INCH,
                        'translateY': 2.3 * self.EMU_PER_INCH,
                        'unit': 'EMU'
                    }
                }
            }
        })
        
        requests.append({
            'insertText': {
                'objectId': 'engine_list',
                'insertionIndex': 0,
                'text': engine_text
            }
        })
        
        # Execute batch update
        if requests:
            self.service.presentations().batchUpdate(
                presentationId=self.presentation_id,
                body={'requests': requests}
            ).execute()
            print(f"✓ Added content to new slides")
    
    def step_3_apply_ce_styling_to_all_slides(self):
        """Apply CE brand styling to all slides"""
        print("Step 3: Applying CE styling to all slides...")
        
        # Get fresh presentation state
        presentation = self.get_presentation()
        slides = presentation.get('slides', [])
        
        requests = []
        
        # Apply white background to all slides
        for slide in slides:
            requests.append({
                'updateSlideProperties': {
                    'objectId': slide['objectId'],
                    'slideProperties': {
                        'pageBackgroundFill': {
                            'solidFill': {
                                'color': {
                                    'rgbColor': self.colors['white']
                                }
                            }
                        }
                    },
                    'fields': 'pageBackgroundFill'
                }
            })
        
        # Style new slides content
        # Deliverables slide
        requests.extend([
            self.create_text_style_request('deliverables_label', 0, 13, 'JetBrains Mono', 10, self.colors['red']),
            self.create_text_style_request('deliverables_heading', 0, 27, 'Playfair Display', 32, self.colors['black']),
            # Style numbers in red JetBrains Mono
            self.create_text_style_request('deliverables_list', 0, 2, 'JetBrains Mono', 14, self.colors['red'], True),  # 01
            self.create_text_style_request('deliverables_list', 2, 16, 'DM Sans', 14, self.colors['black'], True),  # Strategy Brief
            self.create_text_style_request('deliverables_list', 83, 85, 'JetBrains Mono', 14, self.colors['red'], True),  # 02  
            self.create_text_style_request('deliverables_list', 85, 105, 'DM Sans', 14, self.colors['black'], True),  # Campaign Architecture
        ])
        
        # Engine slide
        requests.extend([
            self.create_text_style_request('engine_label', 0, 10, 'JetBrains Mono', 10, self.colors['red']),
            self.create_text_style_request('engine_heading', 0, 44, 'Playfair Display', 24, self.colors['black']),
            # Style numbers in red JetBrains Mono  
            self.create_text_style_request('engine_list', 0, 2, 'JetBrains Mono', 14, self.colors['red'], True),  # 01
            self.create_text_style_request('engine_list', 2, 23, 'DM Sans', 14, self.colors['black'], True),  # Cultural Intelligence
        ])
        
        # Execute styling
        if requests:
            # Split into smaller batches to avoid API limits
            batch_size = 20
            for i in range(0, len(requests), batch_size):
                batch = requests[i:i+batch_size]
                self.service.presentations().batchUpdate(
                    presentationId=self.presentation_id,
                    body={'requests': batch}
                ).execute()
        
        print("✓ Applied CE styling to all slides")
    
    def step_4_fix_existing_slide_titles(self):
        """Fix titles and content on existing slides"""
        print("Step 4: Fixing existing slide titles and styling...")
        
        # Get fresh presentation state
        presentation = self.get_presentation()
        
        requests = []
        
        # Find and update "The Value for Brandwatch" to "The Business Case"
        for slide in presentation.get('slides', []):
            if slide['objectId'] == 'slide_7':  # Value slide
                for element in slide.get('pageElements', []):
                    if 'shape' in element and 'text' in element['shape']:
                        for text_element in element['shape']['text']['textElements']:
                            if 'textRun' in text_element:
                                content = text_element['textRun']['content']
                                if 'The Value for Brandwatch' in content:
                                    # Replace the text
                                    requests.append({
                                        'replaceAllText': {
                                            'containsText': {
                                                'text': 'The Value for Brandwatch',
                                                'matchCase': False
                                            },
                                            'replaceText': 'The Business Case'
                                        }
                                    })
                                    
                                    requests.append({
                                        'insertText': {
                                            'objectId': element['objectId'],
                                            'insertionIndex': len(content),
                                            'text': '\nWhy this matters to Brandwatch'
                                        }
                                    })
        
        # Execute updates
        if requests:
            self.service.presentations().batchUpdate(
                presentationId=self.presentation_id,
                body={'requests': requests}
            ).execute()
        
        print("✓ Fixed slide titles and content")
    
    def run_complete_redesign(self):
        """Run the complete redesign process"""
        print("🎨 Starting Brandwatch deck redesign...")
        print("📋 Target: Match CE landing page structure and brand guidelines")
        print()
        
        try:
            self.step_1_cleanup_and_create_slides()
            self.step_2_add_content_to_new_slides()
            self.step_3_apply_ce_styling_to_all_slides()
            self.step_4_fix_existing_slide_titles()
            
            print()
            print("✅ REDESIGN COMPLETE!")
            print(f"🔗 Deck available at: https://docs.google.com/presentation/d/{self.presentation_id}")
            print()
            print("📊 Final slide order:")
            print("1. Hero/Cover - Brandwatch × Curious Endeavor")
            print("2. The Opportunity - From insight to output")  
            print("3. The Team - Built by operators, run by AI specialists")
            print("4. Deliverables - What the system produces")
            print("5. The Engine - Every hour in CE is an hour in Brandwatch")
            print("6. The System - Eight agents, one system")
            print("7. The Business Case - Why this matters to Brandwatch")
            print("8. Contact - Let's Talk")
            print()
            print("🎨 CE Brand Guidelines Applied:")
            print("✓ White backgrounds on all slides")
            print("✓ Red accent color (#cc0000) for labels and numbers")
            print("✓ Playfair Display for headings")
            print("✓ JetBrains Mono for section labels")
            print("✓ DM Sans for body text")
            print("✓ Proper color hierarchy: black → grey → light grey")
            
        except Exception as e:
            print(f"❌ Error during redesign: {str(e)}")
            raise

if __name__ == "__main__":
    redesigner = BrandwatchDeckRedesigner()
    redesigner.run_complete_redesign()