#!/usr/bin/env python3
"""
Brandwatch × Curious Endeavor — Editorial Deck Redesign (v3)
Jessica (Art Direction) + Thibault (Engineering)

Design System:
- Display: EB Garamond (closest to Larken in Google Slides)
- Body: Inter
- Mono: JetBrains Mono
- Colors: #FFFFFF bg, #1a1a1a text, #666666 secondary, #999999 tertiary, #eeeeee rules, #cc0000 accent (sparingly)
- All white backgrounds. Red = accent only.
"""

import json, requests, time, uuid

# ─── Auth ───────────────────────────────────────────────────────────────────
with open('/root/.config/gws/credentials.json') as f:
    creds = json.load(f)
with open('/root/.config/gws/client_secret.json') as f:
    client = json.load(f)
ci = client.get('installed', client.get('web', {}))

resp = requests.post('https://oauth2.googleapis.com/token', data={
    'client_id': ci['client_id'],
    'client_secret': ci['client_secret'],
    'refresh_token': creds['refresh_token'],
    'grant_type': 'refresh_token'
})
access_token = resp.json()['access_token']
headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}

SLIDES_API = 'https://slides.googleapis.com/v1/presentations'
DRIVE_API = 'https://www.googleapis.com/drive/v3/files'

# ─── Design Constants ───────────────────────────────────────────────────────
PAGE_W = 9144000  # EMU
PAGE_H = 5143500  # EMU
PT = 12700        # 1pt in EMU
INCH = 914400     # 1 inch in EMU

MARGIN_LEFT = int(INCH * 0.8)     # ~0.8" left margin
MARGIN_RIGHT = int(INCH * 0.8)
MARGIN_TOP = int(INCH * 0.7)
MARGIN_BOTTOM = int(INCH * 0.5)

CONTENT_W = PAGE_W - MARGIN_LEFT - MARGIN_RIGHT  # usable width

# Colors as RGB fractions
CLR_TEXT = {"red": 0.102, "green": 0.102, "blue": 0.102}      # #1a1a1a
CLR_SECONDARY = {"red": 0.4, "green": 0.4, "blue": 0.4}       # #666666
CLR_TERTIARY = {"red": 0.6, "green": 0.6, "blue": 0.6}        # #999999
CLR_RULE = {"red": 0.933, "green": 0.933, "blue": 0.933}       # #eeeeee
CLR_RED = {"red": 0.8, "green": 0.0, "blue": 0.0}              # #cc0000
CLR_WHITE = {"red": 1.0, "green": 1.0, "blue": 1.0}
CLR_LIGHT_BG = {"red": 0.98, "green": 0.98, "blue": 0.98}      # #fafafa

FONT_DISPLAY = "EB Garamond"
FONT_BODY = "Inter"
FONT_MONO = "JetBrains Mono"

# ─── Helpers ────────────────────────────────────────────────────────────────
def uid():
    return f"v3_{uuid.uuid4().hex[:12]}"

def text_box(obj_id, x, y, w, h):
    return {
        "createShape": {
            "objectId": obj_id,
            "shapeType": "TEXT_BOX",
            "elementProperties": {
                "pageObjectId": None,  # filled per slide
                "size": {"width": {"magnitude": w, "unit": "EMU"}, "height": {"magnitude": h, "unit": "EMU"}},
                "transform": {
                    "scaleX": 1, "scaleY": 1,
                    "translateX": x, "translateY": y,
                    "unit": "EMU"
                }
            }
        }
    }

def insert_text(obj_id, text, idx=0):
    return {"insertText": {"objectId": obj_id, "text": text, "insertionIndex": idx}}

def style_text(obj_id, font, size_pt, color, start=0, end=None, bold=False, weight=400):
    style = {
        "foregroundColor": {"opaqueColor": {"rgbColor": color}},
        "fontFamily": font,
        "fontSize": {"magnitude": size_pt, "unit": "PT"},
        "bold": bold,
        "weightedFontFamily": {"fontFamily": font, "weight": weight}
    }
    fields = "foregroundColor,fontFamily,fontSize,bold,weightedFontFamily"
    if end is not None:
        text_range = {"type": "FIXED_RANGE", "startIndex": start, "endIndex": end}
    else:
        text_range = {"type": "ALL"}
    return {
        "updateTextStyle": {
            "objectId": obj_id,
            "style": style,
            "fields": fields,
            "textRange": text_range
        }
    }

def para_style(obj_id, alignment="START", line_spacing=115, space_above=0, space_below=0, start=0, end=None):
    style = {
        "alignment": alignment,
        "lineSpacing": line_spacing,
        "spaceAbove": {"magnitude": space_above, "unit": "PT"},
        "spaceBelow": {"magnitude": space_below, "unit": "PT"}
    }
    if end is not None:
        text_range = {"type": "FIXED_RANGE", "startIndex": start, "endIndex": end}
    else:
        text_range = {"type": "ALL"}
    return {
        "updateParagraphStyle": {
            "objectId": obj_id,
            "style": style,
            "fields": "alignment,lineSpacing,spaceAbove,spaceBelow",
            "textRange": text_range
        }
    }

def hairline_rule(obj_id, page_id, x, y, w, color=None):
    """Create a thin line (1px rule)"""
    if color is None:
        color = CLR_RULE
    return {
        "createLine": {
            "objectId": obj_id,
            "lineCategory": "STRAIGHT",
            "elementProperties": {
                "pageObjectId": page_id,
                "size": {"width": {"magnitude": w, "unit": "EMU"}, "height": {"magnitude": 0, "unit": "EMU"}},
                "transform": {
                    "scaleX": 1, "scaleY": 1,
                    "translateX": x, "translateY": y,
                    "unit": "EMU"
                }
            }
        }
    }

def style_line(obj_id, color, weight_pt=0.75):
    return {
        "updateLineProperties": {
            "objectId": obj_id,
            "lineProperties": {
                "lineFill": {"solidFill": {"color": {"rgbColor": color}, "alpha": 1}},
                "weight": {"magnitude": weight_pt, "unit": "PT"}
            },
            "fields": "lineFill,weight"
        }
    }

def create_image(obj_id, page_id, url, x, y, w, h):
    return {
        "createImage": {
            "objectId": obj_id,
            "url": url,
            "elementProperties": {
                "pageObjectId": page_id,
                "size": {"width": {"magnitude": w, "unit": "EMU"}, "height": {"magnitude": h, "unit": "EMU"}},
                "transform": {
                    "scaleX": 1, "scaleY": 1,
                    "translateX": x, "translateY": y,
                    "unit": "EMU"
                }
            }
        }
    }

def set_bg_white(page_id):
    return {
        "updatePageProperties": {
            "objectId": page_id,
            "pageProperties": {
                "pageBackgroundFill": {
                    "solidFill": {
                        "color": {"rgbColor": CLR_WHITE},
                        "alpha": 1
                    }
                }
            },
            "fields": "pageBackgroundFill"
        }
    }

# ─── Image URLs from original deck ─────────────────────────────────────────
IMG_ASSAF = "https://drive.google.com/uc?id=10BAILLxkPB65q7BzbBCBFDCjfbsxzNMY&export=download"
IMG_LUKAS = "https://drive.google.com/uc?id=1hE7dJeUljw_kvc-N_966uCBhxeFdzDwV&export=download"

# Agent avatars
IMG_KITT = "https://drive.google.com/uc?id=1Ef57IYYs3dV201eCzV__Ep8WJEJHVqnZ&export=download"
IMG_GERRI = "https://drive.google.com/uc?id=1kvYAo-FkNM8qO7yxGDWgsR8jAs5nMWI8&export=download"
IMG_OGILVY = "https://drive.google.com/uc?id=1dDPa88dlOB9vKRUleAFFN9JjCDGpaVHI&export=download"
IMG_TATIANA = "https://drive.google.com/uc?id=1dtw8hmaeL05e-tNz64xNawp2DI-Whcym&export=download"
IMG_ANTON = "https://drive.google.com/uc?id=12E0qOPobkyT4e0lRTU-pcymhyfJk3nNK&export=download"
IMG_JULIA = "https://drive.google.com/uc?id=1gUi6AamISXnbfCKMNNIzVw1_5PRpMvhK&export=download"
IMG_JESSICA = "https://drive.google.com/uc?id=1lpaF6NtqT3tMnrq8c0HqNhi3mUg1CqmI&export=download"
IMG_THIBAULT = "https://drive.google.com/uc?id=13GSmRuYEcBw6eRF7zD0sGDGy9DiTdzYi&export=download"


# ═══════════════════════════════════════════════════════════════════════════
# STEP 1: Create new presentation
# ═══════════════════════════════════════════════════════════════════════════
print("Creating new presentation...")
create_body = {
    "title": "Brandwatch × Curious Endeavor — v3 Editorial",
    "pageSize": {
        "width": {"magnitude": PAGE_W, "unit": "EMU"},
        "height": {"magnitude": PAGE_H, "unit": "EMU"}
    }
}
resp = requests.post(SLIDES_API, headers=headers, json=create_body)
if resp.status_code != 200:
    print(f"ERROR creating presentation: {resp.status_code} {resp.text}")
    exit(1)

pres = resp.json()
PRES_ID = pres['presentationId']
print(f"Created: {PRES_ID}")

# The first slide is auto-created, get its ID
first_slide_id = pres['slides'][0]['objectId']

# ═══════════════════════════════════════════════════════════════════════════
# STEP 2: Create 10 more blank slides (total 11), delete placeholder content
# ═══════════════════════════════════════════════════════════════════════════
print("Creating slides...")
slide_ids = [f"slide_{i}" for i in range(11)]
requests_batch = []

# Delete the auto-created first slide (we'll make our own)
requests_batch.append({"deleteObject": {"objectId": first_slide_id}})

# Create all 11 slides
for i, sid in enumerate(slide_ids):
    requests_batch.append({
        "createSlide": {
            "objectId": sid,
            "insertionIndex": i,
            "slideLayoutReference": {"predefinedLayout": "BLANK"}
        }
    })

# Set white backgrounds
for sid in slide_ids:
    requests_batch.append(set_bg_white(sid))

resp = requests.post(f"{SLIDES_API}/{PRES_ID}:batchUpdate", headers=headers, json={"requests": requests_batch})
if resp.status_code != 200:
    print(f"ERROR creating slides: {resp.status_code} {resp.text[:500]}")
    exit(1)
print("Slides created.")


# ═══════════════════════════════════════════════════════════════════════════
# STEP 3: Build all slide content
# ═══════════════════════════════════════════════════════════════════════════
reqs = []

def add_textbox(page_id, obj_id, x, y, w, h, text, font, size_pt, color, alignment="START", line_spacing=115, space_above=0, space_below=0, weight=400):
    """Helper: create textbox, insert text, style it."""
    tb = text_box(obj_id, x, y, w, h)
    tb["createShape"]["elementProperties"]["pageObjectId"] = page_id
    reqs.append(tb)
    reqs.append(insert_text(obj_id, text))
    reqs.append(style_text(obj_id, font, size_pt, color, weight=weight))
    reqs.append(para_style(obj_id, alignment, line_spacing, space_above, space_below))
    return obj_id

def add_line(page_id, x, y, w, color=None, weight_pt=0.75):
    lid = uid()
    r = hairline_rule(lid, page_id, x, y, w, color)
    reqs.append(r)
    reqs.append(style_line(lid, color or CLR_RULE, weight_pt))
    return lid

def add_image(page_id, url, x, y, w, h):
    iid = uid()
    reqs.append(create_image(iid, page_id, url, x, y, w, h))
    return iid

# ─── SLIDE 0: Cover ────────────────────────────────────────────────────────
s = slide_ids[0]
print("Building Slide 0: Cover")

# Thin red accent line at top
add_line(s, MARGIN_LEFT, int(INCH * 0.6), int(INCH * 0.6), CLR_RED, 1.5)

# Title: BRANDWATCH × CURIOUS ENDEAVOR — large editorial type
add_textbox(s, uid(), MARGIN_LEFT, int(PAGE_H * 0.30), int(CONTENT_W * 0.85), int(PT * 48),
    "BRANDWATCH × CURIOUS ENDEAVOR",
    FONT_DISPLAY, 42, CLR_TEXT, "START", 100, weight=400)

# Tagline lines
tagline = "Your partner that turns social intelligence into action.\nFinished creative, deployed across markets, in days instead of months."
add_textbox(s, uid(), MARGIN_LEFT, int(PAGE_H * 0.52), int(CONTENT_W * 0.7), int(PT * 50),
    tagline,
    FONT_BODY, 16, CLR_SECONDARY, "START", 140, space_above=0, space_below=4)

# URL at bottom left
add_textbox(s, uid(), MARGIN_LEFT, int(PAGE_H - MARGIN_BOTTOM - PT * 16), int(CONTENT_W * 0.4), int(PT * 16),
    "curiousendeavor.com/brandwatch-v2",
    FONT_BODY, 11, CLR_TERTIARY, "START", 100)

# Thin rule above URL
add_line(s, MARGIN_LEFT, int(PAGE_H - MARGIN_BOTTOM - PT * 24), int(CONTENT_W * 0.3), CLR_RULE, 0.5)


# ─── SLIDE 1: The Opportunity ──────────────────────────────────────────────
s = slide_ids[1]
print("Building Slide 1: The Opportunity")

# Section label with red accent
add_textbox(s, uid(), MARGIN_LEFT, MARGIN_TOP, int(INCH * 2), int(PT * 14),
    "THE OPPORTUNITY", FONT_BODY, 10, CLR_RED, "START", 100)

# Red accent dot/line next to label
add_line(s, MARGIN_LEFT, int(MARGIN_TOP + PT * 16), int(INCH * 0.4), CLR_RED, 1.0)

# Main statement — big editorial serif
heading_text = "Brandwatch is the world's best\nsocial intelligence platform."
add_textbox(s, uid(), MARGIN_LEFT, int(MARGIN_TOP + PT * 40), int(CONTENT_W * 0.75), int(PT * 80),
    heading_text,
    FONT_DISPLAY, 36, CLR_TEXT, "START", 115)

# Body text
body_text = "Your clients invest $100K–$500K/year for enterprise-grade social 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."
add_textbox(s, uid(), MARGIN_LEFT, int(PAGE_H * 0.52), int(CONTENT_W * 0.6), int(PT * 120),
    body_text,
    FONT_BODY, 15, CLR_SECONDARY, "START", 145, space_above=0, space_below=6)


# ─── SLIDE 2: What Agencies Charge ─────────────────────────────────────────
s = slide_ids[2]
print("Building Slide 2: What Agencies Charge")

# Section label
add_textbox(s, uid(), MARGIN_LEFT, MARGIN_TOP, int(INCH * 3), int(PT * 14),
    "WHAT AGENCIES CHARGE TODAY", FONT_BODY, 10, CLR_RED, "START", 100)

add_line(s, MARGIN_LEFT, int(MARGIN_TOP + PT * 16), int(INCH * 0.4), CLR_RED, 1.0)

# Hero number
add_textbox(s, uid(), MARGIN_LEFT, int(MARGIN_TOP + PT * 36), int(CONTENT_W * 0.7), int(PT * 60),
    "$200K–$1M+",
    FONT_DISPLAY, 54, CLR_TEXT, "START", 100)

# Subtitle
add_textbox(s, uid(), MARGIN_LEFT, int(MARGIN_TOP + PT * 100), int(CONTENT_W * 0.7), int(PT * 24),
    "per year in agency fees — on top of the Brandwatch license",
    FONT_BODY, 16, CLR_SECONDARY, "START", 100)

# Hairline separator
add_line(s, MARGIN_LEFT, int(PAGE_H * 0.48), CONTENT_W, CLR_RULE, 0.5)

# Cost breakdown — structured as clean line items
items = [
    ("Campaign strategy + brief", "$5K–$15K"),
    ("Creative development", "$10K–$50K"),
    ("Multi-market localization (per market)", "$3K–$8K"),
    ("Full campaign (strategy → assets)", "$25K–$150K"),
    ("Timeline", "6–12 weeks"),
]
y_start = int(PAGE_H * 0.52)
row_h = int(PT * 22)

for i, (label, cost) in enumerate(items):
    y = y_start + i * row_h
    # Label left
    add_textbox(s, uid(), MARGIN_LEFT, y, int(CONTENT_W * 0.6), int(PT * 18),
        label, FONT_BODY, 13, CLR_SECONDARY, "START", 100)
    # Cost right-aligned
    add_textbox(s, uid(), int(PAGE_W - MARGIN_RIGHT - INCH * 2), y, int(INCH * 2), int(PT * 18),
        cost, FONT_MONO, 13, CLR_TEXT, "END", 100)
    # Subtle rule below each row (except last)
    if i < len(items) - 1:
        add_line(s, MARGIN_LEFT, y + row_h - int(PT * 3), CONTENT_W, CLR_RULE, 0.25)


# ─── SLIDE 3: What We Do ───────────────────────────────────────────────────
s = slide_ids[3]
print("Building Slide 3: What We Do")

add_textbox(s, uid(), MARGIN_LEFT, MARGIN_TOP, int(INCH * 2), int(PT * 14),
    "WHAT WE DO", FONT_BODY, 10, CLR_RED, "START", 100)

add_line(s, MARGIN_LEFT, int(MARGIN_TOP + PT * 16), int(INCH * 0.4), CLR_RED, 1.0)

# Main heading
add_textbox(s, uid(), MARGIN_LEFT, int(MARGIN_TOP + PT * 36), int(CONTENT_W * 0.8), int(PT * 70),
    "AI-native creative production.\nFrom Brandwatch data to campaign-ready assets.",
    FONT_DISPLAY, 32, CLR_TEXT, "START", 120)

# Three pillars — editorial grid with red numbers
pillar_y = int(PAGE_H * 0.55)
col_w = int((CONTENT_W - INCH * 0.6) / 3)
pillars = [
    ("01", "Strategic\nIntelligence", "Insights your team\nhasn't seen yet"),
    ("02", "Parallel\nProduction", "8 AI agents working\nsimultaneously"),
    ("03", "Cross-Market\nIntelligence", "True localization,\nnot translation"),
]

for i, (num, title, desc) in enumerate(pillars):
    x = MARGIN_LEFT + i * (col_w + int(INCH * 0.3))
    
    # Red number
    add_textbox(s, uid(), x, pillar_y, int(PT * 30), int(PT * 20),
        num, FONT_MONO, 11, CLR_RED, "START", 100)
    
    # Red accent line
    add_line(s, x, pillar_y + int(PT * 22), int(INCH * 0.3), CLR_RED, 0.75)
    
    # Pillar title
    add_textbox(s, uid(), x, pillar_y + int(PT * 30), col_w, int(PT * 44),
        title, FONT_BODY, 16, CLR_TEXT, "START", 125, weight=500)
    
    # Description
    add_textbox(s, uid(), x, pillar_y + int(PT * 76), col_w, int(PT * 40),
        desc, FONT_BODY, 12, CLR_SECONDARY, "START", 140)


# ─── SLIDE 4: The Operators ─────────────────────────────────────────────────
s = slide_ids[4]
print("Building Slide 4: The Operators")

add_textbox(s, uid(), MARGIN_LEFT, MARGIN_TOP, int(INCH * 2), int(PT * 14),
    "THE OPERATORS", FONT_BODY, 10, CLR_RED, "START", 100)

add_line(s, MARGIN_LEFT, int(MARGIN_TOP + PT * 16), int(INCH * 0.4), CLR_RED, 1.0)

add_textbox(s, uid(), MARGIN_LEFT, int(MARGIN_TOP + PT * 28), int(CONTENT_W * 0.6), int(PT * 36),
    "Market veterans building the future",
    FONT_DISPLAY, 28, CLR_TEXT, "START", 100)

# Two-column layout for bios
col_w_bio = int((CONTENT_W - INCH * 0.5) / 2)
bio_y = int(PAGE_H * 0.35)

# Assaf
assaf_x = MARGIN_LEFT
try:
    add_image(s, IMG_ASSAF, assaf_x, bio_y, int(INCH * 0.9), int(INCH * 0.9))
except:
    pass

add_textbox(s, uid(), assaf_x + int(INCH * 1.1), bio_y, col_w_bio - int(INCH * 1.1), int(PT * 24),
    "Assaf Dagan", FONT_BODY, 18, CLR_TEXT, "START", 100, weight=500)

add_textbox(s, uid(), assaf_x + int(INCH * 1.1), bio_y + int(PT * 26), col_w_bio - int(INCH * 1.1), int(PT * 14),
    "STRATEGY & CREATIVE", FONT_BODY, 9, CLR_RED, "START", 100)

add_textbox(s, uid(), assaf_x + int(INCH * 1.1), bio_y + int(PT * 44), col_w_bio - int(INCH * 1.1), int(PT * 80),
    "15+ years. Presidential campaigns, Fortune 500 repositions. Wix, monday.com, eToro, Playtika, ironSource.\n\nBrand isn't decoration — it's the difference between a company people remember and one they don't.",
    FONT_BODY, 10, CLR_SECONDARY, "START", 145, space_below=3)

# Lukas
lukas_x = MARGIN_LEFT + col_w_bio + int(INCH * 0.5)
try:
    add_image(s, IMG_LUKAS, lukas_x, bio_y, int(INCH * 0.9), int(INCH * 0.9))
except:
    pass

add_textbox(s, uid(), lukas_x + int(INCH * 1.1), bio_y, col_w_bio - int(INCH * 1.1), int(PT * 24),
    "Lukas Richthammer", FONT_BODY, 18, CLR_TEXT, "START", 100, weight=500)

add_textbox(s, uid(), lukas_x + int(INCH * 1.1), bio_y + int(PT * 26), col_w_bio - int(INCH * 1.1), int(PT * 14),
    "FORMER BRANDWATCH · MARTECH SAAS & AI SALES", FONT_BODY, 9, CLR_RED, "START", 100)

add_textbox(s, uid(), lukas_x + int(INCH * 1.1), bio_y + int(PT * 44), col_w_bio - int(INCH * 1.1), int(PT * 80),
    "Sold Brandwatch to enterprise clients across DACH. Knows how buyers evaluate social intelligence, what drives renewals, and where the gap between data and action costs them.",
    FONT_BODY, 10, CLR_SECONDARY, "START", 145, space_below=3)


# ─── SLIDE 5: The System ───────────────────────────────────────────────────
s = slide_ids[5]
print("Building Slide 5: The System")

add_textbox(s, uid(), MARGIN_LEFT, MARGIN_TOP, int(INCH * 2), int(PT * 14),
    "THE SYSTEM", FONT_BODY, 10, CLR_RED, "START", 100)

add_line(s, MARGIN_LEFT, int(MARGIN_TOP + PT * 16), int(INCH * 0.4), CLR_RED, 1.0)

add_textbox(s, uid(), MARGIN_LEFT, int(MARGIN_TOP + PT * 28), int(CONTENT_W * 0.5), int(PT * 36),
    "Eight agents. One system.",
    FONT_DISPLAY, 28, CLR_TEXT, "START", 100)

# Grid of 8 agents: 4 columns × 2 rows
agents = [
    (IMG_KITT, "Kitt", "The Strategist"),
    (IMG_GERRI, "Gerri", "The Conductor"),
    (IMG_OGILVY, "Ogilvy", "The Poet"),
    (IMG_TATIANA, "Tatiana", "The Eye"),
    (IMG_ANTON, "Anton", "The Critic"),
    (IMG_JULIA, "Julia", "The Scout"),
    (IMG_JESSICA, "Jessica", "The Director"),
    (IMG_THIBAULT, "Thibault", "The Builder"),
]

cols = 4
agent_col_w = int((CONTENT_W) / cols)
avatar_size = int(INCH * 0.55)
row1_y = int(PAGE_H * 0.38)
row2_y = int(PAGE_H * 0.65)

for idx, (img_url, name, role) in enumerate(agents):
    row = idx // cols
    col = idx % cols
    x = MARGIN_LEFT + col * agent_col_w + int((agent_col_w - avatar_size) / 2)
    y = row1_y if row == 0 else row2_y
    
    # Avatar
    try:
        add_image(s, img_url, x, y, avatar_size, avatar_size)
    except:
        pass
    
    # Name
    name_x = MARGIN_LEFT + col * agent_col_w
    add_textbox(s, uid(), name_x, y + avatar_size + int(PT * 6), agent_col_w, int(PT * 18),
        name, FONT_BODY, 12, CLR_TEXT, "CENTER", 100, weight=500)
    
    # Role
    add_textbox(s, uid(), name_x, y + avatar_size + int(PT * 22), agent_col_w, int(PT * 14),
        role, FONT_BODY, 10, CLR_TERTIARY, "CENTER", 100)


# ─── SLIDE 6: How It Works ─────────────────────────────────────────────────
s = slide_ids[6]
print("Building Slide 6: How It Works")

add_textbox(s, uid(), MARGIN_LEFT, MARGIN_TOP, int(INCH * 2), int(PT * 14),
    "HOW IT WORKS", FONT_BODY, 10, CLR_RED, "START", 100)

add_line(s, MARGIN_LEFT, int(MARGIN_TOP + PT * 16), int(INCH * 0.4), CLR_RED, 1.0)

add_textbox(s, uid(), MARGIN_LEFT, int(MARGIN_TOP + PT * 28), int(CONTENT_W * 0.5), int(PT * 36),
    "Five phases. One pipeline.",
    FONT_DISPLAY, 28, CLR_TEXT, "START", 100)

phases = [
    ("01", "Data Extraction", "Pull structured audience intelligence from Brandwatch"),
    ("02", "Strategic Analysis", "Map pain points to positioning opportunities"),
    ("03", "Campaign Architecture", "Messaging, tone, and channel strategy per segment"),
    ("04", "Asset Production", "Parallel creation of production-ready deliverables"),
    ("05", "Multi-Region Scaling", "Localized strategy across all markets simultaneously"),
]

phase_y_start = int(PAGE_H * 0.35)
phase_row_h = int(PT * 48)

for i, (num, title, desc) in enumerate(phases):
    y = phase_y_start + i * phase_row_h
    
    # Number in red mono
    add_textbox(s, uid(), MARGIN_LEFT, y + int(PT * 4), int(PT * 30), int(PT * 20),
        num, FONT_MONO, 12, CLR_RED, "START", 100)
    
    # Title
    add_textbox(s, uid(), MARGIN_LEFT + int(INCH * 0.5), y, int(CONTENT_W * 0.35), int(PT * 20),
        title, FONT_BODY, 15, CLR_TEXT, "START", 100, weight=500)
    
    # Description
    add_textbox(s, uid(), MARGIN_LEFT + int(INCH * 0.5), y + int(PT * 22), int(CONTENT_W * 0.7), int(PT * 18),
        desc, FONT_BODY, 12, CLR_SECONDARY, "START", 100)
    
    # Subtle rule below
    if i < len(phases) - 1:
        add_line(s, MARGIN_LEFT, y + phase_row_h - int(PT * 6), CONTENT_W, CLR_RULE, 0.25)


# ─── SLIDE 7: Value for Brandwatch ─────────────────────────────────────────
s = slide_ids[7]
print("Building Slide 7: Value for Brandwatch")

add_textbox(s, uid(), MARGIN_LEFT, MARGIN_TOP, int(INCH * 3), int(PT * 14),
    "THE VALUE FOR BRANDWATCH", FONT_BODY, 10, CLR_RED, "START", 100)

add_line(s, MARGIN_LEFT, int(MARGIN_TOP + PT * 16), int(INCH * 0.4), CLR_RED, 1.0)

# 2×2 grid of value props
values = [
    ("Stickiness", "Brandwatch becomes indispensable because it doesn't just report — it responds. Churn drops."),
    ("New Revenue", "Creative layer as premium tier. $50K–$150K/year per client on top of existing subscription."),
    ("Category Creation", "No social intelligence platform does this. Own \"social intelligence to social action\" as a category."),
    ("Agency Disintermediation", "Brands pay Brandwatch for data AND an agency to act on it. Offer both — the agency becomes optional."),
]

grid_y = int(MARGIN_TOP + PT * 36)
col_w_val = int((CONTENT_W - INCH * 0.4) / 2)
row_h_val = int((PAGE_H - grid_y - MARGIN_BOTTOM) / 2)

for i, (title, desc) in enumerate(values):
    row = i // 2
    col = i % 2
    x = MARGIN_LEFT + col * (col_w_val + int(INCH * 0.4))
    y = grid_y + row * row_h_val
    
    # Red number
    num = f"0{i+1}"
    add_textbox(s, uid(), x, y, int(PT * 30), int(PT * 16),
        num, FONT_MONO, 10, CLR_RED, "START", 100)
    
    # Title
    add_textbox(s, uid(), x, y + int(PT * 20), col_w_val, int(PT * 24),
        title, FONT_DISPLAY, 22, CLR_TEXT, "START", 100)
    
    # Accent line
    add_line(s, x, y + int(PT * 46), int(INCH * 0.3), CLR_RED, 0.75)
    
    # Description
    add_textbox(s, uid(), x, y + int(PT * 54), col_w_val, int(PT * 60),
        desc, FONT_BODY, 12, CLR_SECONDARY, "START", 145, space_below=3)


# ─── SLIDE 8: Partnership Models ───────────────────────────────────────────
s = slide_ids[8]
print("Building Slide 8: Partnership Models")

add_textbox(s, uid(), MARGIN_LEFT, MARGIN_TOP, int(INCH * 2.5), int(PT * 14),
    "PARTNERSHIP MODELS", FONT_BODY, 10, CLR_RED, "START", 100)

add_line(s, MARGIN_LEFT, int(MARGIN_TOP + PT * 16), int(INCH * 0.4), CLR_RED, 1.0)

models = [
    ("A", "Technology Partnership", "CE's creative engine integrated as a Brandwatch premium feature. Revenue share. CE maintains the system, Brandwatch provides the distribution."),
    ("B", "White-Label", "CE runs under the Brandwatch brand. \"Brandwatch Creative Intelligence.\" Deeper integration. Maximum brand leverage."),
    ("C", "Acquisition", "Full integration into the product roadmap. Maximum commitment. Biggest upside for both."),
]

model_y = int(MARGIN_TOP + PT * 40)
col_w_model = int((CONTENT_W - INCH * 0.6) / 3)

for i, (letter, title, desc) in enumerate(models):
    x = MARGIN_LEFT + i * (col_w_model + int(INCH * 0.3))
    
    # Letter in display serif, red
    add_textbox(s, uid(), x, model_y, int(PT * 40), int(PT * 48),
        letter, FONT_DISPLAY, 42, CLR_RED, "START", 100)
    
    # Title
    add_textbox(s, uid(), x, model_y + int(PT * 52), col_w_model, int(PT * 24),
        title, FONT_BODY, 16, CLR_TEXT, "START", 100, weight=500)
    
    # Accent line
    add_line(s, x, model_y + int(PT * 78), int(INCH * 0.3), CLR_RED, 0.75)
    
    # Description
    add_textbox(s, uid(), x, model_y + int(PT * 88), col_w_model, int(PT * 100),
        desc, FONT_BODY, 12, CLR_SECONDARY, "START", 145, space_below=3)


# ─── SLIDE 9: The Ask ──────────────────────────────────────────────────────
s = slide_ids[9]
print("Building Slide 9: The Ask")

add_textbox(s, uid(), MARGIN_LEFT, MARGIN_TOP, int(INCH * 2), int(PT * 14),
    "THE ASK", FONT_BODY, 10, CLR_RED, "START", 100)

add_line(s, MARGIN_LEFT, int(MARGIN_TOP + PT * 16), int(INCH * 0.4), CLR_RED, 1.0)

# Big editorial question
add_textbox(s, uid(), MARGIN_LEFT, int(PAGE_H * 0.22), int(CONTENT_W * 0.8), int(PT * 110),
    "What would Brandwatch look like if every insight came with a ready-to-deploy creative response?",
    FONT_DISPLAY, 34, CLR_TEXT, "START", 125)

# The actual ask
add_textbox(s, uid(), MARGIN_LEFT, int(PAGE_H * 0.62), int(CONTENT_W * 0.65), int(PT * 100),
    "A 60-minute conversation with Brandwatch product leadership.\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.",
    FONT_BODY, 14, CLR_SECONDARY, "START", 150, space_below=5)


# ─── SLIDE 10: Contact ─────────────────────────────────────────────────────
s = slide_ids[10]
print("Building Slide 10: Contact")

# "Let's Talk" — large, centered
add_textbox(s, uid(), MARGIN_LEFT, int(PAGE_H * 0.18), CONTENT_W, int(PT * 60),
    "Let's Talk",
    FONT_DISPLAY, 48, CLR_TEXT, "CENTER", 100)

# Thin red line centered
center_x = int((PAGE_W - INCH * 1) / 2)
add_line(s, center_x, int(PAGE_H * 0.38), int(INCH * 1), CLR_RED, 1.0)

# Assaf info
add_textbox(s, uid(), int((PAGE_W - CONTENT_W * 0.5) / 2), int(PAGE_H * 0.44), int(CONTENT_W * 0.5), int(PT * 22),
    "Assaf Dagan", FONT_BODY, 16, CLR_TEXT, "CENTER", 100, weight=500)

add_textbox(s, uid(), int((PAGE_W - CONTENT_W * 0.5) / 2), int(PAGE_H * 0.44) + int(PT * 24), int(CONTENT_W * 0.5), int(PT * 18),
    "assaf@curiousendeavor.com", FONT_BODY, 13, CLR_SECONDARY, "CENTER", 100)

# Lukas info
add_textbox(s, uid(), int((PAGE_W - CONTENT_W * 0.5) / 2), int(PAGE_H * 0.58), int(CONTENT_W * 0.5), int(PT * 22),
    "Lukas Richthammer", FONT_BODY, 16, CLR_TEXT, "CENTER", 100, weight=500)

# URL
add_textbox(s, uid(), int((PAGE_W - CONTENT_W * 0.5) / 2), int(PAGE_H * 0.74), int(CONTENT_W * 0.5), int(PT * 16),
    "curiousendeavor.com/brandwatch-v2", FONT_BODY, 11, CLR_TERTIARY, "CENTER", 100)

# Bottom rule
add_line(s, center_x, int(PAGE_H * 0.70), int(INCH * 1), CLR_RULE, 0.5)


# ═══════════════════════════════════════════════════════════════════════════
# STEP 4: Execute batch update (in chunks to avoid API limits)
# ═══════════════════════════════════════════════════════════════════════════
print(f"\nTotal requests: {len(reqs)}")

CHUNK = 200
for i in range(0, len(reqs), CHUNK):
    chunk = reqs[i:i+CHUNK]
    print(f"  Sending batch {i//CHUNK + 1} ({len(chunk)} requests)...")
    resp = requests.post(f"{SLIDES_API}/{PRES_ID}:batchUpdate", headers=headers, json={"requests": chunk})
    if resp.status_code != 200:
        err = resp.text[:800]
        print(f"  ERROR at batch {i//CHUNK + 1}: {resp.status_code}")
        print(f"  {err}")
        # Try to continue with remaining
        # Find the failing request
        for j, req in enumerate(chunk):
            single_resp = requests.post(f"{SLIDES_API}/{PRES_ID}:batchUpdate", headers=headers, json={"requests": [req]})
            if single_resp.status_code != 200:
                print(f"    Failed request {i+j}: {list(req.keys())[0]}")
                print(f"    {single_resp.text[:200]}")
                break
        break
    time.sleep(0.5)

# ═══════════════════════════════════════════════════════════════════════════
# STEP 5: Set sharing permissions
# ═══════════════════════════════════════════════════════════════════════════
print("\nSetting sharing permissions...")
perm_body = {
    "role": "reader",
    "type": "anyone"
}
resp = requests.post(
    f"{DRIVE_API}/{PRES_ID}/permissions",
    headers=headers,
    json=perm_body
)
if resp.status_code == 200:
    print("Sharing enabled.")
else:
    print(f"Sharing error: {resp.status_code} {resp.text[:200]}")

share_link = f"https://docs.google.com/presentation/d/{PRES_ID}/edit?usp=sharing"
print(f"\n{'='*60}")
print(f"DONE! Share link:")
print(f"{share_link}")
print(f"{'='*60}")
