#!/usr/bin/env python3
"""
Zapier MCP Setup Automation
Navigates to zapier.com/mcp, logs in with Google, creates MCP server with actions,
and returns the MCP URL.
"""

import time
import sys
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError

def zapier_mcp_setup():
    with sync_playwright() as p:
        # Launch browser - non-headless to see what's happening and handle any auth
        browser = p.chromium.launch(
            headless=False,
            args=[
                '--no-sandbox',
                '--disable-blink-features=AutomationControlled',
                '--disable-infobars',
                '--start-maximized',
            ]
        )

        context = browser.new_context(
            viewport={'width': 1366, 'height': 768},
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
        )

        page = context.new_page()

        try:
            print("[1] Navigating to zapier.com/mcp...")
            page.goto('https://zapier.com/mcp', wait_until='domcontentloaded', timeout=30000)
            time.sleep(3)

            print(f"[1] Current URL: {page.url}")
            print(f"[1] Page title: {page.title()}")

            # Take screenshot
            page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_step1.png')
            print("[1] Screenshot saved: zapier_step1.png")

            # Check if we're already on an MCP page or need to log in
            current_url = page.url
            page_content = page.content()

            # Look for login/signup buttons
            if 'login' in current_url.lower() or 'sign' in current_url.lower():
                print("[2] On login page, proceeding with Google login...")
                handle_login(page)
            elif 'zapier.com/mcp' in current_url or 'actions.zapier.com' in current_url:
                print("[2] Already on MCP page or redirected to MCP endpoint")
                # Check if there's a "Get started" or "Create" button
                check_for_mcp_actions(page)
            else:
                # Try to find login or CTA button
                print(f"[2] Unexpected URL: {current_url}, looking for login/CTA...")

                # Try clicking "Log in" or "Sign up" or "Get started"
                for selector in [
                    'text=Log in',
                    'text=Sign in',
                    'text=Sign up',
                    'text=Get started',
                    '[data-testid="login-button"]',
                    'a[href*="login"]',
                    'a[href*="sign-in"]',
                ]:
                    try:
                        btn = page.locator(selector).first
                        if btn.is_visible(timeout=2000):
                            print(f"[2] Found button: {selector}, clicking...")
                            btn.click()
                            time.sleep(2)
                            break
                    except:
                        continue

                page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_step2.png')
                print(f"[2] After button click URL: {page.url}")
                print("[2] Screenshot saved: zapier_step2.png")

                handle_login(page)

            # After login, navigate to MCP page
            time.sleep(3)
            print(f"[3] Post-login URL: {page.url}")
            page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_step3.png')

            # Check if we ended up on MCP or need to navigate there
            if 'mcp' not in page.url.lower():
                print("[3] Navigating to MCP page after login...")
                page.goto('https://zapier.com/mcp', wait_until='domcontentloaded', timeout=30000)
                time.sleep(3)
                print(f"[3] MCP page URL: {page.url}")
                page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_step3b.png')

            # Now look for the MCP URL or "Create" button
            result_url = check_for_mcp_url(page)

            if result_url:
                print(f"\n[SUCCESS] Found MCP URL: {result_url}")
                return result_url

            # Try to create a new MCP server
            print("[4] Looking for create/setup MCP button...")
            result_url = create_mcp_server(page)

            if result_url:
                print(f"\n[SUCCESS] MCP URL after creation: {result_url}")
                return result_url

            print("[FINAL] Checking page content for any MCP URL...")
            # Last resort: search page source for MCP URL pattern
            content = page.content()
            import re
            mcp_urls = re.findall(r'https://actions\.zapier\.com/mcp/[^\s\'"<>]+', content)
            if mcp_urls:
                print(f"[FINAL] Found MCP URLs in page source: {mcp_urls}")
                return mcp_urls[0]

            print("[FINAL] No MCP URL found. Current page URL:", page.url)
            page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_final.png')
            return None

        except Exception as e:
            print(f"[ERROR] {e}")
            page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_error.png')
            raise
        finally:
            time.sleep(5)
            browser.close()


def handle_login(page):
    """Handle Zapier login via Google OAuth"""
    import time

    current_url = page.url
    print(f"[LOGIN] Starting login flow from: {current_url}")

    # If not on login page, navigate there
    if 'login' not in current_url.lower() and 'sign' not in current_url.lower():
        page.goto('https://zapier.com/app/login', wait_until='domcontentloaded', timeout=30000)
        time.sleep(3)

    page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_login.png')
    print(f"[LOGIN] Login page URL: {page.url}")

    # Look for Google sign-in button
    google_selectors = [
        'text=Continue with Google',
        'text=Sign in with Google',
        'text=Log in with Google',
        '[data-provider="google"]',
        'button:has-text("Google")',
        'a:has-text("Google")',
        '[aria-label*="Google"]',
    ]

    google_clicked = False
    for selector in google_selectors:
        try:
            btn = page.locator(selector).first
            if btn.is_visible(timeout=3000):
                print(f"[LOGIN] Clicking Google button: {selector}")
                btn.click()
                time.sleep(3)
                google_clicked = True
                break
        except:
            continue

    if not google_clicked:
        # Try email login instead
        print("[LOGIN] Google button not found, trying email login...")
        try_email_login(page)
        return

    # Handle Google OAuth popup/redirect
    page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_google_oauth.png')
    print(f"[LOGIN] After Google click URL: {page.url}")

    # Check if we're on Google's auth page
    if 'accounts.google.com' in page.url or 'google.com' in page.url:
        print("[LOGIN] On Google OAuth page, entering credentials...")
        handle_google_oauth(page)
    else:
        print(f"[LOGIN] Not on Google page, current URL: {page.url}")


def handle_google_oauth(page):
    """Handle Google OAuth authentication"""
    import time

    time.sleep(2)
    page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_google1.png')

    # Enter email
    email_selectors = [
        'input[type="email"]',
        '#identifierId',
        'input[name="identifier"]',
    ]

    for selector in email_selectors:
        try:
            inp = page.locator(selector).first
            if inp.is_visible(timeout=3000):
                print(f"[GOOGLE] Filling email with: {selector}")
                inp.fill('kinan@agileadapt.com')
                time.sleep(1)
                page.keyboard.press('Enter')
                time.sleep(3)
                break
        except:
            continue

    page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_google2.png')
    print(f"[GOOGLE] After email entry URL: {page.url}")

    # Enter password
    password_selectors = [
        'input[type="password"]',
        'input[name="password"]',
        '#password',
    ]

    for selector in password_selectors:
        try:
            inp = page.locator(selector).first
            if inp.is_visible(timeout=5000):
                print(f"[GOOGLE] Filling password with: {selector}")
                inp.fill('Systema55')
                time.sleep(1)
                page.keyboard.press('Enter')
                time.sleep(5)
                break
        except:
            continue

    page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_google3.png')
    print(f"[GOOGLE] After password entry URL: {page.url}")

    # Handle 2FA or account selection if needed
    time.sleep(3)
    page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_google4.png')
    print(f"[GOOGLE] Final Google auth URL: {page.url}")


def try_email_login(page):
    """Try email/password login directly"""
    import time

    print("[EMAIL LOGIN] Attempting email/password login...")

    email_selectors = [
        'input[type="email"]',
        'input[name="email"]',
        'input[placeholder*="email" i]',
        '#email',
    ]

    for selector in email_selectors:
        try:
            inp = page.locator(selector).first
            if inp.is_visible(timeout=3000):
                inp.fill('kinan@agileadapt.com')
                print(f"[EMAIL LOGIN] Filled email in: {selector}")
                break
        except:
            continue

    # Click next/continue
    for selector in ['text=Continue', 'text=Next', 'button[type="submit"]']:
        try:
            btn = page.locator(selector).first
            if btn.is_visible(timeout=2000):
                btn.click()
                time.sleep(2)
                break
        except:
            continue

    # Fill password
    for selector in ['input[type="password"]', 'input[name="password"]']:
        try:
            inp = page.locator(selector).first
            if inp.is_visible(timeout=5000):
                inp.fill('Systema55')
                print(f"[EMAIL LOGIN] Filled password in: {selector}")
                inp.press('Enter')
                time.sleep(3)
                break
        except:
            continue

    page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_email_login.png')
    print(f"[EMAIL LOGIN] After login URL: {page.url}")


def check_for_mcp_url(page):
    """Check page for existing MCP URL"""
    import re
    import time

    time.sleep(2)
    content = page.content()

    # Look for MCP URL patterns
    patterns = [
        r'https://actions\.zapier\.com/mcp/[a-zA-Z0-9/_-]+',
        r'https://[^/]*zapier[^/]*/mcp/[^\s\'"<>]+',
    ]

    for pattern in patterns:
        matches = re.findall(pattern, content)
        if matches:
            print(f"[URL CHECK] Found MCP URL: {matches[0]}")
            return matches[0]

    # Also check for text content with MCP URL
    try:
        mcp_elements = page.locator('text=/actions.zapier.com\/mcp/').all()
        for el in mcp_elements:
            text = el.inner_text()
            matches = re.findall(r'https://actions\.zapier\.com/mcp/[^\s]+', text)
            if matches:
                return matches[0]
    except:
        pass

    return None


def create_mcp_server(page):
    """Create a new MCP server and add actions"""
    import time
    import re

    print("[CREATE] Looking for MCP creation options...")
    page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_mcp_page.png')

    # Look for "Create" or "Get started" or "Add" buttons
    create_selectors = [
        'text=Create MCP Server',
        'text=Create new MCP',
        'text=New MCP',
        'text=Get started',
        'text=Add actions',
        'text=Create',
        'button:has-text("Create")',
        '[data-testid="create-mcp"]',
        'text=Set up MCP',
        'text=Configure MCP',
    ]

    for selector in create_selectors:
        try:
            btn = page.locator(selector).first
            if btn.is_visible(timeout=2000):
                print(f"[CREATE] Clicking: {selector}")
                btn.click()
                time.sleep(3)
                page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_after_create.png')
                print(f"[CREATE] After create click URL: {page.url}")
                break
        except:
            continue

    # Check for MCP URL after creation
    mcp_url = check_for_mcp_url(page)
    if mcp_url:
        return mcp_url

    # Try to add actions
    print("[CREATE] Looking for action search/add interface...")
    actions_to_add = [
        'Gmail: Send Email',
        'Gmail: Find Email',
        'Google Calendar: Create Event',
        'Google Calendar: Find Event',
        'Google Sheets: Find Row',
        'Google Sheets: Create Row',
        'Slack: Send Message',
    ]

    for action in actions_to_add:
        try:
            # Look for search box
            search_selectors = [
                'input[placeholder*="search" i]',
                'input[placeholder*="find" i]',
                'input[type="search"]',
                '[data-testid="action-search"]',
            ]

            for search_sel in search_selectors:
                try:
                    inp = page.locator(search_sel).first
                    if inp.is_visible(timeout=2000):
                        inp.fill(action.split(':')[0])  # Search by app name
                        time.sleep(2)
                        # Try to click the action
                        action_btn = page.locator(f'text={action}').first
                        if action_btn.is_visible(timeout=2000):
                            action_btn.click()
                            time.sleep(1)
                            print(f"[CREATE] Added action: {action}")
                        break
                except:
                    continue
        except Exception as e:
            print(f"[CREATE] Could not add action {action}: {e}")

    # Look for Connect tab
    for tab_sel in ['text=Connect', '[role="tab"]:has-text("Connect")', 'text=MCP URL']:
        try:
            tab = page.locator(tab_sel).first
            if tab.is_visible(timeout=2000):
                print(f"[CREATE] Clicking Connect tab: {tab_sel}")
                tab.click()
                time.sleep(2)
                mcp_url = check_for_mcp_url(page)
                if mcp_url:
                    return mcp_url
        except:
            continue

    # Final check - look for any copy button near MCP URL
    page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_final_check.png')
    content = page.content()
    mcp_patterns = re.findall(r'https://actions\.zapier\.com/mcp/[a-zA-Z0-9/_?=&-]+', content)
    if mcp_patterns:
        return mcp_patterns[0]

    return None


def check_for_mcp_actions(page):
    """Check if on MCP page and look for actions"""
    import time
    print("[MCP PAGE] On MCP page, checking for actions interface...")
    time.sleep(2)
    page.screenshot(path='/mnt/e/genesis-system/scripts/zapier_mcp_direct.png')


if __name__ == '__main__':
    result = zapier_mcp_setup()
    if result:
        print(f"\n{'='*60}")
        print(f"ZAPIER MCP URL: {result}")
        print(f"{'='*60}")
        # Save to file
        with open('/mnt/e/genesis-system/scripts/zapier_mcp_url.txt', 'w') as f:
            f.write(result)
        print("URL saved to: /mnt/e/genesis-system/scripts/zapier_mcp_url.txt")
    else:
        print("\n[FAILED] Could not retrieve MCP URL")
        sys.exit(1)
