#!/usr/bin/env python3
"""Create eToro SOW as .docx with tables, then upload to Google Drive as Google Doc."""
from docx import Document
from docx.shared import Pt, Inches, RGBColor, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.oxml.ns import qn
import json, requests

doc = Document()

# Page margins
for section in doc.sections:
    section.top_margin = Cm(2.5)
    section.bottom_margin = Cm(2.5)
    section.left_margin = Cm(2.5)
    section.right_margin = Cm(2.5)

RED = RGBColor(0xCC, 0x00, 0x00)
GREY = RGBColor(0x66, 0x66, 0x66)
LIGHT_GREY = RGBColor(0x99, 0x99, 0x99)
BLACK = RGBColor(0x1A, 0x1A, 0x1A)
GREEN = RGBColor(0x28, 0xA7, 0x45)
WHITE = RGBColor(0xFF, 0xFF, 0xFF)

def set_cell_bg(cell, color_hex):
    shading = cell._element.get_or_add_tcPr()
    shd = shading.makeelement(qn('w:shd'), {
        qn('w:fill'): color_hex,
        qn('w:val'): 'clear'
    })
    shading.append(shd)

def add_label(text):
    p = doc.add_paragraph()
    run = p.add_run(text)
    run.font.name = 'Courier New'
    run.font.size = Pt(9)
    run.font.color.rgb = RED
    run.bold = True
    p.space_after = Pt(4)
    p.space_before = Pt(24)
    return p

def add_heading_text(text, size=18):
    p = doc.add_paragraph()
    run = p.add_run(text)
    run.font.size = Pt(size)
    run.bold = True
    run.font.color.rgb = BLACK
    p.space_after = Pt(8)
    return p

def add_body(text, color=None, italic=False, bold=False, size=10):
    p = doc.add_paragraph()
    run = p.add_run(text)
    run.font.size = Pt(size)
    run.font.color.rgb = color or BLACK
    run.italic = italic
    run.bold = bold
    p.space_after = Pt(4)
    return p

def add_table(headers, rows):
    table = doc.add_table(rows=1 + len(rows), cols=len(headers))
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    table.style = 'Table Grid'
    
    # Header row
    for i, h in enumerate(headers):
        cell = table.rows[0].cells[i]
        cell.text = ''
        p = cell.paragraphs[0]
        run = p.add_run(h)
        run.font.size = Pt(8)
        run.font.name = 'Courier New'
        run.bold = True
        run.font.color.rgb = GREY
        set_cell_bg(cell, 'FAFAFA')
    
    # Data rows
    for ri, row in enumerate(rows):
        for ci, val in enumerate(row):
            cell = table.rows[ri + 1].cells[ci]
            cell.text = ''
            p = cell.paragraphs[0]
            run = p.add_run(val)
            run.font.size = Pt(9)
            run.font.color.rgb = BLACK if ci == 0 else GREY
    
    doc.add_paragraph()  # spacing
    return table

def add_sep():
    p = doc.add_paragraph()
    run = p.add_run('─' * 60)
    run.font.size = Pt(6)
    run.font.color.rgb = RGBColor(0xEE, 0xEE, 0xEE)

# ========== DOCUMENT ==========

# Title block
add_label('CURIOUS ENDEAVOR × eTORO')
add_heading_text('Statement of Work', 26)
add_body('Brand Transformation & AI-Powered Production Systems', color=GREY, italic=True, size=12)
add_body('Date: February 2026  ·  Client: eToro  ·  Duration: 12-16 weeks', color=LIGHT_GREY, size=9)
add_sep()

add_body('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.')

# Timeline Overview
add_label('TIMELINE & INVESTMENT OVERVIEW')
add_heading_text('Project Timeline')
add_body('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.')

add_table(
    ['PHASE', 'DURATION', 'TIMELINE', 'DELIVERABLES', 'INVESTMENT'],
    [
        ['Phase 1\nDiscovery + Tech Setup', '~2 weeks', 'Weeks 1–2', 'Competitive research, brand audit, strategy, Discord/AI infrastructure', '€50,000\ncombined'],
        ['Phase 2\nRebrand + Brand System', '~2.5 weeks', 'Weeks 3–5', 'Brand book, design system, UI component foundations', ''],
        ['Phases 3–4\nImplementation + Scale', 'Ongoing', 'Week 6+', 'Brand deployment, AI studios, campaign systems', '€20,000/mo'],
    ]
)

add_body('Note: Delays in client response extend delivery day-for-day.', italic=True, color=LIGHT_GREY, size=9)
add_sep()

# Phase 1
add_label('PHASE 1 · ~2 WEEKS')
add_heading_text('Onboarding, Discovery & Tech Implementation')
add_body('We immerse ourselves in eToro\'s world: brand history, market position, culture, competitive landscape.')

add_table(
    ['PROCESS', 'TIME', 'DELIVERABLES'],
    [
        ['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 docs'],
        ['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, elevator pitch, gap analysis'],
        ['Team onboarding and training', 'optional', 'Training materials + onboarding sessions'],
        ['PHASE 1 TOTAL', '~15 DAYS', '~3 WORKING WEEKS'],
    ]
)

add_sep()

# Phase 2
add_label('PHASE 2 · ~2.5 WEEKS')
add_heading_text('Rebrand: Design Direction & Brand System')

add_body('Clarifications:', bold=True)
add_body('"Brand Design Lock" — formal sign-off on final creative direction.', color=GREY, size=9)
add_body('"UI component foundations" — core building blocks as design specs.', color=GREY, size=9)
add_body('"1 final design direction" — we present 2–3 options, eToro selects one.', color=GREY, size=9)

add_table(
    ['PROCESS', 'TIME', 'DELIVERABLES'],
    [
        ['2–3 inspiration directions + moodboards', '2 days', 'Moodboards + reference collection'],
        ['Stakeholder alignment sessions', '1 day', 'Alignment on chosen direction'],
        ['Brand Design Lock — 1 final direction', '3 days', 'Creative direction + rationale document'],
        ['Logo system development', '3 days', 'Logo system, usage + clear space rules'],
        ['Color palette + typography system', '1 day', 'Primary/secondary/extended palette + type system'],
        ['Tone of voice + photo language', '1 day', 'TOV guidelines, photo language guide'],
        ['Brand architecture + UI foundations', '1 day', 'Brand architecture map, UI foundations'],
        ['PHASE 2 TOTAL', '~12 DAYS', '~2.5 WORKING WEEKS'],
        ['Iteration rounds (3 included)', 'additional', 'Depends on client feedback turnaround'],
    ]
)

add_sep()

# Brand Book Scope
add_label('BRAND BOOK SCOPE')
add_body('Digital, interactive brand book hosted on a dedicated webpage — not a static PDF.', italic=True)

add_table(
    ['SECTION', 'CONTENTS'],
    [
        ['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'],
        ['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_sep()

# Phase 3 & 4
add_label('PHASE 3 (OPTIONAL) · ~3-4 WEEKS')
add_heading_text('Implementation')
add_body('Brand deployment across touchpoints. Three AI + human studios: photography, screen/product imagery, motion design.')
add_sep()

add_label('PHASE 4 (OPTIONAL) · ~3-5 WEEKS')
add_heading_text('Scale: Campaign Machine & Automation')
add_body('Campaign generation, landing pages, multi-variant creative, full funnel automation.')
add_sep()

# Investment
add_label('YOUR INVESTMENT & PAYMENT TERMS')
add_heading_text('Brand Transformation (Phases 1-2): €50,000', 14)
add_body('Complete rebrand: discovery, strategy, brand book, design system.', color=GREY)
add_heading_text('Implementation (Phases 3-4) · Optional: €20,000/month', 14)
add_body('Accompanying internal team through implementation and scale.', color=GREY)
add_body('Payment — milestone-based, invoices due within 15 days:', bold=True)
add_body('▸ 50% upon signing (€25,000) — covers Phase 1 + Phase 2 initiation')
add_body('▸ 50% upon brand book delivery (€25,000) — subject to written approval per MSA §1.3')
add_sep()

# Expenses
add_label('EXPENSES & OPERATIONAL COSTS')
add_body('All operational expenses borne by eToro: API calls, software licenses, font licensing, image rights, domain costs, hosting, third-party fees. Itemized reporting upon request.')
add_sep()

# IP
add_label('IP & SYSTEM OWNERSHIP')
add_heading_text('Intellectual Property & System Ownership')
add_body('Licensed model: eToro interacts through brand interface (inputs → outputs). Engine remains CE\'s IP.')

add_table(
    ['eTORO OWNS OUTRIGHT', 'CURIOUS ENDEAVOR RETAINS'],
    [
        ['All brand assets, design system, visual output', 'AI agent architecture, configurations, prompt engineering'],
        ['Visual language, iconography, design deliverables', 'System config files, setup, technical infrastructure'],
        ['Brand book and all brand documentation', 'Custom prompts, prompt templates, prompt logic'],
        ['All content/creative output from the system', 'Production workflow logic and automation systems'],
        ['Full right to use, modify, extend all output', 'Core methodology, frameworks, strategic approach'],
        ['', 'Proprietary tools, templates, base systems'],
        ['', 'Discord server structure, roles, channels, bots'],
        ['', 'Training methods and operational playbooks'],
    ]
)

add_label('PERPETUAL OPERATING LICENSE')

add_table(
    ['eTORO MAY ✓', 'eTORO MAY NOT ✗'],
    [
        ['Operate the system day-to-day for eToro brand work', 'Access/extract/inspect agent architecture or prompts'],
        ['Modify brand book and design system at will', 'Duplicate/adapt for other brands or purposes'],
        ['Update brand guidelines and design tokens', 'Share/sublicense/let third parties reverse-engineer'],
        ['Prompt the system to create assets and content', 'Hire third parties to modify system architecture'],
        ['Evolve the brand — all brand-level changes in control', 'Reverse-engineer to build competing system'],
        ['Use for the eToro brand as defined in this SOW', ''],
    ]
)

add_body('System-Level Modifications require CE. Exclusive implementation rights for 12 months post-completion.', bold=True, size=9)
add_sep()

# PR
add_label('PR RIGHTS & DOCUMENTATION')

add_table(
    ['CE MAY FREELY SHARE', 'REQUIRES eTORO APPROVAL'],
    [
        ['Process, methodology, tools, behind-the-scenes', 'eToro name/logo in press or marketing'],
        ['Screenshots of our own tools and systems', 'Unreleased or in-progress brand assets'],
        ['General descriptions ("major fintech")', 'eToro internal or confidential materials'],
        ['Visual work samples (excl. logo)', 'Formal case studies naming eToro'],
        ['Post-launch portfolio samples', 'Media interviews referencing eToro'],
        ['Conference/podcast appearances', ''],
    ]
)

add_body('Approval not unreasonably withheld. Joint PR strategy in Phase 1.', italic=True, size=9)
add_body('Credit: eToro credits CE as strategic partner incl. Dan Peguine and Assaf Dagan.', size=9)
add_sep()

# SLAs
add_label('SERVICE LEVEL AGREEMENTS')

add_table(
    ['TYPE', 'CURIOUS ENDEAVOR', 'eTORO (PER MSA §4)'],
    [
        ['Day-to-day requests', '1 business day', '2 business days'],
        ['New / unanticipated requests', '1 business day', '4 business days'],
        ['Design validation / approval', '—', '10 business days'],
    ]
)

add_body('Working days: Mon–Fri. Weekends/holidays excluded.', italic=True, color=LIGHT_GREY, size=9)
add_sep()

# Timeline Impact
add_label('TIMELINE & APPROVAL IMPACT')
add_body('Client delays extend delivery day-for-day. Example: feedback on Day 10 → timeline shifts 8 days.')
add_sep()

# Governance
add_label('GOVERNANCE')
add_body('▸ Designated Project Contacts for day-to-day decisions')
add_body('▸ Weekly 30-min sync between contacts')
add_body('▸ Discord workspace as primary collaboration channel')
add_body('▸ 3-day escalation to senior leadership')
add_sep()

# Liability
add_label('LIABILITY')
add_body('Per MSA §10 and §12. No indirect/consequential damages. Total liability capped at SOW amounts paid.')
add_sep()

# Signatures
add_label('SIGNATURES')
doc.add_paragraph()
add_heading_text('Curious Endeavor LLC', 13)
add_body('Name: ____________________________    Title: ____________________________')
add_body('Signature: ________________________    Date: _____________________________')
doc.add_paragraph()
add_heading_text('eToro', 13)
add_body('Name: ____________________________    Title: ____________________________')
add_body('Signature: ________________________    Date: _____________________________')
doc.add_paragraph()
add_body('Creativity is a curious and unexpected endeavor.', italic=True, color=RED, size=9)

# Save
docx_path = '/root/.openclaw/workspace/public/etoro/sow/etoro-sow.docx'
doc.save(docx_path)
print(f"Saved: {docx_path}")

# Upload to Google Drive as Google Doc
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']

# Delete old broken doc
requests.delete(
    'https://www.googleapis.com/drive/v3/files/10r3v7Xqm4tltaFoSpD4F7Vn_kGENJVQgeWrvJxKyc6Q',
    headers={'Authorization': f'Bearer {access_token}'}
)

# Upload .docx and convert to Google Doc
import io
metadata = json.dumps({'name': 'Curious Endeavor × eToro — Statement of Work', 'mimeType': 'application/vnd.google-apps.document'})
with open(docx_path, 'rb') as f:
    file_data = f.read()

resp = requests.post(
    'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
    headers={'Authorization': f'Bearer {access_token}'},
    files={
        'metadata': ('metadata', metadata, 'application/json'),
        'file': ('etoro-sow.docx', file_data, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    }
)
result = resp.json()
doc_id = result.get('id', 'unknown')
print(f"Uploaded: https://docs.google.com/document/d/{doc_id}/edit")

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

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