#!/usr/bin/env python3
"""
Zapier MCP Setup v2 - Deep inspection + login + URL extraction
"""

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

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

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

        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'
        )

        page = context.new_page()

        # Step 1: Go to Zapier MCP page
        print("[1] Going to zapier.com/mcp...")
        page.goto('https://zapier.com/mcp', wait_until='networkidle', timeout=30000)
        time.sleep(2)
        print(f"    URL: {page.url}")
        print(f"    Title: {page.title()}")
        page.screenshot(path='/mnt/e/genesis-system/scripts/z_s1_mcp_page.png')

        # Dump all hrefs and text content to understand the page
        links = page.eval_on_selector_all('a', 'els => els.map(e => ({href: e.href, text: e.textContent.trim()}))')
        print("\n[1] Links on page:")
        for l in links[:30]:
            if l['href'] or l['text']:
                print(f"    {l['text'][:50]:50s} -> {l['href']}")

        buttons = page.eval_on_selector_all('button', 'els => els.map(e => e.textContent.trim())')
        print("\n[1] Buttons on page:")
        for b in buttons[:20]:
            if b:
                print(f"    [{b}]")

        # Step 2: Look for login/signup CTA
        print("\n[2] Looking for login or get-started button...")

        # Try to find and click "Get started" or "Log in" or similar
        cta_found = False
        cta_selectors = [
            ('text=Get started for free', True),
            ('text=Get started', True),
            ('text=Log in', False),
            ('text=Sign up', True),
            ('a[href*="login"]', False),
            ('a[href*="signup"]', True),
        ]

        for sel, is_signup in cta_selectors:
            try:
                el = page.locator(sel).first
                if el.is_visible(timeout=2000):
                    href = el.get_attribute('href') or ''
                    text = el.inner_text()
                    print(f"    Found: '{text}' -> {href}")
                    el.click()
                    time.sleep(3)
                    cta_found = True
                    print(f"    Clicked. Now at: {page.url}")
                    break
            except:
                continue

        if not cta_found:
            print("    No CTA found, navigating directly to login...")
            page.goto('https://zapier.com/app/login', wait_until='networkidle', timeout=30000)
            time.sleep(2)

        page.screenshot(path='/mnt/e/genesis-system/scripts/z_s2_after_cta.png')
        print(f"    URL after CTA: {page.url}")

        # Step 3: Handle login
        print("\n[3] Handling login flow...")

        # Check if we're on a Google auth page already
        if 'accounts.google.com' in page.url:
            print("    On Google OAuth, entering credentials...")
            google_login(page)
        elif 'zapier.com' in page.url:
            # Look for Google sign-in option
            print("    On Zapier, looking for Google login button...")

            google_btn_selectors = [
                'text=Continue with Google',
                'text=Sign in with Google',
                'text=Log in with Google',
                'button:has-text("Google")',
                '[data-provider="google"]',
                'a:has-text("Google")',
            ]

            google_found = False
            for sel in google_btn_selectors:
                try:
                    btn = page.locator(sel).first
                    if btn.is_visible(timeout=3000):
                        print(f"    Clicking Google button: {sel}")
                        btn.click()
                        time.sleep(4)
                        google_found = True
                        break
                except:
                    continue

            if not google_found:
                print("    Google button not found, dumping page buttons:")
                btns = page.eval_on_selector_all('button, [role="button"]', 'els => els.map(e => e.textContent.trim())')
                for b in btns:
                    print(f"      [{b}]")

                # Try email login
                print("    Trying email/password login...")
                email_login(page)

            else:
                # Handle Google OAuth
                if 'accounts.google.com' in page.url or 'google.com' in page.url:
                    print(f"    On Google OAuth page: {page.url}")
                    google_login(page)
                else:
                    print(f"    After Google click, at: {page.url}")

        page.screenshot(path='/mnt/e/genesis-system/scripts/z_s3_post_login.png')
        print(f"    URL after login steps: {page.url}")

        # Wait for potential redirects
        time.sleep(5)
        print(f"    Final URL after wait: {page.url}")
        page.screenshot(path='/mnt/e/genesis-system/scripts/z_s3b_settled.png')

        # Step 4: Navigate to MCP page if not already there
        if 'mcp' not in page.url.lower():
            print("\n[4] Navigating to MCP page...")
            page.goto('https://zapier.com/mcp', wait_until='networkidle', timeout=30000)
            time.sleep(3)
            print(f"    URL: {page.url}")
            page.screenshot(path='/mnt/e/genesis-system/scripts/z_s4_mcp_authed.png')

        # Step 5: Inspect the authenticated MCP page
        print("\n[5] Inspecting MCP page (authenticated)...")
        content = page.content()

        # Save full page HTML for inspection
        with open('/mnt/e/genesis-system/scripts/zapier_mcp_page.html', 'w', encoding='utf-8') as f:
            f.write(content)
        print("    Saved full page HTML")

        # Search for MCP URL patterns
        mcp_patterns = [
            r'https://actions\.zapier\.com/mcp/[a-zA-Z0-9/_?=&-]+',
            r'https://mcp\.zapier\.com/[a-zA-Z0-9/_?=&-]+(?!/mcp/servers)',
            r'https://[^"\'<>\s]*zapier[^"\'<>\s]*/mcp/[a-zA-Z0-9/_?=&-]+',
        ]

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

        if found_urls:
            print(f"    Found URLs: {found_urls}")
        else:
            print("    No MCP URLs found in page source yet")

        # Dump links on authenticated page
        links = page.eval_on_selector_all('a', 'els => els.map(e => ({href: e.href, text: e.textContent.trim()}))')
        print("\n[5] Links on authenticated MCP page:")
        for l in links[:40]:
            if l['href'] or l['text']:
                print(f"    {l['text'][:50]:50s} -> {l['href']}")

        buttons = page.eval_on_selector_all('button', 'els => els.map(e => e.textContent.trim())')
        print("\n[5] Buttons on authenticated MCP page:")
        for b in buttons[:30]:
            if b:
                print(f"    [{b}]")

        # Step 6: Try to find and click "New server" or "Create" or navigate to actions
        print("\n[6] Looking for MCP server creation...")

        # Try navigating to known Zapier MCP actions URL
        for url in [
            'https://actions.zapier.com/mcp',
            'https://zapier.com/app/actions',
            'https://actions.zapier.com',
        ]:
            print(f"    Trying: {url}")
            try:
                page.goto(url, wait_until='networkidle', timeout=15000)
                time.sleep(2)
                print(f"    Arrived at: {page.url}")
                content = page.content()
                page.screenshot(path=f'/mnt/e/genesis-system/scripts/z_try_{url.replace("https://","").replace("/","_")}.png')

                found_urls = re.findall(r'https://actions\.zapier\.com/mcp/[a-zA-Z0-9/_?=&-]+', content)
                if found_urls:
                    print(f"    FOUND MCP URL: {found_urls}")
                    clean_urls = [u for u in found_urls if '/servers' not in u]
                    if clean_urls:
                        return clean_urls[0]
                    return found_urls[0]

                # Dump links
                links = page.eval_on_selector_all('a', 'els => els.map(e => ({href: e.href, text: e.textContent.trim()}))')
                for l in links[:20]:
                    if 'mcp' in l['href'].lower() or 'mcp' in l['text'].lower():
                        print(f"    MCP Link: {l['text'][:50]} -> {l['href']}")
            except Exception as e:
                print(f"    Error: {e}")

        # Step 7: Try creating a new MCP server via the API approach
        print("\n[7] Trying MCP servers API...")

        # First check if user is logged in by looking at profile
        page.goto('https://zapier.com/app/actions', wait_until='networkidle', timeout=15000)
        time.sleep(3)
        print(f"    Actions page URL: {page.url}")
        page.screenshot(path='/mnt/e/genesis-system/scripts/z_s7_actions.png')
        content = page.content()

        # Look for "Add action" or similar
        buttons = page.eval_on_selector_all('button, [role="button"]', 'els => els.map(e => ({text: e.textContent.trim(), type: e.type}))')
        print("    Action page buttons:")
        for b in buttons[:20]:
            if b['text']:
                print(f"      [{b['text']}]")

        # Save this page HTML too
        with open('/mnt/e/genesis-system/scripts/zapier_actions_page.html', 'w', encoding='utf-8') as f:
            f.write(content)

        # Search for any MCP URL in this page
        all_matches = re.findall(r'https?://[^"\'<>\s]*mcp[^"\'<>\s]*', content)
        print(f"    MCP-related URLs found: {all_matches[:10]}")

        # Step 8: Navigate and look for "Connect" tab or MCP URL section
        print("\n[8] Checking page for MCP URL in text/code elements...")
        try:
            # Look for code blocks or pre elements that might have the URL
            code_texts = page.eval_on_selector_all('code, pre, [class*="copy"]', 'els => els.map(e => e.textContent.trim())')
            for ct in code_texts[:20]:
                if ct and ('zapier' in ct.lower() or 'mcp' in ct.lower()):
                    print(f"    Code block: {ct[:200]}")
        except:
            pass

        # Try the new API endpoint format
        print("\n[9] Trying to create MCP server via new Zapier interface...")
        page.goto('https://mcp.zapier.com', wait_until='networkidle', timeout=15000)
        time.sleep(3)
        print(f"    mcp.zapier.com URL: {page.url}")
        page.screenshot(path='/mnt/e/genesis-system/scripts/z_s9_mcp_subdomain.png')

        content = page.content()
        with open('/mnt/e/genesis-system/scripts/zapier_mcp_subdomain.html', 'w', encoding='utf-8') as f:
            f.write(content)

        # Find all URLs
        all_urls = re.findall(r'https?://[^"\'<>\s]{10,}', content)
        mcp_urls = [u for u in all_urls if 'mcp' in u.lower() and 'zapier' in u.lower()]
        print(f"    MCP URLs found: {mcp_urls[:10]}")

        # Look for buttons/links to create
        links = page.eval_on_selector_all('a', 'els => els.map(e => ({href: e.href, text: e.textContent.trim()}))')
        print("    Links on mcp.zapier.com:")
        for l in links[:30]:
            print(f"    {l['text'][:50]:50s} -> {l['href']}")

        buttons = page.eval_on_selector_all('button, [role="button"]', 'els => els.map(e => e.textContent.trim())')
        print("    Buttons:")
        for b in buttons[:20]:
            if b:
                print(f"    [{b}]")

        # Check for "Create" buttons
        for sel in ['text=Create', 'text=New', 'text=Add', 'text=Get started', 'text=Create server']:
            try:
                btn = page.locator(sel).first
                if btn.is_visible(timeout=2000):
                    print(f"\n[9] Clicking: {sel}")
                    btn.click()
                    time.sleep(3)
                    print(f"    After click URL: {page.url}")
                    page.screenshot(path='/mnt/e/genesis-system/scripts/z_s9_after_create.png')

                    content = page.content()
                    mcp_urls = re.findall(r'https://[^"\'<>\s]*zapier[^"\'<>\s]*/mcp/[^"\'<>\s]+', content)
                    if mcp_urls:
                        print(f"    Found MCP URL: {mcp_urls}")
                        return mcp_urls[0]
                    break
            except:
                continue

        browser.close()
        return None


def google_login(page):
    """Complete Google OAuth login"""
    time.sleep(2)
    page.screenshot(path='/mnt/e/genesis-system/scripts/z_google_login.png')
    print(f"    Google OAuth URL: {page.url}")

    # Enter email
    for sel in ['input[type="email"]', '#identifierId', 'input[name="identifier"]']:
        try:
            inp = page.locator(sel).first
            if inp.is_visible(timeout=3000):
                print(f"    Filling email in: {sel}")
                inp.fill(EMAIL)
                time.sleep(0.5)
                page.keyboard.press('Enter')
                time.sleep(3)
                break
        except:
            continue

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

    # Enter password
    for sel in ['input[type="password"]', 'input[name="password"]', '#password']:
        try:
            inp = page.locator(sel).first
            if inp.is_visible(timeout=5000):
                print(f"    Filling password in: {sel}")
                inp.fill(PASSWORD)
                time.sleep(0.5)
                page.keyboard.press('Enter')
                time.sleep(5)
                break
        except:
            continue

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

    # Handle 2FA prompt or account chooser
    time.sleep(3)
    page.screenshot(path='/mnt/e/genesis-system/scripts/z_google_final.png')
    print(f"    Final Google auth URL: {page.url}")


def email_login(page):
    """Try direct email login on Zapier"""
    print("    Trying direct email login...")

    for sel in ['input[type="email"]', 'input[name="email"]', '#email']:
        try:
            inp = page.locator(sel).first
            if inp.is_visible(timeout=2000):
                inp.fill(EMAIL)
                break
        except:
            continue

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

    for sel in ['input[type="password"]', 'input[name="password"]']:
        try:
            inp = page.locator(sel).first
            if inp.is_visible(timeout=5000):
                inp.fill(PASSWORD)
                inp.press('Enter')
                time.sleep(4)
                break
        except:
            continue

    page.screenshot(path='/mnt/e/genesis-system/scripts/z_email_login.png')
    print(f"    After email login 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('/mnt/e/genesis-system/scripts/zapier_mcp_url.txt', 'w') as f:
            f.write(result)
        print("Saved to: /mnt/e/genesis-system/scripts/zapier_mcp_url.txt")
    else:
        print("\n[INCOMPLETE] Need to review screenshots and HTML files")
        print("Screenshots saved in /mnt/e/genesis-system/scripts/")
        print("HTML files saved in /mnt/e/genesis-system/scripts/")
