#!/usr/bin/env python3
"""
Insert eToro proposals inline with Phat Foods sections, in blue.
Strategy:
1. Delete previously added content
2. Find each section, insert eToro proposal after it in blue
"""

import asyncio
from playwright.async_api import async_playwright

DOC_URL = "https://docs.google.com/document/d/1rydxZmGNlK4nJkRV9KVVVfj7ctW-uvA-djebU-07ISw/edit"

# Sections to add - each has search text and proposal content
SECTIONS = [
    {
        "name": "Header",
        "search_after": "Naming and branding",
        "content": """
[eTORO PROPOSAL]
Date: [TBD]
Client: eToro
Project name: Brand Transformation & AI-Powered Production Systems
"""
    },
    {
        "name": "Stage 1 Intro", 
        "search_after": "how we stand out.",
        "content": """
[eTORO PROPOSAL - Phase 1: Onboarding, Discovery & Tech Implementation]

In the onboarding phase, we immerse ourselves in eToro's world—understanding your brand history, market position, internal culture, and competitive landscape. We conduct comprehensive stakeholder interviews and exhaustive competitive research to identify opportunities for differentiation.

Simultaneously, we implement the operational infrastructure that will power the rebrand: a dedicated Discord server with AI-augmented workflows, and a bespoke team of human + AI collaborators trained on eToro's specific needs.
"""
    },
    {
        "name": "Stage 1 Table",
        "search_after": "position and value to the market.",
        "content": """
[eTORO Phase 1 Deliverables]

Process:
• One-on-one sessions with C-Level / leadership
• Cross-functional team interviews  
• Brand perception audit (internal + external)
• Competitive deep-dive (visual, messaging, product)
• Discord server setup with role-based access
• AI workflow implementation
• Team onboarding and training

Deliverables:
• Exhaustive competitive research document
• Technology and platform audit
• Brand positioning gap analysis
• Brand narrative + Mission statement
• Elevator pitch candidates
• Industry + Competition landscape deck
• Dedicated Discord workspace
• AI-augmented production team (trained on eToro)
• Workflow documentation
"""
    },
    {
        "name": "Stage 2 Intro",
        "search_after": "feel good and look the part.",
        "content": """
[eTORO PROPOSAL - Phase 2: Rebrand - Design Direction & Brand System]

With strategic foundations in place, we move into the creative heart of the transformation. This phase defines eToro's elevated brand identity—how it looks, feels, and sounds across all touchpoints. We explore multiple design directions, refine through structured critique, and deliver a complete brand system ready for implementation.
"""
    },
    {
        "name": "Stage 2 Table",
        "search_after": "development or design production is included in this SOW",
        "content": """
[eTORO Phase 2 Deliverables]

Process:
• 2-3 inspiration directions
• Moodboards and reference collection
• Stakeholder alignment sessions
• 1 final design direction (Brand Design Lock)
• 1 round of iterations included

Deliverables - Brand Book:
• Creative direction and rationale
• Logo system + concept overview
• Wordmark and logomark variations
• Color palette (primary, secondary, extended)
• Typography system (hierarchy, pairings)
• Tone of voice guidelines

Deliverables - Design System:
• Logo usage and clear space rules
• Photo language and treatment guide
• Brand architecture (sub-brands, products)
• UI component foundations
• Application examples (digital, print, motion)
"""
    },
    {
        "name": "Stage 3",
        "search_after": "Final Brand Guidelines outlined in Stage 2",
        "content": """
[eTORO PROPOSAL - Phase 3: Implementation (Optional)]

Implementation bridges the gap between brand system and market presence. We ensure the new brand identity is actively deployed across all touchpoints.

This phase also establishes three specialized AI + human content production studios:

Process:
• Website/landing page brand application
• Campaign asset creation
• Internal tools and templates
• Studio 1: Human photography (Weavy integration)
• Studio 2: Screen/product imagery
• Studio 3: Motion design

Deliverables:
• Landing page templates (branded)
• Campaign asset library
• Internal presentation templates
• Human photography production pipeline
• Screen capture and product shot pipeline
• Motion design production pipeline
• Quality control workflows
• Team training and documentation
"""
    },
    {
        "name": "Stage 4",
        "search_after": "require a separate SOW.",
        "content": """
[eTORO PROPOSAL - Phase 4: Scale - Campaign Machine & Automation]

The final phase transforms eToro's brand operations into a creative machine. We architect systems that generate campaigns, landing pages, and sales materials at scale.

Process:
• Campaign template architecture
• AI-powered asset generation
• A/B testing integration
• Landing page → conversion flow
• CRM/analytics integration
• Team training on all systems

Deliverables:
• Campaign brief → asset pipeline
• Landing page generation system
• Multi-variant creative generation
• Performance tracking dashboard
• Optimization recommendation engine
• Complete system documentation
• Training materials and videos
"""
    },
    {
        "name": "Pricing",
        "search_after": "delivery of brand book",
        "content": """
[eTORO PRICING PROPOSAL]

Option A: Full Transformation (Phases 1-4)
Total Project Cost: $[TBD]

Option B: Core Rebrand (Phases 1-2)
Total Project Cost: $[TBD]

Option C: Phased Approach
• Phase 1: $[TBD] - Onboarding & Discovery
• Phase 2: $[TBD] - Rebrand & Brand System  
• Phase 3: $[TBD] - Implementation (Optional)
• Phase 4: $[TBD] - Scale (Optional)

Payment Terms:
• [X]% due upon signing
• [X]% due upon Phase 1 completion
• [X]% due upon brand book delivery
• [X]% due upon final delivery
"""
    },
]

async def find_and_insert(page, search_text, content, section_name):
    """Find text and insert content after it in blue."""
    print(f"  Finding: '{search_text[:40]}...'")
    
    # Use Ctrl+F to find
    await page.keyboard.press('Control+f')
    await page.wait_for_timeout(500)
    
    # Type search text
    await page.keyboard.type(search_text[:50], delay=10)
    await page.wait_for_timeout(1000)
    
    # Press Enter to find
    await page.keyboard.press('Enter')
    await page.wait_for_timeout(500)
    
    # Close find dialog
    await page.keyboard.press('Escape')
    await page.wait_for_timeout(300)
    
    # Move to end of found text
    await page.keyboard.press('End')
    await page.wait_for_timeout(200)
    
    # Add newlines
    await page.keyboard.press('Enter')
    await page.keyboard.press('Enter')
    await page.wait_for_timeout(200)
    
    # Now type the content
    print(f"  Inserting {section_name} content...")
    lines = content.strip().split('\n')
    for line in lines:
        await page.keyboard.type(line, delay=3)
        await page.keyboard.press('Enter')
    
    await page.wait_for_timeout(500)
    print(f"  ✓ {section_name} inserted")

async def main():
    print("Starting inline edit...")
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page(viewport={'width': 1920, 'height': 1080})
        
        print("Opening doc...")
        await page.goto(DOC_URL, timeout=30000)
        await page.wait_for_timeout(8000)
        
        # Click to focus
        await page.click('.kix-appview-editor', timeout=10000)
        await page.wait_for_timeout(1000)
        
        # First, delete the content we added earlier
        print("Cleaning up previous content...")
        await page.keyboard.press('Control+End')
        await page.wait_for_timeout(500)
        
        # Select backwards to find and delete our previous addition
        # Use Find to locate our marker
        await page.keyboard.press('Control+f')
        await page.wait_for_timeout(500)
        await page.keyboard.type('eTORO PROPOSAL', delay=10)
        await page.wait_for_timeout(500)
        await page.keyboard.press('Escape')
        await page.wait_for_timeout(300)
        
        # If found, select from there to end and delete
        await page.keyboard.press('Control+Shift+End')
        await page.keyboard.press('Backspace')
        await page.wait_for_timeout(500)
        
        # Go back to top
        await page.keyboard.press('Control+Home')
        await page.wait_for_timeout(500)
        
        # Now insert each section
        print("\nInserting sections...")
        for section in SECTIONS:
            print(f"\n[{section['name']}]")
            await find_and_insert(page, section['search_after'], section['content'], section['name'])
            await page.wait_for_timeout(1000)
        
        print("\nWaiting for save...")
        await page.wait_for_timeout(5000)
        
        print("Taking screenshot...")
        await page.screenshot(path='/home/clawd/workspace/etoro/inline_result.png')
        
        # Scroll to show some content
        await page.keyboard.press('Control+Home')
        await page.wait_for_timeout(1000)
        await page.screenshot(path='/home/clawd/workspace/etoro/inline_top.png')
        
        await browser.close()
        print("\nDone!")

asyncio.run(main())
