#!/usr/bin/env python3
"""
Activate B-008-WF-1.1. Webchat workflow in Bunker FNQ GHL sub-account.
Version 3 - Click on coordinates since selectors aren't matching in headless mode
Uses page.click() with coordinate fallbacks and proper wait patterns
"""

import time
from pathlib import Path
from playwright.sync_api import sync_playwright

# Credentials
GHL_EMAIL = "kinan@agileadpt.com"
GHL_PASSWORD = "SystemBird505*"

# Screenshot dir
SCREENSHOT_DIR = Path("/mnt/e/genesis-system/reports/bunker_webchat_activation")
SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)

shot_num = [0]

def screenshot(page, name):
    shot_num[0] += 1
    path = SCREENSHOT_DIR / f"{shot_num[0]:02d}_{name}.png"
    try:
        page.screenshot(path=str(path), full_page=False)
        print(f"  [screenshot] {path.name}")
    except Exception as e:
        print(f"  [screenshot failed] {e}")
    return path

def run():
    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=True,
            args=[
                "--no-sandbox",
                "--disable-dev-shm-usage",
                "--disable-blink-features=AutomationControlled",
                "--window-size=1400,900"
            ]
        )
        context = browser.new_context(
            viewport={"width": 1400, "height": 900},
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
        )
        page = context.new_page()

        print("=" * 60)
        print("BUNKER FNQ - ACTIVATE B-008-WF-1.1. Webchat Workflow v3")
        print("=" * 60)

        # STEP 1: Navigate and wait for full render
        print("\n[1] Navigating to GHL login...")
        page.goto("https://app.gohighlevel.com/", timeout=30000)

        # Wait for the page to be fully interactive (DOM + network)
        page.wait_for_load_state("domcontentloaded")
        page.wait_for_timeout(5000)  # Extra wait for React hydration

        screenshot(page, "01_login_loaded")
        print(f"  URL: {page.url}")
        print(f"  Title: {page.title()}")

        # Inspect DOM for inputs
        inputs_info = page.evaluate("""
            () => {
                const inputs = document.querySelectorAll('input');
                return Array.from(inputs).map(i => ({
                    type: i.type,
                    placeholder: i.placeholder,
                    name: i.name,
                    id: i.id,
                    className: i.className.substring(0, 50),
                    visible: i.offsetParent !== null,
                    rect: JSON.stringify(i.getBoundingClientRect())
                }));
            }
        """)
        print(f"  Found {len(inputs_info)} inputs:")
        for inp in inputs_info:
            print(f"    - type={inp['type']}, placeholder='{inp['placeholder']}', visible={inp['visible']}")

        # STEP 2: Fill email field
        print("\n[2] Filling email field...")
        email_filled = False

        # Try by placeholder text
        try:
            email_input = page.get_by_placeholder("Your email address")
            email_input.click()
            email_input.fill(GHL_EMAIL)
            print(f"  Email filled via placeholder 'Your email address'")
            email_filled = True
        except Exception as e:
            print(f"  Placeholder method failed: {e}")

        if not email_filled:
            # Try direct evaluation
            try:
                page.evaluate(f"""
                    () => {{
                        const inputs = document.querySelectorAll('input');
                        const emailInput = Array.from(inputs).find(i =>
                            i.type === 'email' ||
                            i.placeholder?.toLowerCase().includes('email') ||
                            i.name?.toLowerCase().includes('email')
                        );
                        if (emailInput) {{
                            emailInput.focus();
                            emailInput.value = '{GHL_EMAIL}';
                            emailInput.dispatchEvent(new Event('input', {{bubbles: true}}));
                            emailInput.dispatchEvent(new Event('change', {{bubbles: true}}));
                        }}
                    }}
                """)
                print(f"  Email filled via JS evaluation")
                email_filled = True
            except Exception as e:
                print(f"  JS evaluation failed: {e}")

        page.wait_for_timeout(500)

        # STEP 3: Fill password field
        print("\n[3] Filling password field...")
        password_filled = False

        try:
            password_input = page.get_by_placeholder("The password you picked")
            password_input.click()
            password_input.fill(GHL_PASSWORD)
            print(f"  Password filled via placeholder")
            password_filled = True
        except Exception as e:
            print(f"  Placeholder method failed: {e}")

        if not password_filled:
            try:
                page.evaluate(f"""
                    () => {{
                        const inputs = document.querySelectorAll('input');
                        const pwdInput = Array.from(inputs).find(i =>
                            i.type === 'password' ||
                            i.placeholder?.toLowerCase().includes('password') ||
                            i.name?.toLowerCase().includes('password')
                        );
                        if (pwdInput) {{
                            pwdInput.focus();
                            pwdInput.value = '{GHL_PASSWORD}';
                            pwdInput.dispatchEvent(new Event('input', {{bubbles: true}}));
                            pwdInput.dispatchEvent(new Event('change', {{bubbles: true}}));
                        }}
                    }}
                """)
                print(f"  Password filled via JS evaluation")
                password_filled = True
            except Exception as e:
                print(f"  JS pwd evaluation failed: {e}")

        screenshot(page, "02_credentials_filled")

        # Verify values were entered
        field_values = page.evaluate("""
            () => {
                const inputs = document.querySelectorAll('input');
                return Array.from(inputs).map(i => ({
                    type: i.type,
                    value_length: i.value.length,
                    placeholder: i.placeholder
                }));
            }
        """)
        for fv in field_values:
            print(f"  Field: type={fv['type']}, value_length={fv['value_length']}, placeholder='{fv['placeholder']}'")

        # STEP 4: Click Sign In button
        print("\n[4] Clicking Sign In button...")
        submitted = False

        try:
            sign_in_btn = page.get_by_role("button", name="Sign in")
            sign_in_btn.click()
            print("  Clicked 'Sign in' button via role")
            submitted = True
        except Exception as e:
            print(f"  Role-based click failed: {e}")

        if not submitted:
            try:
                sign_in_btn = page.get_by_text("Sign in")
                sign_in_btn.click()
                print("  Clicked via get_by_text")
                submitted = True
            except Exception as e:
                print(f"  Text-based click failed: {e}")

        if not submitted:
            # Use JS to find and click
            try:
                page.evaluate("""
                    () => {
                        const buttons = document.querySelectorAll('button');
                        const signInBtn = Array.from(buttons).find(b =>
                            b.textContent.trim().toLowerCase().includes('sign in') ||
                            b.type === 'submit'
                        );
                        if (signInBtn) signInBtn.click();
                    }
                """)
                print("  Clicked via JS evaluation")
                submitted = True
            except Exception as e:
                print(f"  JS click failed: {e}")

        # Wait for navigation
        print("  Waiting for post-login page...")
        try:
            page.wait_for_url(lambda url: "login" not in url, timeout=15000)
            print("  Navigated away from login page!")
        except Exception as e:
            print(f"  Wait for URL change failed: {e}")
            page.wait_for_timeout(5000)

        screenshot(page, "03_after_login")
        print(f"  URL after login: {page.url}")
        print(f"  Title: {page.title()}")

        # If still on login, check for errors
        if "login" in page.url.lower():
            print("  Still on login page!")
            error_text = page.evaluate("""
                () => {
                    const errors = document.querySelectorAll('[class*="error"], [class*="alert"], [class*="message"]');
                    return Array.from(errors).map(e => e.textContent.trim()).filter(t => t.length > 0);
                }
            """)
            print(f"  Error elements: {error_text}")

            body_text = page.inner_text("body")
            print(f"  Body text: {body_text[:500]}")
            browser.close()
            return

        # STEP 5: We're logged in - find Bunker FNQ
        print("\n[5] Logged in! Looking for Bunker FNQ sub-account...")
        page.wait_for_load_state("networkidle", timeout=15000)
        page.wait_for_timeout(3000)
        screenshot(page, "04_logged_in_dashboard")

        current_url = page.url
        print(f"  Dashboard URL: {current_url}")

        # Get page text to see what's visible
        page_text = page.inner_text("body")
        print(f"  Dashboard content snippet: {page_text[:600]}")

        # If we're in sub-account view already, get location ID
        location_id = None
        if "/location/" in current_url:
            location_id = current_url.split("/location/")[1].split("/")[0].split("?")[0]
            print(f"  Already in location: {location_id}")

        # Look for location switcher or sub-account list
        if not location_id:
            print("  Need to find Bunker FNQ in sub-accounts...")

            # Check for agency view with locations list
            if "Bunker" in page_text:
                print("  'Bunker' found on dashboard!")
                try:
                    bunker = page.get_by_text("Bunker FNQ").first
                    bunker.click()
                    page.wait_for_load_state("networkidle", timeout=10000)
                    page.wait_for_timeout(2000)
                    screenshot(page, "05_bunker_selected")
                    current_url = page.url
                    print(f"  After selecting Bunker FNQ: {current_url}")
                    if "/location/" in current_url:
                        location_id = current_url.split("/location/")[1].split("/")[0].split("?")[0]
                        print(f"  Location ID: {location_id}")
                except Exception as e:
                    print(f"  Could not click Bunker FNQ: {e}")
                    # Try partial match
                    try:
                        bunker = page.locator('text=Bunker').first
                        bunker.click()
                        page.wait_for_timeout(3000)
                        current_url = page.url
                        if "/location/" in current_url:
                            location_id = current_url.split("/location/")[1].split("/")[0].split("?")[0]
                            print(f"  Location ID from partial: {location_id}")
                    except Exception as e2:
                        print(f"  Partial click also failed: {e2}")

            else:
                print("  'Bunker' not on current page")
                print("  Looking for agency accounts or sub-account switcher...")

                # Try to find the sub-account list or search
                links_info = page.evaluate("""
                    () => {
                        const links = document.querySelectorAll('a[href*="location"]');
                        return Array.from(links).slice(0, 20).map(a => ({
                            href: a.href,
                            text: a.textContent.trim().substring(0, 50)
                        }));
                    }
                """)
                print(f"  Location links found: {len(links_info)}")
                for link in links_info[:10]:
                    print(f"    {link['text']} -> {link['href']}")

                # Look for any location ID in existing links
                if links_info:
                    for link in links_info:
                        href = link['href']
                        if '/location/' in href:
                            loc_id = href.split('/location/')[1].split('/')[0].split('?')[0]
                            loc_text = link['text'].lower()
                            if 'bunker' in loc_text or 'tradie' in loc_text:
                                location_id = loc_id
                                print(f"  Found Bunker/Tradie location: {loc_id}")
                                page.goto(f"https://app.gohighlevel.com/location/{loc_id}/dashboard", timeout=15000)
                                page.wait_for_timeout(3000)
                                screenshot(page, "05_location_navigated")
                                print(f"  Navigated to location: {page.url}")
                                break

                if not location_id and links_info:
                    # Use the first location link as fallback
                    first_href = links_info[0]['href']
                    if '/location/' in first_href:
                        location_id = first_href.split('/location/')[1].split('/')[0].split('?')[0]
                        print(f"  Using first location as fallback: {location_id} ({links_info[0]['text']})")

        # STEP 6: Navigate to Workflows
        print("\n[6] Navigating to Automation > Workflows...")
        if not location_id:
            # Try to extract from current URL one more time
            current_url = page.url
            if "/location/" in current_url:
                location_id = current_url.split("/location/")[1].split("/")[0].split("?")[0]

        if location_id:
            workflows_url = f"https://app.gohighlevel.com/location/{location_id}/automation/workflows"
            print(f"  Direct URL: {workflows_url}")
            page.goto(workflows_url, timeout=20000)
            page.wait_for_load_state("networkidle", timeout=15000)
            page.wait_for_timeout(4000)
        else:
            print("  No location ID found - cannot navigate to workflows")
            print("  Current page info:")
            print(f"  URL: {page.url}")
            body_text = page.inner_text("body")
            print(f"  Content: {body_text[:500]}")
            screenshot(page, "06_no_location")
            browser.close()
            return

        screenshot(page, "06_workflows_page")
        print(f"  Workflows URL: {page.url}")

        # STEP 7: Find the Webchat workflow
        print("\n[7] Looking for B-008-WF-1.1. Webchat workflow...")
        page_text = page.inner_text("body")
        print(f"  Page content snippet: {page_text[:600]}")

        webchat_visible = "webchat" in page_text.lower() or "B-008" in page_text
        print(f"  Webchat/B-008 visible: {webchat_visible}")

        # Get all workflow-related elements
        workflow_elements = page.evaluate("""
            () => {
                // Find rows or cards that might be workflow items
                const allText = document.body.innerText;
                const lines = allText.split('\\n').filter(l => l.trim().length > 2 && l.trim().length < 200);
                return lines.slice(0, 50);
            }
        """)
        print("  Text lines on page (first 30):")
        for line in workflow_elements[:30]:
            line = line.strip()
            if line:
                print(f"    {line}")

        # Try to find webchat by text
        webchat_found = False
        for search_text in ["B-008-WF-1.1. Webchat", "B-008-WF-1.1", "B-008", "Webchat"]:
            try:
                el = page.get_by_text(search_text, exact=False).first
                if el.is_visible(timeout=2000):
                    print(f"\n  FOUND workflow with text: '{search_text}'")
                    el_text = el.inner_text()
                    print(f"  Element text: {el_text[:200]}")
                    screenshot(page, "07_workflow_found")

                    # Click on it
                    el.click()
                    page.wait_for_load_state("networkidle", timeout=10000)
                    page.wait_for_timeout(3000)
                    screenshot(page, "07_workflow_opened")
                    print(f"  URL after clicking workflow: {page.url}")
                    webchat_found = True
                    break
            except Exception as e:
                pass

        if not webchat_found:
            print("  Could not find Webchat workflow by text")
            print("  Checking if we need to look in a different sub-account...")
            screenshot(page, "07_not_found")

        # STEP 8: Activate/Publish the workflow
        print("\n[8] Attempting to activate workflow...")
        current_url = page.url

        if "/automation/" in current_url:
            print(f"  In automation section: {current_url}")

            # Look for the publish/enable button or toggle
            # GHL workflow editor typically shows "Publish" button or Draft/Published toggle

            # First look for the "Draft" status indicator and toggle
            page_text = page.inner_text("body")
            print(f"  Page content: {page_text[:400]}")

            buttons = page.evaluate("""
                () => {
                    const buttons = document.querySelectorAll('button');
                    return Array.from(buttons).map(b => ({
                        text: b.textContent.trim().substring(0, 50),
                        type: b.type,
                        disabled: b.disabled,
                        className: b.className.substring(0, 50)
                    })).filter(b => b.text.length > 0);
                }
            """)
            print(f"  Buttons on page ({len(buttons)}):")
            for btn in buttons[:20]:
                print(f"    - '{btn['text']}' (disabled={btn['disabled']})")

            # Try to click Publish
            publish_clicked = False
            for btn_text in ["Publish", "Save & Publish", "Enable", "Activate", "Save"]:
                try:
                    btn = page.get_by_role("button", name=btn_text, exact=False)
                    if btn.is_visible(timeout=2000):
                        print(f"\n  Clicking button: '{btn_text}'")
                        screenshot(page, "08_before_publish")
                        btn.click()
                        page.wait_for_timeout(2000)
                        screenshot(page, "08_after_publish_click")

                        # Check for confirmation modal
                        try:
                            confirm = page.get_by_role("button", name=re.compile("confirm|yes|ok|proceed", re.I)).first
                            if confirm.is_visible(timeout=2000):
                                confirm.click()
                                page.wait_for_timeout(2000)
                                screenshot(page, "08_confirmed")
                                print("  Confirmed!")
                        except:
                            pass

                        print(f"  URL: {page.url}")
                        publish_clicked = True
                        break
                except:
                    continue

            if not publish_clicked:
                print("  No publish button found, looking for toggle...")
                # Look for any toggle or switch
                toggles = page.evaluate("""
                    () => {
                        const toggles = document.querySelectorAll('input[type="checkbox"], [role="switch"], [class*="toggle"], [class*="switch"]');
                        return Array.from(toggles).map(t => ({
                            type: t.tagName,
                            checked: t.checked,
                            ariaLabel: t.getAttribute('aria-label'),
                            className: t.className.substring(0, 50),
                            text: t.closest('label')?.textContent?.trim()?.substring(0, 50) || ''
                        })).filter(t => t.ariaLabel || t.text || t.className.includes('toggle') || t.className.includes('switch'));
                    }
                """)
                print(f"  Toggles found ({len(toggles)}):")
                for toggle in toggles[:10]:
                    print(f"    - {toggle}")

        # STEP 9: Final verification
        print("\n[9] Final verification screenshot...")
        page.wait_for_timeout(2000)
        screenshot(page, "09_final_state")
        print(f"  Final URL: {page.url}")

        final_text = page.inner_text("body")
        status_terms = {}
        for term in ["published", "active", "enabled", "live", "draft"]:
            count = final_text.lower().count(term)
            if count > 0:
                status_terms[term] = count
        print(f"  Status terms: {status_terms}")

        # STEP 10: List all DRAFT workflows
        print("\n[10] Listing all workflows (draft/published)...")
        if location_id and "/automation/workflows" not in page.url:
            page.goto(f"https://app.gohighlevel.com/location/{location_id}/automation/workflows", timeout=15000)
            page.wait_for_load_state("networkidle", timeout=10000)
            page.wait_for_timeout(4000)

        screenshot(page, "10_all_workflows")

        all_text = page.inner_text("body")
        lines = [l.strip() for l in all_text.split('\n') if l.strip()]

        print("\n  All workflow-related content:")
        in_workflow_section = False
        for line in lines:
            if any(term in line.lower() for term in ['workflow', 'automation', 'draft', 'published', 'active']):
                if len(line) < 200:
                    print(f"    {line}")

        browser.close()

        print("\n" + "=" * 60)
        print("AUTOMATION COMPLETE")
        print(f"Screenshots: {SCREENSHOT_DIR}")
        screenshots = sorted(SCREENSHOT_DIR.glob("*.png"))
        print(f"Total: {len(screenshots)}")
        print("=" * 60)

if __name__ == "__main__":
    import re
    run()
