#!/usr/bin/env python3
"""Build the Brandwatch x CE Partner Pitch deck."""

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

PRESENTATION_ID = "1MRxdQp2Njr-Z5s45c_kV3oC4X-devR4_u5_LpLQ6MpA"

# Auth
with open('/root/.config/gws/credentials.json') as f:
    creds_data = json.load(f)

creds = Credentials(
    token=None,
    refresh_token=creds_data['refresh_token'],
    token_uri=creds_data['token_uri'],
    client_id=creds_data['client_id'],
    client_secret=creds_data['client_secret']
)

service = build('slides', 'v1', credentials=creds)

# Slide definitions
slides = [
    {
        "title": "Brandwatch × Curious Endeavor",
        "subtitle": "Your partner that turns social intelligence into action.\nFinished creative, deployed across markets, in days instead of months.",
        "layout": "title"
    },
    {
        "title": "The Opportunity",
        "body": "Brandwatch is the world's best social intelligence platform.\n\nYour clients invest $100K–$500K/year for enterprise-grade data.\n\nBut data without action is just expensive reporting.\n\nThe gap between insight and creative response costs brands months and hundreds of thousands in agency fees.\n\nWe close that gap."
    },
    {
        "title": "What Agencies Charge Today",
        "body": "Campaign strategy + brief: $5K–$15K\nCreative development: $10K–$50K\nMulti-market localization (per market): $3K–$8K\nFull campaign (strategy → assets): $25K–$150K\nTimeline: 6–12 weeks\n\nEnterprise brands spend $200K–$1M+/year on agency retainers — on top of their Brandwatch license."
    },
    {
        "title": "What We Do",
        "body": "Curious Endeavor is an AI-native creative production system.\n\n• Strategic Intelligence — insights your team hasn't seen\n• Parallel Production — 8 specialized AI agents working simultaneously\n• Cross-Market — true localization, not translation\n\nWe turn Brandwatch data into campaign-ready assets.\nReactive. Proactive. At the speed of social."
    },
    {
        "title": "The Operators",
        "body": "Assaf Dagan — Strategy & Creative\n15+ years leading campaigns for Wix, monday.com, eToro, Playtika, ironSource. Presidential campaigns to Fortune 500 repositions.\n\nLukas Richthammer — Former Brandwatch · MarTech SaaS & AI Sales\nSold Brandwatch to enterprise clients across DACH and beyond. Knows the product, the buyer, and what's missing."
    },
    {
        "title": "The System",
        "body": "Eight specialized AI agents:\n\n🔧 Kitt — The Strategist\n📋 Gerri — The Conductor\n✍️ Ogilvy — The Poet\n🎨 Tatiana — The Eye\n🐀 Anton — The Critic\n🔍 Julia — The Scout\n🎬 Jessica — The Director\n⚡ Thibault — The Builder\n\nCoordinated workflows. Human oversight at decision points.\nNot a demo. A production system that ships real work."
    },
    {
        "title": "How It Works with Brandwatch",
        "body": "1. Data Extraction\n   Pull structured audience intelligence from Brandwatch\n\n2. Strategic Analysis\n   Map pain points to positioning opportunities\n\n3. Campaign Architecture\n   Messaging, tone, and channel strategy per segment\n\n4. Asset Production\n   Parallel creation of production-ready deliverables\n\n5. Multi-Region Scaling\n   Localized strategy across all markets simultaneously"
    },
    {
        "title": "The Value for Brandwatch",
        "body": "• Stickiness — Brandwatch becomes indispensable because it doesn't just report, it responds\n\n• New Revenue — Creative layer as a premium tier. $50K–$150K/year per client on top of existing subscription\n\n• Category Creation — No social intelligence platform does this. Own \"social intelligence to social action\"\n\n• Agency Disintermediation — Brands pay Brandwatch for data AND an agency to act on it. Offer both, the agency becomes optional"
    },
    {
        "title": "Partnership Models",
        "body": "A. Technology Partnership\nCE's creative engine integrated as a Brandwatch premium feature.\nRevenue share. CE maintains the system, Brandwatch provides data + distribution.\n\nB. White-Label Integration\nCE runs under the Brandwatch brand. \"Brandwatch Creative Intelligence.\"\nDeeper integration. Maximum brand leverage.\n\nC. Acquisition\nFull integration into the product roadmap.\nMaximum commitment. Biggest upside for both."
    },
    {
        "title": "The Ask",
        "body": "A 60-minute conversation with Brandwatch product leadership.\n\nOne question:\nWhat would Brandwatch look like if every insight it surfaced came with a ready-to-deploy creative response?\n\nWe'll bring a live demonstration — real brand data, processed through CE's pipeline, with finished campaign assets.\n\nNot a deck. The actual output."
    },
    {
        "title": "Let's Talk",
        "subtitle": "Assaf Dagan — assaf@curiousendeavor.com\nLukas Richthammer\n\ncuriousendeavor.com/brandwatch-v2",
        "layout": "title"
    }
]

requests = []

# Get existing first slide ID
pres = service.presentations().get(presentationId=PRESENTATION_ID).execute()
first_slide_id = pres['slides'][0]['objectId']

# Create slides (skip first, use existing title slide)
for i, slide in enumerate(slides):
    if i == 0:
        # Update existing title slide
        # Find the title and subtitle placeholders
        for element in pres['slides'][0]['pageElements']:
            if 'shape' in element and 'placeholder' in element['shape']:
                ph = element['shape']['placeholder']
                if ph.get('type') == 'CENTERED_TITLE' or ph.get('type') == 'TITLE':
                    requests.append({
                        'insertText': {
                            'objectId': element['objectId'],
                            'text': slide['title']
                        }
                    })
                elif ph.get('type') == 'SUBTITLE':
                    requests.append({
                        'insertText': {
                            'objectId': element['objectId'],
                            'text': slide.get('subtitle', '')
                        }
                    })
    else:
        slide_id = f'slide_{i}'
        
        if slide.get('layout') == 'title':
            # Title slide layout
            requests.append({
                'createSlide': {
                    'objectId': slide_id,
                    'insertionIndex': i,
                    'slideLayoutReference': {'predefinedLayout': 'TITLE'}
                }
            })
        else:
            # Content slide
            requests.append({
                'createSlide': {
                    'objectId': slide_id,
                    'insertionIndex': i,
                    'slideLayoutReference': {'predefinedLayout': 'TITLE_AND_BODY'},
                    'placeholderIdMappings': [
                        {'layoutPlaceholder': {'type': 'TITLE'}, 'objectId': f'{slide_id}_title'},
                        {'layoutPlaceholder': {'type': 'BODY'}, 'objectId': f'{slide_id}_body'}
                    ]
                }
            })

# Execute slide creation first
if requests:
    service.presentations().batchUpdate(
        presentationId=PRESENTATION_ID,
        body={'requests': requests}
    ).execute()
    print(f"Created {len(slides)} slides")

# Now populate content
requests2 = []

for i, slide in enumerate(slides):
    if i == 0:
        continue  # Already handled
    
    slide_id = f'slide_{i}'
    
    if slide.get('layout') == 'title':
        # Need to get the actual placeholder IDs from the created slide
        pres2 = service.presentations().get(presentationId=PRESENTATION_ID).execute()
        for element in pres2['slides'][i]['pageElements']:
            if 'shape' in element and 'placeholder' in element['shape']:
                ph = element['shape']['placeholder']
                if ph.get('type') in ('CENTERED_TITLE', 'TITLE'):
                    requests2.append({
                        'insertText': {
                            'objectId': element['objectId'],
                            'text': slide['title']
                        }
                    })
                elif ph.get('type') == 'SUBTITLE':
                    requests2.append({
                        'insertText': {
                            'objectId': element['objectId'],
                            'text': slide.get('subtitle', '')
                        }
                    })
    else:
        requests2.append({
            'insertText': {
                'objectId': f'{slide_id}_title',
                'text': slide['title']
            }
        })
        if slide.get('body'):
            requests2.append({
                'insertText': {
                    'objectId': f'{slide_id}_body',
                    'text': slide['body']
                }
            })

if requests2:
    service.presentations().batchUpdate(
        presentationId=PRESENTATION_ID,
        body={'requests': requests2}
    ).execute()
    print("Content populated")

print(f"\nDeck ready: https://docs.google.com/presentation/d/{PRESENTATION_ID}/edit")
