#!/usr/bin/env python3
"""
Zapier MCP Setup v3 - Login properly then get MCP URL
"""

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

EMAIL = 'kinan@agileadapt.com'
PASSWORD = 'Systema55'

SCREENSHOT_DIR = '/mnt/e/genesis-system/scripts'

def ss(page, name):
    path = f'{SCREENSHOT_DIR}/zv3_{name}.png'
    page.screenshot(path=path)
    print(f"  [screenshot] {path}")

def run():
    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=False,
            slow_mo=100,
            args=['--no-sandbox', '--start-maximized', '--disable-blink-features=AutomationControlled']
        )

        context = browser.new_context(
            viewport={'width': 1366, 'height': 900},
            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',
            locale='en-AU',
        )
        context.set_extra_http_headers({
            'Accept-Language': 'en-AU,en;q=0.9',
        })

        page = context.new_page()

        # ============================================================
        # STEP 1: Login to Zapier
        # ============================================================
        print("\n=== STEP 1: Login ===")
        page.goto('https://zapier.com/app/login', wait_until='domcontentloaded', timeout=30000)
        time.sleep(2)
        print(f"URL: {page.url}")
        ss(page, '01_login_page')

        # Look for Google login button
        print("Looking for Google login button...")
        google_clicked = False

        # First check for email input (direct login form)
        for email_sel in ['input[type="email"]', 'input[name="email"]', '#username']:
            try:
                inp = page.locator(email_sel).first
                if inp.is_visible(timeout=2000):
                    print(f"Found email input: {email_sel}")
                    inp.fill(EMAIL)
                    time.sleep(1)

                    # Look for continue button
                    for cont_sel in ['button[type="submit"]', 'text=Continue', 'text=Log in', 'text=Sign in']:
                        try:
                            btn = page.locator(cont_sel).first
                            if btn.is_visible(timeout=1000):
                                btn.click()
                                time.sleep(3)
                                break
                        except:
                            continue

                    ss(page, '02_after_email')
                    print(f"After email URL: {page.url}")

                    # Check for password
                    for pass_sel in ['input[type="password"]', 'input[name="password"]']:
                        try:
                            pinp = page.locator(pass_sel).first
                            if pinp.is_visible(timeout=5000):
                                print(f"Found password input: {pass_sel}")
                                pinp.fill(PASSWORD)
                                time.sleep(1)
                                pinp.press('Enter')
                                time.sleep(5)
                                break
                        except:
                            continue

                    ss(page, '03_after_password')
                    print(f"After password URL: {page.url}")
                    break
            except:
                continue

        # Check if logged in (should redirect to dashboard)
        time.sleep(3)
        current_url = page.url
        print(f"Post-login URL: {current_url}")
        ss(page, '04_post_login')

        # If still on login page, try Google OAuth
        if 'login' in current_url.lower() or 'app/login' in current_url.lower():
            print("Still on login page. Trying Google OAuth...")

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

            for sel in google_selectors:
                try:
                    btn = page.locator(sel).first
                    if btn.is_visible(timeout=3000):
                        print(f"Clicking Google: {sel}")
                        with context.expect_page() as popup_info:
                            btn.click()
                        popup = popup_info.value
                        popup.wait_for_load_state('domcontentloaded')
                        time.sleep(2)
                        print(f"Popup URL: {popup.url}")
                        ss(popup, '05_google_popup')

                        # Handle Google auth in popup
                        handle_google_oauth(popup)
                        google_clicked = True

                        # Wait for popup to close and main page to update
                        try:
                            popup.wait_for_event('close', timeout=30000)
                        except:
                            pass
                        time.sleep(3)
                        print(f"After Google OAuth URL: {page.url}")
                        break
                except Exception as e:
                    print(f"  Error with {sel}: {e}")
                    continue

            if not google_clicked:
                # Try clicking without popup expectation
                for sel in ['text=Continue with Google', 'text=Google']:
                    try:
                        btn = page.locator(sel).first
                        if btn.is_visible(timeout=2000):
                            btn.click()
                            time.sleep(4)
                            print(f"After Google click URL: {page.url}")
                            if 'accounts.google.com' in page.url:
                                handle_google_oauth(page)
                            break
                    except:
                        continue

        time.sleep(3)
        ss(page, '06_settled')
        print(f"Settled URL: {page.url}")

        # Check if login was successful
        if 'dashboard' in page.url or 'app/' in page.url and 'login' not in page.url:
            print("LOGIN SUCCESSFUL!")
        else:
            print(f"Login may have failed. Current URL: {page.url}")
            # Try to continue anyway

        # ============================================================
        # STEP 2: Navigate to MCP settings / create MCP server
        # ============================================================
        print("\n=== STEP 2: Navigate to MCP ===")

        # Try mcp.zapier.com first (new interface)
        mcp_url_result = None

        # Try the new Zapier MCP interface
        targets = [
            'https://mcp.zapier.com',
            'https://actions.zapier.com/settings/mcp/',
            'https://actions.zapier.com/mcp/',
        ]

        for target in targets:
            try:
                print(f"\nTrying: {target}")
                page.goto(target, wait_until='domcontentloaded', timeout=20000)
                time.sleep(4)
                print(f"Arrived at: {page.url}")
                ss(page, f'07_mcp_target_{target.replace("https://","").replace("/","_")[:30]}')

                # Save HTML
                content = page.content()
                fname = f'{SCREENSHOT_DIR}/zv3_page_{target.replace("https://","").replace("/","_")[:30]}.html'
                with open(fname, 'w', encoding='utf-8') as f:
                    f.write(content)

                # Check if we got redirected to login
                if 'login' in page.url.lower():
                    print("  Redirected to login - not authenticated")
                    continue

                # Look for MCP URL patterns in content
                mcp_urls = find_mcp_urls(content, page.url)
                if mcp_urls:
                    print(f"  Found MCP URLs: {mcp_urls}")
                    mcp_url_result = mcp_urls[0]

                # Look for page elements
                print("  Page title:", page.title())

                # Dump buttons and links
                try:
                    buttons = page.eval_on_selector_all('button, [role="button"], a',
                        'els => els.map(e => ({tag: e.tagName, text: e.textContent.trim().substring(0, 80), href: e.href || ""}))')
                    relevant = [b for b in buttons if b['text'] and len(b['text']) > 1]
                    print("  Buttons/Links:")
                    for b in relevant[:25]:
                        print(f"    [{b['tag']}] {b['text'][:60]:60s} -> {b['href'][:60]}")
                except:
                    pass

                if mcp_url_result:
                    break

            except Exception as e:
                print(f"  Error: {e}")
                continue

        # ============================================================
        # STEP 3: Create MCP server if not found yet
        # ============================================================
        if not mcp_url_result:
            print("\n=== STEP 3: Create MCP Server ===")

            # Look for "New server" or "Create" button
            create_selectors = [
                'text=New server',
                'text=Create server',
                'text=New MCP server',
                'text=Create new',
                'text=Get started',
                'text=Create',
                'button:has-text("New")',
                '[data-testid*="create"]',
                '[data-testid*="new"]',
            ]

            for sel in create_selectors:
                try:
                    btn = page.locator(sel).first
                    if btn.is_visible(timeout=2000):
                        print(f"  Clicking: {sel}")
                        btn.click()
                        time.sleep(3)
                        print(f"  After create URL: {page.url}")
                        ss(page, '08_after_create')

                        # Check for MCP URL
                        content = page.content()
                        mcp_urls = find_mcp_urls(content, page.url)
                        if mcp_urls:
                            mcp_url_result = mcp_urls[0]
                            break
                except:
                    continue

        # ============================================================
        # STEP 4: Add actions if on MCP page
        # ============================================================
        if not mcp_url_result and 'mcp' in page.url.lower():
            print("\n=== STEP 4: Add Actions ===")
            ss(page, '09_mcp_page_for_actions')

            actions_to_find = ['Gmail', 'Google Calendar', 'Google Sheets', 'Slack']
            for action_app in actions_to_find:
                try:
                    # Search for app
                    search_inputs = page.locator('input[type="search"], input[placeholder*="search" i], input[placeholder*="find" i]').all()
                    for inp in search_inputs:
                        if inp.is_visible():
                            inp.fill(action_app)
                            time.sleep(2)
                            # Click first result
                            result = page.locator(f'text={action_app}').nth(1)
                            if result.is_visible(timeout=2000):
                                result.click()
                                time.sleep(1)
                            inp.fill('')
                            break
                except Exception as e:
                    print(f"  Could not add {action_app}: {e}")

            time.sleep(2)
            content = page.content()
            mcp_urls = find_mcp_urls(content, page.url)
            if mcp_urls:
                mcp_url_result = mcp_urls[0]

        # ============================================================
        # STEP 5: Look for "Connect" tab and MCP URL
        # ============================================================
        print("\n=== STEP 5: Looking for Connect tab / MCP URL ===")

        connect_selectors = [
            'text=Connect',
            '[role="tab"]:has-text("Connect")',
            'text=Copy URL',
            'text=MCP URL',
            'text=Server URL',
        ]

        for sel in connect_selectors:
            try:
                el = page.locator(sel).first
                if el.is_visible(timeout=2000):
                    print(f"  Clicking Connect tab: {sel}")
                    el.click()
                    time.sleep(2)
                    content = page.content()
                    mcp_urls = find_mcp_urls(content, page.url)
                    if mcp_urls:
                        mcp_url_result = mcp_urls[0]
                        break
            except:
                continue

        # Final screenshot and HTML save
        ss(page, '99_final')
        final_content = page.content()
        with open(f'{SCREENSHOT_DIR}/zv3_final.html', 'w', encoding='utf-8') as f:
            f.write(final_content)

        # One last search
        if not mcp_url_result:
            mcp_urls = find_mcp_urls(final_content, page.url)
            if mcp_urls:
                mcp_url_result = mcp_urls[0]

        browser.close()
        return mcp_url_result


def find_mcp_urls(content, current_url=''):
    """Find all Zapier MCP URLs in page content"""
    patterns = [
        r'https://actions\.zapier\.com/mcp/[a-zA-Z0-9/_?=&.-]+',
        r'https://mcp\.zapier\.com/mcp/[a-zA-Z0-9/_?=&.-]+',
        r'https://[^"\'<>\s]*zapier[^"\'<>\s]*/mcp/[a-zA-Z0-9/_?=&.-]+',
    ]

    found = []
    for pattern in patterns:
        matches = re.findall(pattern, content)
        found.extend(matches)

    # Filter out generic/list endpoints
    filtered = []
    for url in found:
        # Skip if it ends in /servers or is just the list URL
        if url.endswith('/servers') or url == 'https://mcp.zapier.com/mcp/servers':
            continue
        # Keep personalized URLs (contain hash/token)
        filtered.append(url)

    # Also search in current URL
    if current_url and 'mcp' in current_url:
        for pattern in patterns:
            if re.match(pattern, current_url):
                filtered.append(current_url)

    return list(dict.fromkeys(filtered))  # deduplicate


def handle_google_oauth(page):
    """Handle Google OAuth steps"""
    import time
    time.sleep(2)

    print(f"  Google OAuth URL: {page.url}")
    ss(page, 'google_01')

    # Enter email
    for sel in ['input[type="email"]', '#identifierId', 'input[name="identifier"]']:
        try:
            inp = page.locator(sel).first
            if inp.is_visible(timeout=5000):
                print(f"  Filling email in: {sel}")
                inp.fill(EMAIL)
                time.sleep(0.5)
                # Click Next
                for next_sel in ['#identifierNext', 'text=Next', 'button:has-text("Next")']:
                    try:
                        next_btn = page.locator(next_sel).first
                        if next_btn.is_visible(timeout=1000):
                            next_btn.click()
                            break
                    except:
                        page.keyboard.press('Enter')
                        break
                time.sleep(3)
                break
        except:
            continue

    ss(page, 'google_02')
    print(f"  After email URL: {page.url}")

    # Enter password
    for sel in ['input[type="password"]', 'input[name="Passwd"]']:
        try:
            inp = page.locator(sel).first
            if inp.is_visible(timeout=8000):
                print(f"  Filling password in: {sel}")
                inp.fill(PASSWORD)
                time.sleep(0.5)
                for next_sel in ['#passwordNext', 'text=Next', 'button:has-text("Next")']:
                    try:
                        next_btn = page.locator(next_sel).first
                        if next_btn.is_visible(timeout=1000):
                            next_btn.click()
                            break
                    except:
                        page.keyboard.press('Enter')
                        break
                time.sleep(5)
                break
        except Exception as e:
            print(f"  Password error: {e}")

    ss(page, 'google_03')
    print(f"  After password URL: {page.url}")

    # Handle any additional prompts (2FA warning, choose account, etc.)
    time.sleep(3)
    ss(page, 'google_04')
    print(f"  Final Google URL: {page.url}")


if __name__ == '__main__':
    result = run()
    if result:
        print(f"\n{'='*60}")
        print(f"ZAPIER MCP URL: {result}")
        print(f"{'='*60}")
        with open(f'{SCREENSHOT_DIR}/zapier_mcp_url.txt', 'w') as f:
            f.write(result)
        print(f"Saved to: {SCREENSHOT_DIR}/zapier_mcp_url.txt")
    else:
        print("\n[RESULT] No MCP URL found automatically.")
        print("Review screenshots and HTML in:", SCREENSHOT_DIR)
