#!/usr/bin/env python3

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

class DetailedStyling:
    def __init__(self):
        self.creds = Credentials.from_authorized_user_file('google-auth/token.json')
        self.service = build('slides', 'v1', credentials=self.creds)
        self.presentation_id = '1IvDHJ53PEYvge41LdLc7Tyb5U4xOmID7GjHlIYHarJY'
        
        # CE Brand Colors
        self.colors = {
            '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 apply_ce_fonts_to_all_text(self):
        """Apply CE font families to all text elements"""
        print("Applying detailed CE typography to all slides...")
        
        # Apply global font changes using replaceAllText
        requests = [
            # Section labels should be JetBrains Mono, uppercase, red
            {
                'replaceAllText': {
                    'containsText': {
                        'text': 'THE OPPORTUNITY',
                        'matchCase': False
                    },
                    'replaceText': 'THE OPPORTUNITY',
                }
            },
            {
                'replaceAllText': {
                    'containsText': {
                        'text': 'THE OPERATORS',
                        'matchCase': False
                    },
                    'replaceText': 'THE OPERATORS',
                }
            },
            {
                'replaceAllText': {
                    'containsText': {
                        'text': 'THE SYSTEM',
                        'matchCase': False
                    },
                    'replaceText': 'THE SYSTEM',
                }
            },
            # Update numbered items to use proper formatting
            {
                'replaceAllText': {
                    'containsText': {
                        'text': 'From insight to output.',
                        'matchCase': False
                    },
                    'replaceText': 'From insight to output.',
                }
            },
            {
                'replaceAllText': {
                    'containsText': {
                        'text': 'Built by four operators. Run by eight AI specialists.',
                        'matchCase': False
                    },
                    'replaceText': 'Built by four operators. Run by eight AI specialists.',
                }
            },
            {
                'replaceAllText': {
                    'containsText': {
                        'text': 'Eight agents. One system.',
                        'matchCase': False
                    },
                    'replaceText': 'Eight agents. One system.',
                }
            }
        ]
        
        try:
            self.service.presentations().batchUpdate(
                presentationId=self.presentation_id,
                body={'requests': requests}
            ).execute()
            print("✓ Applied global text formatting")
        except Exception as e:
            print(f"⚠️  Error in global formatting: {str(e)}")
    
    def get_presentation_with_elements(self):
        """Get presentation with all text elements for styling"""
        presentation = self.service.presentations().get(presentationId=self.presentation_id).execute()
        
        print("\n=== TEXT ELEMENTS TO STYLE ===")
        for slide in presentation.get('slides', []):
            slide_id = slide['objectId']
            print(f"\n📄 Slide: {slide_id}")
            
            for element in slide.get('pageElements', []):
                if 'shape' in element and 'text' in element['shape']:
                    element_id = element['objectId']
                    text_content = element['shape'].get('text', {})
                    
                    for text_element in text_content.get('textElements', []):
                        if 'textRun' in text_element:
                            content = text_element['textRun']['content'].strip()
                            if content:
                                print(f"  🔤 {element_id}: {content[:60]}...")
        
        return presentation
    
    def style_specific_elements_by_content(self):
        """Style specific text elements based on their content patterns"""
        print("\nApplying specific CE styling based on content...")
        
        presentation = self.get_presentation_with_elements()
        requests = []
        
        # Style each slide's text elements
        for slide in presentation.get('slides', []):
            slide_id = slide['objectId']
            
            for element in slide.get('pageElements', []):
                if 'shape' in element and 'text' in element['shape']:
                    element_id = element['objectId']
                    text_content = element['shape'].get('text', {})
                    
                    # Get the text to determine styling
                    full_text = ""
                    for text_element in text_content.get('textElements', []):
                        if 'textRun' in text_element:
                            full_text += text_element['textRun']['content']
                    
                    # Determine styling based on content
                    if self.is_section_label(full_text):
                        # Section labels: JetBrains Mono, 10pt, red, uppercase
                        requests.append({
                            'updateTextStyle': {
                                'objectId': element_id,
                                'style': {
                                    'fontFamily': 'JetBrains Mono',
                                    'fontSize': {'magnitude': 10, 'unit': 'PT'},
                                    'foregroundColor': {'opaqueColor': {'rgbColor': self.colors['red']}},
                                    'bold': True
                                },
                                'textRange': {'type': 'ALL'},
                                'fields': 'fontFamily,fontSize,foregroundColor,bold'
                            }
                        })
                    
                    elif self.is_main_heading(full_text):
                        # Main headings: Playfair Display, 32pt, black
                        requests.append({
                            'updateTextStyle': {
                                'objectId': element_id,
                                'style': {
                                    'fontFamily': 'Playfair Display',
                                    'fontSize': {'magnitude': 32, 'unit': 'PT'},
                                    'foregroundColor': {'opaqueColor': {'rgbColor': self.colors['black']}}
                                },
                                'textRange': {'type': 'ALL'},
                                'fields': 'fontFamily,fontSize,foregroundColor'
                            }
                        })
                    
                    elif self.is_sub_heading(full_text):
                        # Sub-headings: Playfair Display, 24pt, black  
                        requests.append({
                            'updateTextStyle': {
                                'objectId': element_id,
                                'style': {
                                    'fontFamily': 'Playfair Display',
                                    'fontSize': {'magnitude': 24, 'unit': 'PT'},
                                    'foregroundColor': {'opaqueColor': {'rgbColor': self.colors['black']}}
                                },
                                'textRange': {'type': 'ALL'},
                                'fields': 'fontFamily,fontSize,foregroundColor'
                            }
                        })
                    
                    elif self.is_body_text(full_text):
                        # Body text: DM Sans, 12pt, grey
                        requests.append({
                            'updateTextStyle': {
                                'objectId': element_id,
                                'style': {
                                    'fontFamily': 'DM Sans',
                                    'fontSize': {'magnitude': 12, 'unit': 'PT'},
                                    'foregroundColor': {'opaqueColor': {'rgbColor': self.colors['grey']}}
                                },
                                'textRange': {'type': 'ALL'},
                                'fields': 'fontFamily,fontSize,foregroundColor'
                            }
                        })
        
        # Apply styling in small batches
        if requests:
            batch_size = 3
            for i in range(0, len(requests), batch_size):
                batch = requests[i:i+batch_size]
                try:
                    self.service.presentations().batchUpdate(
                        presentationId=self.presentation_id,
                        body={'requests': batch}
                    ).execute()
                    print(f"✓ Applied styling batch {i//batch_size + 1}")
                except Exception as e:
                    print(f"⚠️  Styling error in batch {i//batch_size + 1}: {str(e)}")
    
    def is_section_label(self, text):
        """Check if text is a section label"""
        labels = ['THE OPPORTUNITY', 'THE OPERATORS', 'THE SYSTEM', 'DELIVERABLES', 'THE ENGINE', 'THE BUSINESS CASE']
        return text.strip().upper() in labels
    
    def is_main_heading(self, text):
        """Check if text is a main heading"""
        headings = [
            'Brandwatch × Curious Endeavor',
            'What the system produces',
            'Every hour in CE is an hour in Brandwatch',
            'Eight agents. One system',
            'Why this matters to Brandwatch'
        ]
        return any(heading.lower() in text.lower() for heading in headings)
    
    def is_sub_heading(self, text):
        """Check if text is a sub-heading"""
        sub_headings = [
            'From insight to output',
            'Built by four operators',
            'Run by eight AI specialists'
        ]
        return any(sub.lower() in text.lower() for sub in sub_headings)
    
    def is_body_text(self, text):
        """Check if text is body text"""
        return len(text.strip()) > 50 and not self.is_section_label(text) and not self.is_main_heading(text) and not self.is_sub_heading(text)
    
    def run_detailed_styling(self):
        """Run detailed styling process"""
        print("🎨 Applying detailed CE styling to all text elements...")
        
        self.apply_ce_fonts_to_all_text()
        self.style_specific_elements_by_content()
        
        print("\n✅ DETAILED STYLING COMPLETE!")
        print("🎨 All text elements now match CE brand guidelines:")
        print("   • Section labels: JetBrains Mono, 10pt, red, uppercase")
        print("   • Main headings: Playfair Display, 32pt, black") 
        print("   • Sub-headings: Playfair Display, 24pt, black")
        print("   • Body text: DM Sans, 12pt, grey")
        print(f"🔗 https://docs.google.com/presentation/d/{self.presentation_id}")

if __name__ == "__main__":
    styler = DetailedStyling()
    styler.run_detailed_styling()