#!/usr/bin/env python3
import asyncio
from playwright.async_api import async_playwright
import os

async def signup_mailchimp():
    async with async_playwright() as p:
        # Connect to existing Chrome instance
        browser = await p.chromium.connect_over_cdp("http://127.0.0.1:18800")
        
        # Get the page
        context = browser.contexts[0]
        pages = context.pages
        page = None
        for p in pages:
            if 'mailchimp.com/signup' in p.url:
                page = p
                break
        
        if not page:
            print("Could not find Mailchimp signup page")
            await browser.close()
            return False
            
        print(f"Found page: {page.url}")
        
        # Dismiss cookie banner
        try:
            await page.wait_for_selector('button:has-text("Dismiss")', timeout=5000)
            await page.click('button:has-text("Dismiss")')
            print("Dismissed cookie banner")
            await asyncio.sleep(1)
        except:
            print("No cookie banner or already dismissed")
        
        # Fill out the form
        email = "jake@burtonmethod.com"
        password = "Mailchimp2026!Secure"
        
        # Fill email field
        await page.fill('input[name="email"]', email)
        print(f"Filled email: {email}")
        await asyncio.sleep(0.5)
        
        # Fill username field (use email as username)
        await page.fill('input[name="username"]', email)
        print(f"Filled username: {email}")
        await asyncio.sleep(0.5)
        
        # Fill password field
        await page.fill('input[name="new_password"]', password)
        print(f"Filled password")
        await asyncio.sleep(0.5)
        
        # Click Sign up button
        await page.click('button:has-text("Sign up")')
        print("Clicked Sign up button")
        
        # Wait for navigation or error
        try:
            await page.wait_for_load_state('networkidle', timeout=30000)
            print(f"Navigated to: {page.url}")
            
            # Take screenshot of result
            await page.screenshot(path='/Users/jakeshore/.clawdbot/workspace/signup_result.png')
            print("Screenshot saved")
            
            return True
        except Exception as e:
            print(f"Error after signup: {e}")
            await page.screenshot(path='/Users/jakeshore/.clawdbot/workspace/signup_error.png')
            return False
        
        await browser.close()

if __name__ == "__main__":
    result = asyncio.run(signup_mailchimp())
    if result:
        print("Signup completed successfully")
    else:
        print("Signup failed")
