#!/usr/bin/env python3
"""Create a styled Google Doc version of the eToro SOW - v2 (insert all text, then format)."""
import json, requests

with open('/root/.openclaw/workspace/google-auth/token.json') as f:
    d = json.load(f)

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

# Build the full document text first
lines = []
formats = []  # (start_offset_in_line_index, line_index, style_dict)

def add(text, bold=False, italic=False, font_size=11, font_family='Inter', color=None):
    lines.append(text)
    style = {}
    if bold: style['bold'] = True
    if italic: style['italic'] = True
    style['fontSize'] = {'magnitude': font_size, 'unit': 'PT'}
    style['weightedFontFamily'] = {'fontFamily': font_family}
    if color:
        rv = int(color[1:3], 16) / 255
        gv = int(color[3:5], 16) / 255
        bv = int(color[5:7], 16) / 255
        style['foregroundColor'] = {'color': {'rgbColor': {'red': rv, 'green': gv, 'blue': bv}}}
    formats.append((len(lines)-1, style))

# === DOCUMENT CONTENT ===
add('CURIOUS ENDEAVOR × eTORO', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Statement of Work', bold=True, font_size=28)
add('Brand Transformation & AI-Powered Production Systems', italic=True, font_size=14, color='#666666')
add('')
add('Date: February 2026  ·  Client: eToro  ·  Duration: 12-16 weeks', font_size=10, font_family='JetBrains Mono', color='#999999')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')
add('This Statement of Work ("SOW") made effective as of February 2026, is entered into by and between Curious Endeavor LLC, ("Curious Endeavor") and eToro ("Company"). Unless otherwise specified, capitalized terms used in this SOW shall have the meanings defined in the Agreement.')
add('')

# Timeline
add('TIMELINE & INVESTMENT OVERVIEW', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Project Timeline', bold=True, font_size=18)
add('Total duration: ~5 weeks for Phases 1-2, with Phases 3-4 ongoing from Week 6. All dates assume client feedback within 2 business days per MSA Section 4. Delays in client response extend phase duration day-for-day.')
add('')
add('Phase 1 — Discovery + Tech Setup  ·  ~2 weeks (Weeks 1–2)  ·  €50,000 combined', bold=True)
add('Competitive research, brand audit, strategy foundation, Discord/AI infrastructure', color='#666666')
add('Phase 2 — Rebrand + Brand System  ·  ~2.5 weeks (Weeks 3–5)', bold=True)
add('Brand book, design system, UI component foundations', color='#666666')
add('Phases 3–4 — Implementation + Scale  ·  Week 6+  ·  €20,000/month', bold=True)
add('Brand deployment, AI studios, campaign systems', color='#666666')
add('')
add('Note: All timelines assume client feedback within 2 business days. Delays extend delivery day-for-day. Calendar dates confirmed upon signing.', italic=True, font_size=10, color='#999999')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# Phase 1
add('PHASE 1 · ~2 WEEKS', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Onboarding, Discovery & Tech Implementation', bold=True, font_size=18)
add('In the onboarding phase, we immerse ourselves in eToro\'s world: understanding your brand history, market position, internal culture, and competitive landscape.')
add('')
for proc, time, deliv in [
    ('C-Suite / leadership interviews', '2 days', 'Stakeholder insights document'),
    ('Brand perception audit (internal + external)', '1 day', 'Brand perception report'),
    ('Competitive deep-dive (visual, messaging, product)', '1 day', 'Exhaustive competitive research document'),
    ('Discord server setup with role-based access', '2 days', 'Dedicated Discord workspace'),
    ('AI workflow implementation', '2 days', 'AI-augmented production team + workflow documentation'),
    ('Competitive research document', '2 days', 'Industry + competition landscape deck'),
    ('Technology and platform audit', 'optional', 'Platform audit report'),
    ('Brand positioning, narrative, pitch, mission', '~5 days', 'Brand narrative + mission statement, elevator pitch, gap analysis'),
    ('Team onboarding and training', 'optional', 'Training materials + onboarding sessions'),
]:
    c = '#999999' if time == 'optional' else None
    add(f'▸ {proc}  —  {time}', bold=True, font_size=10, color=c)
    add(f'   {deliv}', font_size=10, color='#666666')

add('')
add('Phase 1 Total: ~15 days (~3 working weeks)', bold=True, color='#cc0000')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# Phase 2
add('PHASE 2 · ~2.5 WEEKS', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Rebrand: Design Direction & Brand System', bold=True, font_size=18)
add('This phase defines eToro\'s elevated brand identity across all touchpoints.')
add('')
add('Clarifications:', bold=True)
add('"Brand Design Lock" — formal sign-off milestone on final creative direction.', color='#666666', font_size=10)
add('"UI component foundations" — core visual building blocks as design specs for engineering.', color='#666666', font_size=10)
add('"1 final design direction" — we present 2–3 options, eToro selects one.', color='#666666', font_size=10)
add('')

for proc, time, deliv in [
    ('2–3 inspiration directions + moodboards', '2 days', 'Moodboards + reference collection per direction'),
    ('Stakeholder alignment sessions', '1 day', 'Alignment on chosen direction'),
    ('Brand Design Lock — 1 final design direction', '3 days', 'Creative direction and rationale document'),
    ('Logo system development', '3 days', 'Logo system + concept overview, usage and clear space rules'),
    ('Color palette + typography system', '1 day', 'Primary, secondary, extended palette + type system'),
    ('Tone of voice + photo language', '1 day', 'Tone of voice guidelines, photo language and treatment guide'),
    ('Brand architecture + UI component foundations', '1 day', 'Brand architecture map, UI component foundations'),
]:
    add(f'▸ {proc}  —  {time}', bold=True, font_size=10)
    add(f'   {deliv}', font_size=10, color='#666666')

add('')
add('Phase 2 Total: ~12 days (~2.5 working weeks)', bold=True, color='#cc0000')
add('Iteration rounds: 3 rounds included — additional to work timeline, depends on client feedback.', italic=True, font_size=10, color='#999999')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# Brand Book Scope
add('BRAND BOOK SCOPE', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Digital, interactive document hosted on a dedicated webpage. Single source of truth for eToro\'s brand identity.')
add('')
for section, contents in [
    ('Brand Strategy', 'Creative direction, brand narrative, mission statement, elevator pitch, positioning'),
    ('Logo System', 'Logo concept, usage rules, clear space, minimum sizes, do\'s/don\'ts, file formats'),
    ('Color Palette', 'Primary/secondary/extended palette, hex/RGB/CMYK, usage guidelines, accessibility'),
    ('Typography', 'Type hierarchy, font families, weights, sizes, spacing, usage rules'),
    ('Tone of Voice', 'Voice principles, writing guidelines, example copy for different contexts'),
    ('Photo & Image Language', 'Photography style, treatment guide, composition rules, illustration guidelines'),
    ('Visual Language & Iconography', 'Icon system, visual language guidelines, graphic elements'),
    ('Brand Architecture', 'Sub-brand relationships, naming conventions, brand hierarchy'),
    ('UI Component Foundations', 'Core building blocks as design specs for engineering teams'),
]:
    add(f'▸ {section}', bold=True, font_size=10)
    add(f'   {contents}', font_size=10, color='#666666')

add('')
add('Format: Digital brand book on dedicated webpage — not a static PDF. Interactive examples, downloadable assets, copy-paste specs.', italic=True, font_size=10, color='#999999')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# Phase 3
add('PHASE 3 (OPTIONAL) · ~3-4 WEEKS', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Implementation', bold=True, font_size=18)
add('Brand deployment across all touchpoints. Three AI + human content production studios: Human photography, Screen/product imagery, Motion design.')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# Phase 4
add('PHASE 4 (OPTIONAL) · ~3-5 WEEKS', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Scale: Campaign Machine & Automation', bold=True, font_size=18)
add('Campaign generation, landing page systems, multi-variant creative, full funnel automation. Self-sustaining brand machine.')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# Investment
add('YOUR INVESTMENT & PAYMENT TERMS', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('')
add('Brand Transformation (Phases 1-2): €50,000', bold=True, font_size=16)
add('Complete rebrand including discovery, strategy, brand book, and design system.', color='#666666')
add('')
add('Implementation Support (Phases 3-4) · Optional: €20,000/month', bold=True, font_size=16)
add('Accompanying the internal team through implementation and scale phases.', color='#666666')
add('')
add('Payment Terms — Milestone-based, invoices due within 15 days:', bold=True)
add('▸ 50% upon signing (€25,000) — covers Phase 1 + Phase 2 initiation. Secures resource allocation.')
add('▸ 50% upon brand book delivery (€25,000) — subject to eToro written approval per MSA §1.3.')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# Expenses
add('EXPENSES & OPERATIONAL COSTS', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('All operational expenses borne by eToro: API calls, software licenses, typography/font licensing, image rights, domain costs, hosting, third-party fees. Itemized reporting upon request.')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# IP
add('IP & SYSTEM OWNERSHIP', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Intellectual Property & System Ownership', bold=True, font_size=18)
add('The production system operates on a licensed model: eToro interacts through the brand interface layer (brand inputs → brand outputs). The underlying engine remains Curious Endeavor\'s IP.')
add('')
add('eToro Owns Outright:', bold=True, font_size=12)
add('▸ All brand assets, design system, and visual output produced')
add('▸ Visual language, iconography, and all design deliverables')
add('▸ Brand book and all brand documentation')
add('▸ All content and creative output generated through the system')
add('▸ Full right to use, modify, and extend all output for any purpose')
add('')
add('Curious Endeavor Retains Ownership:', bold=True, font_size=12)
add('▸ AI agent architecture, configurations, and prompt engineering')
add('▸ All system configuration files, setup, and technical infrastructure')
add('▸ Custom prompts, prompt templates, and prompt logic')
add('▸ Production workflow logic and automation systems')
add('▸ Core methodology, frameworks, and strategic approach')
add('▸ Proprietary tools, templates, and base systems')
add('▸ Discord server structure, roles, channels, and bot configurations')
add('▸ Training methods and operational playbooks')
add('')

add('PERPETUAL OPERATING LICENSE', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('eToro receives a perpetual, non-exclusive, non-transferable license for eToro brand purposes.')
add('')
add('eToro May:', bold=True, color='#28a745')
add('▸ Operate the production system day-to-day for eToro brand work')
add('▸ Modify their brand book and design system at will — system adapts accordingly')
add('▸ Update brand guidelines (colors, fonts, tone, imagery) and design tokens')
add('▸ Prompt the system to create brand assets, campaigns, and content')
add('▸ Evolve the brand over time — all brand-level changes fully within eToro\'s control')
add('▸ Use the system for the eToro brand as defined in this SOW')
add('')
add('eToro May Not:', bold=True, color='#cc0000')
add('▸ Access, extract, or inspect underlying agent architecture, prompts, or workflow logic')
add('▸ Duplicate or adapt the system for other brands or purposes beyond this SOW')
add('▸ Share, sublicense, or allow third parties to study, copy, or reverse-engineer the system')
add('▸ Hire third parties to modify the agent layer, workflow logic, or system architecture')
add('▸ Reverse-engineer the methodology to build a competing or derivative system')
add('')
add('System-Level Modifications: Require engagement with CE. CE holds exclusive implementation rights for 12 months post-completion.', bold=True, font_size=10)
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# PR
add('PR RIGHTS & DOCUMENTATION', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('')
add('CE May Freely Share:', bold=True, color='#28a745')
add('▸ Process, methodology, tools, behind-the-scenes workflow on social media')
add('▸ Screenshots of our own tools and systems')
add('▸ General descriptions ("working with a major fintech")')
add('▸ Visual work samples (excluding logo and unreleased final assets)')
add('▸ Post-launch portfolio samples, conference/podcast appearances')
add('')
add('Requires eToro Approval:', bold=True, color='#cc0000')
add('▸ Use of eToro name/logo in press or marketing')
add('▸ Unreleased brand assets')
add('▸ Confidential materials')
add('▸ Formal case studies naming eToro')
add('▸ Media interviews referencing eToro')
add('')
add('Approval not unreasonably withheld. Joint PR strategy developed in Phase 1.')
add('Credit: eToro credits CE as strategic partner, including Dan Peguine and Assaf Dagan by name.')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# Timeline Impact
add('TIMELINE & APPROVAL IMPACT', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Client delays extend delivery day-for-day. Example: feedback on Day 10 = timeline shifts 8 days (10 minus 2-day SLA).')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# SLAs
add('SERVICE LEVEL AGREEMENTS', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Day-to-day: CE 1 biz day · eToro 2 biz days')
add('New requests: CE 1 biz day · eToro 4 biz days')
add('Design validation: eToro 10 biz days')
add('Working days: Mon–Fri. Weekends/holidays excluded.', italic=True, font_size=10, color='#999999')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# Governance
add('GOVERNANCE', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('▸ Designated Project Contacts for day-to-day decisions')
add('▸ Weekly 30-min sync between contacts')
add('▸ Discord workspace as primary collaboration channel')
add('▸ 3-day escalation to senior leadership')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')

# Liability
add('LIABILITY', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('Per MSA §10 and §12. No indirect/consequential damages. Total liability capped at SOW amounts paid.')
add('─────────────────────────────────────────────────────────', font_size=8, color='#eeeeee')
add('')
add('')

# Signatures
add('SIGNATURES', bold=True, font_size=10, font_family='JetBrains Mono', color='#cc0000')
add('')
add('Curious Endeavor LLC', bold=True, font_size=14)
add('Name: ____________________________    Title: ____________________________')
add('Signature: ________________________    Date: _____________________________')
add('')
add('eToro', bold=True, font_size=14)
add('Name: ____________________________    Title: ____________________________')
add('Signature: ________________________    Date: _____________________________')
add('')
add('')
add('Creativity is a curious and unexpected endeavor.', italic=True, font_size=10, color='#cc0000')

# === CREATE DOC AND INSERT ===
full_text = '\n'.join(lines) + '\n'

# Create doc
r = requests.post('https://docs.googleapis.com/v1/documents', headers=headers,
    json={'title': 'Curious Endeavor × eToro — Statement of Work'})
doc = r.json()
doc_id = doc['documentId']
print(f"Doc: https://docs.google.com/document/d/{doc_id}/edit")

# Insert all text at once
insert_req = [{'insertText': {'location': {'index': 1}, 'text': full_text}}]
r = requests.post(f'https://docs.googleapis.com/v1/documents/{doc_id}:batchUpdate',
    headers=headers, json={'requests': insert_req})
if r.status_code != 200:
    print(f'Insert error: {r.text[:300]}')

# Now apply formatting
fmt_reqs = []
offset = 1  # starts at 1 in Google Docs
for i, line in enumerate(lines):
    line_start = offset
    line_end = offset + len(line)
    
    # Find format for this line
    for li, style in formats:
        if li == i and len(line) > 0:
            fields = ','.join(style.keys())
            fmt_reqs.append({
                'updateTextStyle': {
                    'range': {'startIndex': line_start, 'endIndex': line_end},
                    'textStyle': style,
                    'fields': fields
                }
            })
            break
    
    offset += len(line) + 1  # +1 for newline

# Apply in batches
for i in range(0, len(fmt_reqs), 50):
    batch = fmt_reqs[i:i+50]
    r = requests.post(f'https://docs.googleapis.com/v1/documents/{doc_id}:batchUpdate',
        headers=headers, json={'requests': batch})
    if r.status_code != 200:
        print(f'Format batch {i} error: {r.text[:300]}')

# Set margins
r = requests.post(f'https://docs.googleapis.com/v1/documents/{doc_id}:batchUpdate',
    headers=headers, json={'requests': [{
        'updateDocumentStyle': {
            'documentStyle': {
                'marginTop': {'magnitude': 72, 'unit': 'PT'},
                'marginBottom': {'magnitude': 72, 'unit': 'PT'},
                'marginLeft': {'magnitude': 72, 'unit': 'PT'},
                'marginRight': {'magnitude': 72, 'unit': 'PT'},
            },
            'fields': 'marginTop,marginBottom,marginLeft,marginRight'
        }
    }]})

# Share
for email in ['assafdagan@gmail.com', 'assaf@curiousendeavor.com']:
    requests.post(f'https://www.googleapis.com/drive/v3/files/{doc_id}/permissions',
        headers=headers, json={'type': 'user', 'role': 'writer', 'emailAddress': email})

print(f"Done! https://docs.google.com/document/d/{doc_id}/edit")
