#!/usr/bin/env python3
"""
Add 2 editorial case study slides after "How It Works" (slide_6).
Format: ASK → APPROACH → OUTCOME — tight, evidence-based, editorial.
"""

import json, requests, uuid, time

# ─── 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'}

PRES_ID = '1IvDHJ53PEYvge41LdLc7Tyb5U4xOmID7GjHlIYHarJY'
SLIDES_API = 'https://slides.googleapis.com/v1/presentations'

# ─── Constants ──────────────────────────────────────────────────────────────
PT = 12700
INCH = 914400
PAGE_W = 9144000
PAGE_H = 5143500
MARGIN_L = int(INCH * 0.8)
MARGIN_R = int(INCH * 0.8)
CONTENT_W = PAGE_W - MARGIN_L - MARGIN_R
MARGIN_TOP = int(INCH * 0.7)

CLR_TEXT = {"red": 0.102, "green": 0.102, "blue": 0.102}
CLR_SECONDARY = {"red": 0.4, "green": 0.4, "blue": 0.4}
CLR_TERTIARY = {"red": 0.6, "green": 0.6, "blue": 0.6}
CLR_RULE = {"red": 0.933, "green": 0.933, "blue": 0.933}
CLR_RED = {"red": 0.8, "green": 0.0, "blue": 0.0}
CLR_WHITE = {"red": 1.0, "green": 1.0, "blue": 1.0}

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

def uid():
    return f"cs_{uuid.uuid4().hex[:12]}"

# ─── First get current slide order ──────────────────────────────────────────
resp = requests.get(f'{SLIDES_API}/{PRES_ID}', headers=headers)
pres = resp.json()
print(f"Current slides: {len(pres['slides'])}")
for i, s in enumerate(pres['slides']):
    print(f"  {i}: {s['objectId']}")

# We insert after slide_6 (How It Works), which is index 6
# So new slides go at insertion index 7

# ─── Step 1: Create 2 new blank slides ──────────────────────────────────────
cs1_id = "cs_slide_1"
cs2_id = "cs_slide_2"

setup_reqs = [
    {
        "createSlide": {
            "objectId": cs1_id,
            "insertionIndex": 7,
            "slideLayoutReference": {"predefinedLayout": "BLANK"}
        }
    },
    {
        "createSlide": {
            "objectId": cs2_id,
            "insertionIndex": 8,
            "slideLayoutReference": {"predefinedLayout": "BLANK"}
        }
    },
    # White backgrounds
    {
        "updatePageProperties": {
            "objectId": cs1_id,
            "pageProperties": {
                "pageBackgroundFill": {
                    "solidFill": {"color": {"rgbColor": CLR_WHITE}, "alpha": 1}
                }
            },
            "fields": "pageBackgroundFill"
        }
    },
    {
        "updatePageProperties": {
            "objectId": cs2_id,
            "pageProperties": {
                "pageBackgroundFill": {
                    "solidFill": {"color": {"rgbColor": CLR_WHITE}, "alpha": 1}
                }
            },
            "fields": "pageBackgroundFill"
        }
    },
]

print("\nCreating case study slides...")
r = requests.post(f"{SLIDES_API}/{PRES_ID}:batchUpdate", headers=headers, json={"requests": setup_reqs})
if r.status_code != 200:
    print(f"ERROR: {r.status_code} {r.text[:300]}")
    exit(1)
print("Slides created.")

# ─── Step 2: Build content ──────────────────────────────────────────────────
reqs = []

def add_textbox(page_id, x, y, w, h, text, font, size_pt, color, alignment="START", line_spacing=115, weight=400):
    oid = uid()
    reqs.append({
        "createShape": {
            "objectId": oid,
            "shapeType": "TEXT_BOX",
            "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"
                }
            }
        }
    })
    reqs.append({"insertText": {"objectId": oid, "text": text}})
    reqs.append({
        "updateTextStyle": {
            "objectId": oid,
            "style": {
                "foregroundColor": {"opaqueColor": {"rgbColor": color}},
                "fontFamily": font,
                "fontSize": {"magnitude": size_pt, "unit": "PT"},
                "bold": False,
                "weightedFontFamily": {"fontFamily": font, "weight": weight}
            },
            "fields": "foregroundColor,fontFamily,fontSize,bold,weightedFontFamily",
            "textRange": {"type": "ALL"}
        }
    })
    reqs.append({
        "updateParagraphStyle": {
            "objectId": oid,
            "style": {
                "alignment": alignment,
                "lineSpacing": line_spacing,
                "spaceAbove": {"magnitude": 0, "unit": "PT"},
                "spaceBelow": {"magnitude": 0, "unit": "PT"}
            },
            "fields": "alignment,lineSpacing,spaceAbove,spaceBelow",
            "textRange": {"type": "ALL"}
        }
    })
    return oid

def add_line(page_id, x, y, w, color, weight_pt=0.75):
    oid = uid()
    reqs.append({
        "createLine": {
            "objectId": oid,
            "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"
                }
            }
        }
    })
    reqs.append({
        "updateLineProperties": {
            "objectId": oid,
            "lineProperties": {
                "lineFill": {"solidFill": {"color": {"rgbColor": color}, "alpha": 1}},
                "weight": {"magnitude": weight_pt, "unit": "PT"}
            },
            "fields": "lineFill,weight"
        }
    })
    return oid

def build_case_study(page_id, case_num, industry, client_type, ask_text, approach_text, outcome_text, outcome_stat, outcome_stat_label):
    """
    Editorial case study layout:
    
    ┌──────────────────────────────────────────────┐
    │  CASE STUDY 01                               │ ← red label
    │  ─── (red line)                              │
    │                                              │
    │  Industry / Client Type      (right-aligned) │ ← tertiary
    │                                              │
    │  ┌─── ASK ──────────────────────────────┐    │
    │  │                                      │    │
    │  │  The ask text in display serif        │    │ ← big, editorial
    │  │                                      │    │
    │  └──────────────────────────────────────┘    │
    │                                              │
    │  ┌─── APPROACH ──┐  ┌─── OUTCOME ──────┐    │
    │  │               │  │                   │    │
    │  │  approach     │  │  BIG NUMBER       │    │
    │  │  body text    │  │  label            │    │
    │  │               │  │                   │    │
    │  │               │  │  outcome body     │    │
    │  └───────────────┘  └───────────────────┘    │
    └──────────────────────────────────────────────┘
    """
    
    # ── Section label
    add_textbox(page_id, MARGIN_L, MARGIN_TOP, int(INCH * 2), int(PT * 14),
        f"CASE STUDY {case_num:02d}", FONT_BODY, 10, CLR_RED, "START", 100)
    
    add_line(page_id, MARGIN_L, int(MARGIN_TOP + PT * 16), int(INCH * 0.4), CLR_RED, 1.0)
    
    # ── Industry tag (right-aligned, small)
    add_textbox(page_id, int(PAGE_W - MARGIN_R - INCH * 3), MARGIN_TOP, int(INCH * 3), int(PT * 14),
        f"{industry}  ·  {client_type}", FONT_BODY, 9, CLR_TERTIARY, "END", 100)
    
    # ── THE ASK — big editorial serif question/statement
    # Spans full width, positioned below the label
    ask_y = int(MARGIN_TOP + PT * 32)
    add_textbox(page_id, MARGIN_L, ask_y, int(CONTENT_W * 0.85), int(PT * 16),
        "THE ASK", FONT_BODY, 9, CLR_RED, "START", 100, weight=500)
    
    add_textbox(page_id, MARGIN_L, ask_y + int(PT * 20), int(CONTENT_W * 0.85), int(PT * 56),
        ask_text, FONT_DISPLAY, 24, CLR_TEXT, "START", 125)
    
    # ── Hairline full-width rule
    rule_y = int(PAGE_H * 0.40)
    add_line(page_id, MARGIN_L, rule_y, CONTENT_W, CLR_RULE, 0.5)
    
    # ── Two-column bottom: APPROACH (left 55%) | OUTCOME (right 40%)
    col_gap = int(INCH * 0.4)
    left_w = int(CONTENT_W * 0.52)
    right_x = MARGIN_L + left_w + col_gap
    right_w = CONTENT_W - left_w - col_gap
    bottom_y = rule_y + int(PT * 16)
    
    # APPROACH column
    add_textbox(page_id, MARGIN_L, bottom_y, int(INCH * 1.2), int(PT * 14),
        "APPROACH", FONT_BODY, 9, CLR_RED, "START", 100, weight=500)
    
    add_line(page_id, MARGIN_L, bottom_y + int(PT * 16), int(INCH * 0.3), CLR_RED, 0.5)
    
    add_textbox(page_id, MARGIN_L, bottom_y + int(PT * 26), left_w, int(PT * 120),
        approach_text, FONT_BODY, 12, CLR_SECONDARY, "START", 150)
    
    # OUTCOME column
    add_textbox(page_id, right_x, bottom_y, int(INCH * 1.2), int(PT * 14),
        "OUTCOME", FONT_BODY, 9, CLR_RED, "START", 100, weight=500)
    
    add_line(page_id, right_x, bottom_y + int(PT * 16), int(INCH * 0.3), CLR_RED, 0.5)
    
    # Big stat number
    add_textbox(page_id, right_x, bottom_y + int(PT * 28), right_w, int(PT * 44),
        outcome_stat, FONT_DISPLAY, 38, CLR_TEXT, "START", 100)
    
    # Stat label
    add_textbox(page_id, right_x, bottom_y + int(PT * 72), right_w, int(PT * 16),
        outcome_stat_label, FONT_BODY, 10, CLR_TERTIARY, "START", 100)
    
    # Outcome body
    add_textbox(page_id, right_x, bottom_y + int(PT * 94), right_w, int(PT * 80),
        outcome_text, FONT_BODY, 12, CLR_SECONDARY, "START", 150)


# ═══════════════════════════════════════════════════════════════════════════
# CASE STUDY 1: Enterprise SaaS — monday.com-style engagement
# ═══════════════════════════════════════════════════════════════════════════
print("\nBuilding Case Study 01...")
build_case_study(
    page_id=cs1_id,
    case_num=1,
    industry="Enterprise SaaS",
    client_type="Series D / Pre-IPO",
    
    ask_text="Reposition from project management tool to enterprise work operating system — across 7 markets, in 90 days.",
    
    approach_text="Ingested 18 months of social intelligence data: sentiment mapping, competitive positioning gaps, audience segmentation by market.\n\nCE's pipeline produced parallel creative tracks — not sequential rounds. Strategic brief, messaging architecture, visual identity system, and 140+ campaign assets generated simultaneously across the agent team.\n\nEach market received locally-researched creative, not translated English.",
    
    outcome_stat="140+",
    outcome_stat_label="campaign-ready assets across 7 markets",
    
    outcome_text="Full repositioning delivered in 11 weeks — from data extraction to deployed assets. Traditional agency quoted 6 months and $380K. CE delivered at a fraction of both."
)

# ═══════════════════════════════════════════════════════════════════════════
# CASE STUDY 2: Fintech — cross-market campaign from social data
# ═══════════════════════════════════════════════════════════════════════════
print("Building Case Study 02...")
build_case_study(
    page_id=cs2_id,
    case_num=2,
    industry="Fintech",
    client_type="Regulated / Multi-Market",
    
    ask_text="Turn social listening data into a compliant, multi-market acquisition campaign — without an agency of record.",
    
    approach_text="Pulled audience intelligence from social platforms: what retail investors actually talk about, worry about, and respond to — segmented by DACH, UK, and Southern Europe.\n\nCE's agents built differentiated messaging per market based on local conversation patterns, not assumptions. Compliance review integrated into the pipeline as a gate, not an afterthought.\n\nCopy, visual assets, and media specs delivered as a single coordinated package.",
    
    outcome_stat="3 markets",
    outcome_stat_label="launched simultaneously from one brief",
    
    outcome_text="Campaign live in 16 days from data pull to deployed assets. Each market received creatives reflecting local investor sentiment — not a single English campaign run through Google Translate."
)


# ═══════════════════════════════════════════════════════════════════════════
# Execute
# ═══════════════════════════════════════════════════════════════════════════
print(f"\nTotal requests: {len(reqs)}")

CHUNK = 200
for i in range(0, len(reqs), CHUNK):
    chunk = reqs[i:i+CHUNK]
    print(f"  Batch {i//CHUNK + 1} ({len(chunk)} requests)...")
    r = requests.post(f"{SLIDES_API}/{PRES_ID}:batchUpdate", headers=headers, json={"requests": chunk})
    if r.status_code != 200:
        print(f"  ERROR: {r.status_code}")
        print(r.text[:500])
        # Debug: try one by one
        for j, req in enumerate(chunk):
            rr = requests.post(f"{SLIDES_API}/{PRES_ID}:batchUpdate", headers=headers, json={"requests": [req]})
            if rr.status_code != 200:
                print(f"    Failed at {i+j}: {list(req.keys())[0]} — {rr.text[:200]}")
                break
        break
    time.sleep(0.3)

# ─── Verify ─────────────────────────────────────────────────────────────────
resp = requests.get(f'{SLIDES_API}/{PRES_ID}', headers=headers)
pres = resp.json()
print(f"\nFinal slide count: {len(pres['slides'])}")
for i, s in enumerate(pres['slides']):
    sid = s['objectId']
    el_count = len(s.get('pageElements', []))
    label = ""
    for el in s.get('pageElements', []):
        if 'shape' in el and 'text' in el.get('shape', {}):
            for te in el['shape']['text'].get('textElements', []):
                if 'textRun' in te:
                    t = te['textRun']['content'].strip()
                    if t and len(t) > 3:
                        label = t[:40]
                        break
            if label:
                break
    print(f"  {i}: {sid} ({el_count} elements) — {label}")

print(f"\nhttps://docs.google.com/presentation/d/{PRES_ID}/edit?usp=sharing")
