#!/usr/bin/env python3
"""
Activate B-008-WF-1.1. Webchat workflow in Bunker FNQ GHL sub-account.
Version 2 - with proper wait conditions for React SPA
"""

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 wait_and_screenshot(page, name, wait_ms=3000):
    page.wait_for_timeout(wait_ms)
    return screenshot(page, name)

def run():
    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=True,
            args=["--no-sandbox", "--disable-dev-shm-usage", "--disable-blink-features=AutomationControlled"]
        )
        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",
            ignore_https_errors=True
        )
        page = context.new_page()

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

        # STEP 1: Navigate to GHL login with proper wait
        print("\n[1] Navigating to GHL login...")
        page.goto("https://app.leadconnectorhq.com/login", timeout=30000)

        # Wait for React app to load - wait for any input to appear
        print("  Waiting for React app to render...")
        try:
            page.wait_for_selector('input', timeout=15000)
            print("  Login form rendered!")
        except Exception as e:
            print(f"  Timeout waiting for input: {e}")
            # Try waiting for specific network idle
            page.wait_for_load_state("networkidle", timeout=15000)

        wait_and_screenshot(page, "01_login_page", 1000)
        print(f"  Title: {page.title()}")
        print(f"  URL: {page.url}")

        # Debug: check what's on the page
        try:
            all_inputs = page.locator('input').all()
            print(f"  Found {len(all_inputs)} input fields")
            for inp in all_inputs[:5]:
                try:
                    attr_type = inp.get_attribute('type')
                    attr_placeholder = inp.get_attribute('placeholder')
                    attr_name = inp.get_attribute('name')
                    print(f"    input: type={attr_type}, placeholder={attr_placeholder}, name={attr_name}")
                except:
                    pass
        except Exception as e:
            print(f"  Error inspecting inputs: {e}")

        # STEP 2: Fill email
        print("\n[2] Filling email field...")
        try:
            # Try multiple selectors
            for selector in ['input[name="email"]', 'input[type="email"]', 'input[placeholder*="email" i]', 'input[placeholder*="Email"]', 'input:first-of-type']:
                try:
                    el = page.locator(selector).first
                    if el.is_visible(timeout=2000):
                        el.fill(GHL_EMAIL)
                        print(f"  Email filled with selector: {selector}")
                        break
                except:
                    continue
        except Exception as e:
            print(f"  Error filling email: {e}")

        page.wait_for_timeout(500)

        # STEP 3: Fill password
        print("\n[3] Filling password field...")
        try:
            for selector in ['input[type="password"]', 'input[name="password"]', 'input[placeholder*="password" i]']:
                try:
                    el = page.locator(selector).first
                    if el.is_visible(timeout=2000):
                        el.fill(GHL_PASSWORD)
                        print(f"  Password filled with selector: {selector}")
                        break
                except:
                    continue
        except Exception as e:
            print(f"  Error filling password: {e}")

        screenshot(page, "02_credentials_filled")

        # STEP 4: Submit login
        print("\n[4] Submitting login...")
        submitted = False

        # Try submit button
        for btn_selector in [
            'button[type="submit"]',
            'button:has-text("Sign In")',
            'button:has-text("Log In")',
            'button:has-text("Login")',
            'button:has-text("Continue")',
            '.btn-primary',
            'button[data-cy="login"]',
        ]:
            try:
                btn = page.locator(btn_selector).first
                if btn.is_visible(timeout=1500):
                    print(f"  Clicking button: {btn_selector} - text: '{btn.inner_text()}'")
                    btn.click()
                    submitted = True
                    break
            except:
                continue

        if not submitted:
            print("  No button found, pressing Enter...")
            page.keyboard.press("Enter")

        # Wait for navigation after login
        print("  Waiting for post-login navigation...")
        try:
            page.wait_for_url("**/dashboard**", timeout=15000)
            print("  Navigated to dashboard!")
        except:
            try:
                page.wait_for_load_state("networkidle", timeout=10000)
            except:
                pass

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

        # Check if still on login page
        if "login" in page.url:
            print("  Still on login page - checking for error messages...")
            try:
                errors = page.locator('[class*="error"], [class*="alert"], .text-red').all()
                for e in errors:
                    print(f"  Error: {e.inner_text()}")
            except:
                pass
            page_text = page.inner_text("body")
            print(f"  Page content: {page_text[:300]}")

        # STEP 5: Look for sub-accounts / Bunker FNQ
        print("\n[5] Looking for Bunker FNQ sub-account...")
        current_url = page.url
        print(f"  Current URL: {current_url}")

        # Check if we're in the agency view
        page_text = page.inner_text("body")
        if "Bunker" in page_text:
            print("  'Bunker' text found on current page!")

        # Try to navigate to the agency locations list
        print("  Trying to navigate to locations/sub-accounts list...")

        # GHL sub-account selection page
        for url_attempt in [
            "https://app.gohighlevel.com/",
            "https://app.leadconnectorhq.com/",
        ]:
            try:
                page.goto(url_attempt, timeout=15000)
                page.wait_for_load_state("networkidle", timeout=10000)
                time.sleep(2)
                url_now = page.url
                print(f"  After navigating to {url_attempt}: {url_now}")
                break
            except Exception as e:
                print(f"  Error navigating to {url_attempt}: {e}")

        wait_and_screenshot(page, "04_agency_view", 2000)

        # Check content for sub-accounts
        page_text = page.inner_text("body")
        print(f"  Page content snippet: {page_text[:400]}")

        if "Bunker" in page_text:
            print("  Found 'Bunker' - trying to click...")
            try:
                # Look for Bunker FNQ as a clickable element
                bunker = page.locator('text=Bunker FNQ').first
                bunker.click()
                page.wait_for_load_state("networkidle", timeout=10000)
                wait_and_screenshot(page, "05_bunker_selected", 2000)
                print(f"  After clicking Bunker FNQ: {page.url}")
            except Exception as e:
                print(f"  Could not click 'Bunker FNQ': {e}")
                try:
                    bunker = page.locator('text=Bunker').first
                    bunker.click()
                    page.wait_for_load_state("networkidle", timeout=10000)
                    wait_and_screenshot(page, "05_bunker_clicked", 2000)
                    print(f"  After clicking 'Bunker': {page.url}")
                except Exception as e2:
                    print(f"  Could not click 'Bunker': {e2}")

        # Extract location ID from current URL
        location_id = None
        current_url = page.url
        if "/location/" in current_url:
            parts = current_url.split("/location/")
            if len(parts) > 1:
                location_id = parts[1].split("/")[0].split("?")[0]
                print(f"\n  Detected location ID: {location_id}")

        # STEP 6: Navigate to Workflows
        print("\n[6] Navigating to Workflows...")

        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)
        else:
            # Try to find the location from the current page
            print("  No location ID in URL yet. Checking page for location context...")

            # Try clicking on Automation in sidebar
            try:
                auto_link = page.locator('a[href*="automation"], nav a:has-text("Automation"), [data-tooltip="Automation"]').first
                if auto_link.is_visible(timeout=3000):
                    auto_link.click()
                    time.sleep(2)
                    screenshot(page, "06_automation_clicked")

                    wf_link = page.locator('a[href*="workflows"], :has-text("Workflows")').first
                    if wf_link.is_visible(timeout=3000):
                        wf_link.click()
                        time.sleep(2)
            except Exception as e:
                print(f"  Sidebar navigation failed: {e}")

        wait_and_screenshot(page, "06_workflows_page", 3000)
        print(f"  URL: {page.url}")

        # Check if we're on the workflows page
        page_text = page.inner_text("body")
        print(f"  Page content snippet: {page_text[:500]}")

        # Look for location ID in URL now
        current_url = page.url
        if "/location/" in current_url and not location_id:
            parts = current_url.split("/location/")
            if len(parts) > 1:
                location_id = parts[1].split("/")[0].split("?")[0]
                print(f"  Now have location ID: {location_id}")

        # STEP 7: Find the Webchat workflow
        print("\n[7] Looking for B-008-WF-1.1. Webchat workflow...")

        # List all workflows visible
        print("  Scanning for workflows on page...")
        page_text = page.inner_text("body")

        # Look for specific workflow
        webchat_text_found = "webchat" in page_text.lower() or "B-008" in page_text

        if webchat_text_found:
            print("  Webchat/B-008 reference found on page!")
        else:
            print("  Webchat not visible, checking draft filter or search...")
            # Try searching for the workflow
            try:
                search = page.locator('input[placeholder*="search" i], input[placeholder*="Search"]').first
                if search.is_visible(timeout=3000):
                    search.fill("Webchat")
                    page.wait_for_timeout(2000)
                    screenshot(page, "07_search_webchat")
                    print("  Searched for 'Webchat'")
            except Exception as e:
                print(f"  No search field: {e}")

        wait_and_screenshot(page, "07_workflow_list", 2000)

        # Try to find and click webchat workflow
        webchat_clicked = False
        for selector in [
            'text="B-008-WF-1.1. Webchat"',
            ':has-text("B-008-WF-1.1")',
            ':has-text("B-008")',
            ':has-text("Webchat")',
            'text="Webchat"',
        ]:
            try:
                el = page.locator(selector).first
                if el.is_visible(timeout=2000):
                    print(f"  Found with: {selector}")
                    print(f"  Element text: {el.inner_text()[:100]}")
                    el.click()
                    page.wait_for_load_state("networkidle", timeout=10000)
                    wait_and_screenshot(page, "07_workflow_opened", 3000)
                    print(f"  URL after click: {page.url}")
                    webchat_clicked = True
                    break
            except Exception as e:
                pass

        if not webchat_clicked:
            print("  Could not find webchat workflow directly")
            print("  Listing all text that looks like workflow names...")
            try:
                # Try to get all items in the workflow list
                items = page.locator('[class*="workflow"], .hl-table-row, [class*="automation-item"], tbody tr').all()
                print(f"  Found {len(items)} list items")
                for item in items[:15]:
                    try:
                        text = item.inner_text().strip()
                        if text and "Draft" in text or "workflow" in text.lower() or len(text) > 5:
                            print(f"    Item: {text[:100]}")
                    except:
                        pass
            except Exception as e:
                print(f"  Error listing items: {e}")

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

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

            # Look for the publish toggle or button
            print("  Looking for Publish/Enable button...")
            for selector in [
                'button:has-text("Publish")',
                'button:has-text("Save & Publish")',
                'button:has-text("Enable")',
                'button:has-text("Activate")',
                '[data-testid*="publish"]',
                '[aria-label*="publish" i]',
                '[title*="publish" i]',
            ]:
                try:
                    btn = page.locator(selector).first
                    if btn.is_visible(timeout=2000):
                        btn_text = btn.inner_text()
                        print(f"  Found button: '{btn_text}' with selector: {selector}")
                        screenshot(page, "08_before_publish")
                        btn.click()
                        page.wait_for_timeout(2000)
                        screenshot(page, "08_after_publish")
                        print(f"  Clicked button!")

                        # Check for confirmation dialog
                        try:
                            confirm_btn = page.locator('button:has-text("Confirm"), button:has-text("Yes"), button:has-text("OK")').first
                            if confirm_btn.is_visible(timeout=2000):
                                confirm_btn.click()
                                page.wait_for_timeout(2000)
                                screenshot(page, "08_confirmed")
                                print("  Confirmed!")
                        except:
                            pass

                        break
                except:
                    continue

            # Look for Draft/Published toggle
            print("  Looking for Draft/Published toggle...")
            try:
                draft_toggle = page.locator('[class*="toggle"], [class*="switch"], input[type="checkbox"]').all()
                for toggle in draft_toggle[:5]:
                    try:
                        is_checked = toggle.is_checked()
                        toggle_parent = toggle.locator("..")
                        parent_text = toggle_parent.inner_text()[:50]
                        print(f"  Toggle: checked={is_checked}, context: {parent_text}")
                    except:
                        pass
            except Exception as e:
                print(f"  Error checking toggles: {e}")

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

        final_text = page.inner_text("body")

        # Look for published/active indicators
        status_indicators = []
        for term in ["published", "active", "enabled", "live", "draft"]:
            count = final_text.lower().count(term)
            if count > 0:
                status_indicators.append(f"{term}({count}x)")

        print(f"  Status terms found: {', '.join(status_indicators) if status_indicators else 'none'}")

        # STEP 10: Go back to workflow list and enumerate DRAFT workflows
        print("\n[10] Enumerating all DRAFT workflows...")

        if location_id:
            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(3000)
            wait_and_screenshot(page, "10_all_workflows", 2000)

            wf_page_text = page.inner_text("body")
            lines = wf_page_text.split("\n")
            draft_workflows = []
            published_workflows = []

            for i, line in enumerate(lines):
                line = line.strip()
                if not line:
                    continue
                if "draft" in line.lower() and len(line) < 200:
                    # Look at surrounding context
                    context_start = max(0, i-3)
                    context_end = min(len(lines), i+3)
                    context = " | ".join(l.strip() for l in lines[context_start:context_end] if l.strip())
                    draft_workflows.append(context[:150])
                elif "published" in line.lower() and len(line) < 200:
                    context_start = max(0, i-3)
                    context_end = min(len(lines), i+3)
                    context = " | ".join(l.strip() for l in lines[context_start:context_end] if l.strip())
                    published_workflows.append(context[:150])

            print(f"\n  DRAFT workflows found ({len(draft_workflows)}):")
            for wf in draft_workflows[:10]:
                print(f"    - {wf}")

            print(f"\n  PUBLISHED workflows found ({len(published_workflows)}):")
            for wf in published_workflows[:10]:
                print(f"    - {wf}")

        browser.close()

        print("\n" + "=" * 60)
        print("AUTOMATION COMPLETE")
        print(f"Screenshots saved to: {SCREENSHOT_DIR}")
        screenshots = list(SCREENSHOT_DIR.glob("*.png"))
        print(f"Total screenshots: {len(screenshots)}")
        for s in sorted(screenshots):
            print(f"  {s.name}")
        print("=" * 60)

if __name__ == "__main__":
    run()
