#!/usr/bin/env python3
"""
Zapier MCP Setup v4 - Click Google button properly, handle OAuth, get MCP URL
"""

import time
import re
import sys
from playwright.sync_api import sync_playwright

EMAIL = 'kinan@agileadapt.com'
PASSWORD = 'Systema55'
SCREENSHOT_DIR = '/mnt/e/genesis-system/scripts'


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


def find_mcp_urls(content):
    patterns = [
        r'https://actions\.zapier\.com/mcp/[a-zA-Z0-9/_?=&.-]+',
        r'https://mcp\.zapier\.com/mcp/[a-zA-Z0-9/_?=&.-]+(?<!servers)(?<!servers/)',
    ]
    found = []
    for pattern in patterns:
        matches = re.findall(pattern, content)
        found.extend(matches)
    filtered = [u for u in found if '/servers' not in u]
    return list(dict.fromkeys(filtered))


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

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

        page = context.new_page()

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

        # Click "Continue with Google" button (the big blue button at top)
        print("Clicking 'Continue with Google'...")
        google_btn = page.locator('text=Continue with Google').first
        google_btn.wait_for(state='visible', timeout=10000)
        print(f"  Google button found, clicking...")

        # Use expect_popup to handle if it opens in a new window
        # Or it may navigate in same tab
        try:
            with context.expect_page(timeout=5000) as popup_info:
                google_btn.click()
            popup = popup_info.value
            popup.wait_for_load_state('domcontentloaded', timeout=15000)
            print(f"  Popup opened: {popup.url}")
            ss(popup, '02_google_popup')
            google_oauth_flow(popup)
            # Wait for popup to close
            try:
                popup.wait_for_event('close', timeout=60000)
                print("  Google popup closed")
            except:
                print("  Popup timeout, checking if closed...")
            time.sleep(3)
        except Exception as e:
            print(f"  No popup: {e}")
            # Same page navigation
            time.sleep(3)
            print(f"  Current page: {page.url}")
            ss(page, '02_after_google_click')
            if 'accounts.google.com' in page.url or 'google.com' in page.url:
                print("  On Google OAuth page (same tab)")
                google_oauth_flow(page)
            else:
                print(f"  Unexpected URL: {page.url}")

        # ============================================================
        # STEP 2: Check login status
        # ============================================================
        time.sleep(5)
        print(f"\n=== STEP 2: Post-login URL: {page.url} ===")
        ss(page, '03_post_login')

        # If still on login or Google, we may need to complete 2FA manually
        # or the account chooser appeared
        if 'login' in page.url or 'accounts.google.com' in page.url:
            print("  Still on auth page. Waiting 15s for manual intervention...")
            time.sleep(15)
            print(f"  After wait URL: {page.url}")
            ss(page, '03b_after_wait')

        # ============================================================
        # STEP 3: Navigate to mcp.zapier.com
        # ============================================================
        print(f"\n=== STEP 3: Navigating to mcp.zapier.com ===")
        page.goto('https://mcp.zapier.com', wait_until='domcontentloaded', timeout=30000)
        time.sleep(4)
        print(f"URL: {page.url}")
        ss(page, '04_mcp_zapier')

        # Check if we're redirected to login again
        if 'login' in page.url.lower():
            print("  Redirected to login - trying email/password route...")
            # Try email+password directly
            try_email_password_login(page, context)

            # After login, navigate to MCP again
            page.goto('https://mcp.zapier.com', wait_until='domcontentloaded', timeout=30000)
            time.sleep(4)
            print(f"After re-login MCP URL: {page.url}")
            ss(page, '04b_mcp_after_relogin')

        # ============================================================
        # STEP 4: Inspect the MCP page
        # ============================================================
        print("\n=== STEP 4: Inspecting MCP page ===")
        content = page.content()
        with open(f'{SCREENSHOT_DIR}/zv4_mcp_page.html', 'w', encoding='utf-8') as f:
            f.write(content)

        print(f"Page title: {page.title()}")

        # Look for MCP URL already there
        mcp_urls = find_mcp_urls(content)
        if mcp_urls:
            print(f"Found MCP URLs: {mcp_urls}")
            return mcp_urls[0]

        # Dump page elements
        try:
            elements = page.eval_on_selector_all('button, [role="button"], a, input',
                'els => els.map(e => ({tag: e.tagName, text: e.textContent.trim().substring(0,80), href: e.href||"", type: e.type||""}))')
            print("Page elements:")
            for el in elements[:40]:
                if el['text'] or el['href']:
                    print(f"  [{el['tag']}:{el['type']}] {el['text'][:60]:60s} | {el['href'][:50]}")
        except Exception as e:
            print(f"  Error dumping elements: {e}")

        # ============================================================
        # STEP 5: Try to create/find MCP server
        # ============================================================
        print("\n=== STEP 5: Finding/Creating MCP Server ===")

        # Look for "New server" button
        for sel in [
            'text=New server',
            'text=Create server',
            'text=New MCP',
            'button:has-text("New")',
            'button:has-text("Create")',
            'text=Get started',
            '[data-testid*="create"]',
            '[data-testid*="new-server"]',
        ]:
            try:
                btn = page.locator(sel).first
                if btn.is_visible(timeout=2000):
                    print(f"  Clicking: {sel}")
                    btn.click()
                    time.sleep(3)
                    print(f"  After click URL: {page.url}")
                    ss(page, '05_after_create')
                    content = page.content()
                    mcp_urls = find_mcp_urls(content)
                    if mcp_urls:
                        return mcp_urls[0]
                    break
            except:
                continue

        # ============================================================
        # STEP 6: Look for Connect tab and copy MCP URL
        # ============================================================
        print("\n=== STEP 6: Looking for MCP URL in tabs ===")
        ss(page, '06_pre_connect')

        for tab_sel in [
            'text=Connect',
            '[role="tab"]:has-text("Connect")',
            'text=MCP URL',
            'text=Connection',
            'text=Setup',
        ]:
            try:
                tab = page.locator(tab_sel).first
                if tab.is_visible(timeout=2000):
                    print(f"  Clicking tab: {tab_sel}")
                    tab.click()
                    time.sleep(2)
                    ss(page, '06_connect_tab')
                    content = page.content()
                    mcp_urls = find_mcp_urls(content)
                    if mcp_urls:
                        return mcp_urls[0]
            except:
                continue

        # Look for text elements containing the URL
        try:
            code_elements = page.eval_on_selector_all(
                'code, pre, [class*="code"], [class*="url"], [class*="copy"]',
                'els => els.map(e => e.textContent.trim())'
            )
            for ce in code_elements:
                if 'zapier' in ce.lower() and 'mcp' in ce.lower():
                    print(f"  Code element: {ce[:300]}")
                    mcp_match = re.search(r'https://[^"\s<>]+mcp[^"\s<>]+', ce)
                    if mcp_match:
                        return mcp_match.group()
        except:
            pass

        # ============================================================
        # STEP 7: Try actions.zapier.com with auth
        # ============================================================
        print("\n=== STEP 7: Trying actions.zapier.com ===")

        # Navigate to get a Zapier NLA (Natural Language Actions) API key
        for url in [
            'https://actions.zapier.com/settings/mcp/',
            'https://actions.zapier.com/api/v2/configuration/',
        ]:
            try:
                print(f"  Trying: {url}")
                page.goto(url, wait_until='domcontentloaded', timeout=15000)
                time.sleep(3)
                print(f"  URL: {page.url}")
                ss(page, f'07_{url[-20:].replace("/","_")}')

                if 'login' not in page.url.lower():
                    content = page.content()
                    with open(f'{SCREENSHOT_DIR}/zv4_actions_{url[-20:].replace("/","_")}.html', 'w', encoding='utf-8') as f:
                        f.write(content)
                    mcp_urls = find_mcp_urls(content)
                    if mcp_urls:
                        return mcp_urls[0]

                    # Print content for inspection
                    print(f"  Title: {page.title()}")
                    text_content = page.inner_text('body')[:500]
                    print(f"  Body: {text_content}")
            except Exception as e:
                print(f"  Error: {e}")

        # Final check
        ss(page, '99_final')
        content = page.content()
        all_mcp = find_mcp_urls(content)
        if all_mcp:
            return all_mcp[0]

        browser.close()
        return None


def google_oauth_flow(page):
    """Complete Google OAuth on the given page"""
    time.sleep(2)
    print(f"  [Google] URL: {page.url}")
    ss(page, 'google_01')

    # Enter email
    email_entered = False
    for sel in ['input[type="email"]', '#identifierId', 'input[name="identifier"]']:
        try:
            inp = page.locator(sel).first
            if inp.is_visible(timeout=5000):
                print(f"  [Google] Filling email in: {sel}")
                inp.click()
                time.sleep(0.5)
                inp.fill(EMAIL)
                time.sleep(0.5)
                ss(page, 'google_email_filled')

                # Click Next button
                for next_sel in ['#identifierNext', 'button:has-text("Next")', 'text=Next']:
                    try:
                        next_btn = page.locator(next_sel).first
                        if next_btn.is_visible(timeout=2000):
                            next_btn.click()
                            email_entered = True
                            break
                    except:
                        pass

                if not email_entered:
                    page.keyboard.press('Enter')
                    email_entered = True

                time.sleep(3)
                break
        except Exception as e:
            print(f"  [Google] Email error with {sel}: {e}")

    if not email_entered:
        print("  [Google] Could not enter email!")
        return

    ss(page, 'google_02_after_email')
    print(f"  [Google] 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=10000):
                print(f"  [Google] Filling password in: {sel}")
                inp.click()
                time.sleep(0.3)
                inp.fill(PASSWORD)
                time.sleep(0.5)
                ss(page, 'google_password_filled')

                for next_sel in ['#passwordNext', 'button:has-text("Next")', 'text=Next']:
                    try:
                        next_btn = page.locator(next_sel).first
                        if next_btn.is_visible(timeout=2000):
                            next_btn.click()
                            break
                    except:
                        pass
                else:
                    page.keyboard.press('Enter')

                time.sleep(5)
                break
        except Exception as e:
            print(f"  [Google] Password error with {sel}: {e}")

    ss(page, 'google_03_after_password')
    print(f"  [Google] After password URL: {page.url}")

    # Handle any 2FA or account selection prompts
    time.sleep(3)

    # If there's a "2-Step Verification" or similar
    page_text = ''
    try:
        page_text = page.inner_text('body')[:500]
    except:
        pass

    if '2-step' in page_text.lower() or '2fa' in page_text.lower() or 'verification' in page_text.lower():
        print("  [Google] 2FA prompt detected! Waiting 30s for manual handling...")
        time.sleep(30)
    elif 'choose an account' in page_text.lower():
        print("  [Google] Account chooser - selecting first account...")
        try:
            first_account = page.locator('[data-identifier]').first
            if first_account.is_visible():
                first_account.click()
                time.sleep(3)
        except:
            pass

    ss(page, 'google_04_final')
    print(f"  [Google] Final URL: {page.url}")


def try_email_password_login(page, context):
    """Try Zapier direct email/password login"""
    print("  [Fallback] Trying email/password Zapier login...")

    # The login page should be showing
    # Look for the email field (NOT the Google button)
    try:
        # Find the email field below the social buttons
        email_inp = page.locator('input[type="email"], input[name="email"]').first
        if email_inp.is_visible(timeout=5000):
            email_inp.fill(EMAIL)
            time.sleep(0.5)
            # Click Continue
            cont = page.locator('text=Continue').first
            if cont.is_visible(timeout=2000):
                cont.click()
                time.sleep(3)

            # Password
            pass_inp = page.locator('input[type="password"]').first
            if pass_inp.is_visible(timeout=8000):
                pass_inp.fill(PASSWORD)
                pass_inp.press('Enter')
                time.sleep(5)
    except Exception as e:
        print(f"  [Fallback] Error: {e}")


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(f"Review screenshots in: {SCREENSHOT_DIR}")
