#!/usr/bin/env python3
"""
Create Porsche pitch deck using Google Slides API
"""

import json
import os
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow

# Google Slides API scope
SCOPES = ['https://www.googleapis.com/auth/presentations']

def authenticate():
    """Authenticate with Google API"""
    creds = None
    
    # Check for existing token file
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
        
        # If there are no (valid) credentials available, try to refresh.
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                try:
                    creds.refresh(Request())
                    # Save the refreshed token
                    with open('token.json', 'w') as token_file:
                        token_file.write(creds.to_json())
                except Exception as e:
                    print(f"Failed to refresh token: {e}")
                    return None
            else:
                # No valid credentials
                return None
    
    return creds

def create_presentation():
    """Create a new Google Slides presentation"""
    
    # Try to authenticate
    creds = authenticate()
    if not creds:
        print("No credentials available. Run gws auth login first.")
        return None
    
    # Build the service
    service = build('slides', 'v1', credentials=creds)
    
    # Create presentation
    presentation_body = {
        'title': 'Porsche × Curious Endeavor - Creative Production for the AI Era'
    }
    
    try:
        presentation = service.presentations().create(body=presentation_body).execute()
        presentation_id = presentation.get('presentationId')
        print(f'Created presentation: https://docs.google.com/presentation/d/{presentation_id}')
        return presentation_id
    except Exception as e:
        print(f"Error creating presentation: {e}")
        return None

def add_slide_content(service, presentation_id, slide_id, title, body_text=None):
    """Add content to a slide"""
    requests = []
    
    # Find text elements on the slide
    presentation = service.presentations().get(presentationId=presentation_id).execute()
    
    for slide in presentation.get('slides', []):
        if slide.get('objectId') == slide_id:
            for element in slide.get('pageElements', []):
                if element.get('shape') and element.get('shape', {}).get('text'):
                    # This is a text element
                    placeholder = element.get('shape', {}).get('placeholder')
                    if placeholder:
                        if placeholder.get('type') == 'TITLE':
                            # Replace title text
                            requests.append({
                                'insertText': {
                                    'objectId': element.get('objectId'),
                                    'text': title
                                }
                            })
                        elif placeholder.get('type') == 'BODY' and body_text:
                            # Replace body text
                            requests.append({
                                'insertText': {
                                    'objectId': element.get('objectId'),
                                    'text': body_text
                                }
                            })
    
    if requests:
        service.presentations().batchUpdate(
            presentationId=presentation_id,
            body={'requests': requests}
        ).execute()

def build_full_deck():
    """Build the complete Porsche deck"""
    
    creds = authenticate()
    if not creds:
        print("Authentication failed. Please run: gws auth login")
        return None
    
    service = build('slides', 'v1', credentials=creds)
    
    # Create presentation
    presentation_id = create_presentation()
    if not presentation_id:
        return None
    
    # Define slide content
    slides_content = [
        {
            'title': 'Porsche × Curious Endeavor',
            'body': 'Creative Production for the AI Era'
        },
        {
            'title': 'The creative bottleneck is costing you time, not money.',
            'body': '• 8-12 week agency cycles for campaign production\n• 120+ markets, each needing localized (not translated) assets\n• Cultural moments expire faster than the production pipeline can serve them\n• Every off-brand asset is a brand risk at Porsche\'s level'
        },
        {
            'title': 'From agency calendar to always-on creative system.',
            'body': 'The world moved to real-time. Brand production didn\'t.\n\nTraditional: Brief → Agency → Rounds → Production → Localization → Launch (8-12 weeks)\n\nCE: Strategy → Production → Localization → Launch (14 days)\n\nNot faster because we cut corners. Faster because the system is built differently.'
        },
        {
            'title': 'An AI-native creative production system. Not an agency. A system.',
            'body': '• 8 specialized AI agents: strategy, copy, art direction, layout, production, quality review\n• Each agent trained on YOUR brand book, visual assets, tone of voice\n• Human quality gates at every stage — nothing ships without review\n• Full pipeline: data → insight → strategy → creative → production-ready assets'
        },
        {
            'title': 'Signal → Strategy → Creative → Production → Market',
            'body': '• Brand intelligence layer — your guidelines, your assets, your voice\n• Strategy engine — positioning, messaging, audience mapping\n• Creative production — copy, visuals, layout — all on-brand\n• Quality gates — Anton reviews everything before it ships\n• Localization layer — market-native, not machine-translated'
        },
        {
            'title': 'Three use cases that fit immediately:',
            'body': '1. Model launch campaigns — Taycan refresh, new 911 editions, concept reveals. From reveal moment to 20-market campaign in 14 days.\n\n2. Motorsport content — Le Mans, Formula E, GT racing. Real-time content production during race weekends. On-brand. On-platform. On-time.\n\n3. Dealer network assets — 800+ dealers need premium-feeling localized materials. Not templates. Actual creative that feels native to each market.'
        },
        {
            'title': 'Case Study — eToro: Speed × Quality',
            'body': 'The Problem: Global fintech needs localized campaigns across 15 markets. Traditional agency timeline: 10-12 weeks.\n\nWhat CE Delivered: Complete campaign system — positioning, copy, visuals — localized for each market. Brand-compliant assets ready for immediate deployment.\n\nTimeline: 16 days from brief to production-ready assets across all markets.\n\nImpact: 3x faster time-to-market. Consistent brand execution. 40% cost reduction vs. traditional agency model.'
        },
        {
            'title': 'Case Study — Brandwatch: Strategic Depth',
            'body': 'The Challenge: Position social intelligence platform for enterprise market expansion.\n\nCE\'s Approach: Deep strategic work — competitive analysis, messaging architecture, positioning that connects data insights to business outcomes.\n\nOutput: Complete strategic framework + campaign assets. Not just copy — complete creative system that sales and marketing teams could execute immediately.\n\nResult: Clear differentiation in crowded market. Strategic foundation for product-market expansion.'
        },
        {
            'title': 'Porsche is building a new audience. That requires a new creative velocity.',
            'body': '• Taycan buyers don\'t have 911 nostalgia. They need different stories.\n• Speaking to new audiences while keeping loyalists engaged = strategic challenge\n• CE\'s strategy layer handles the nuance. Generic AI tools produce generic output.\n• Speed matters because the EV conversation is moving faster than any product cycle.'
        },
        {
            'title': 'Brand-safe by architecture, not by hope.',
            'body': '❌ What We\'re NOT:\n• A chatbot generating copy\n• A template system that stamps out variants\n• A replacement for your creative leadership\n\n✅ What We ARE:\n• A production engine that executes your vision at scale and speed\n• A system where every asset traces back to strategy and data\n• Brand-safe by architecture, not by hope'
        },
        {
            'title': 'Three ways to start:',
            'body': 'Pilot — One campaign, one market. Prove the system on real work. (30 days)\n\nProduction Partner — Ongoing creative production across select markets. (90-day ramp)\n\nStrategic Integration — Full creative system embedded in Porsche\'s workflow. (6-month build)\n\nRecommendation: Start with a pilot. Let the output speak.'
        },
        {
            'title': 'Built for brands where every pixel matters.',
            'body': 'Assaf Dagan — Founder/Creative Director. 20+ years. monday.com, Wix, Playtika, ironSource.\n\nThe CE System — 8 specialized AI agents, each with defined expertise and quality standards.\n\nLukas Klement — Former Brandwatch. Bridge to enterprise partnerships.'
        },
        {
            'title': 'A 60-minute conversation to explore one question:',
            'body': '"What would Porsche\'s creative production look like if speed and quality weren\'t a tradeoff?"\n\nWe\'ll bring a demonstration: a real Porsche campaign scenario, processed through CE\'s system, with finished assets. Not a deck. The actual output.'
        },
        {
            'title': 'Contact',
            'body': 'Assaf Dagan\nassaf@curiousendeavor.com\ncuriousendeavor.com'
        }
    ]
    
    # Get the presentation to see existing slides
    presentation = service.presentations().get(presentationId=presentation_id).execute()
    existing_slides = presentation.get('slides', [])
    
    # Add additional slides (the first slide already exists)
    requests = []
    for i in range(1, len(slides_content)):
        requests.append({
            'createSlide': {
                'objectId': f'slide_{i+1}',
                'slideLayoutReference': {
                    'predefinedLayout': 'TITLE_AND_BODY'
                }
            }
        })
    
    if requests:
        service.presentations().batchUpdate(
            presentationId=presentation_id,
            body={'requests': requests}
        ).execute()
    
    # Now add content to all slides
    presentation = service.presentations().get(presentationId=presentation_id).execute()
    slides = presentation.get('slides', [])
    
    for i, slide_content in enumerate(slides_content):
        if i < len(slides):
            slide_id = slides[i].get('objectId')
            add_slide_content(service, presentation_id, slide_id, 
                            slide_content['title'], slide_content.get('body'))
    
    print(f'Deck complete: https://docs.google.com/presentation/d/{presentation_id}')
    return presentation_id

if __name__ == '__main__':
    build_full_deck()