#!/usr/bin/env python3
"""
Activate 3 critical draft workflows for George/Bunker FNQ demo.
Target workflows:
- B-008-WF-1.1. Webchat (ID: 4a07ae2e-56d0-4f00-b6fb-c733bbdbec70)
- B-008-WF-0.1. Segment Inbound MSG (ID: b42723b3-c517-45da-b30f-9259fa4fdf88)
- B-008-WF-4.1. Contact Us Form (ID: 9d17cc6d-4d63-43ce-aa62-8834cc9f51fa)
"""
import time
import json
from pathlib import Path
from playwright.sync_api import sync_playwright

GHL_EMAIL = "kinan@agileadpt.com"
GHL_PASSWORD = "SystemBird505*"
LOCATION_ID = "SWdaQpAVAtRigYcMfder"

REPORT_DIR = Path("/mnt/e/genesis-system/reports/three_wf_activate")
REPORT_DIR.mkdir(parents=True, exist_ok=True)

# Target draft workflows by name fragment
TARGET_WORKFLOWS = [
    "B-008-WF-1.1",
    "B-008-WF-0.1",
    "B-008-WF-4.1",
]

shot_num = [0]

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

def log(msg):
    print(f"[{time.strftime('%H:%M:%S')}] {msg}")

def run():
    results = {
        "login": "pending",
        "workflows_activated": [],
        "workflows_failed": [],
        "screenshots": str(REPORT_DIR),
    }

    with sync_playwright() as p:
        browser = p.chromium.launch(
            headless=True,
            args=[
                "--no-sandbox",
                "--disable-dev-shm-usage",
                "--disable-blink-features=AutomationControlled",
                "--disable-infobars",
            ],
            ignore_default_args=["--enable-automation"],
        )

        ctx = browser.new_context(
            viewport={"width": 1920, "height": 1080},
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.6261.128 Safari/537.36",
            locale="en-AU",
            timezone_id="Australia/Brisbane",
        )
        page = ctx.new_page()

        try:
            # =====================
            # STEP 1: Login
            # =====================
            log("Step 1: Navigating to GHL login...")
            page.goto("https://app.gohighlevel.com/", timeout=30000)
            page.wait_for_load_state("domcontentloaded")

            log("Waiting for login form...")
            page.wait_for_selector('input[name="email"], input[type="email"]', timeout=20000)
            page.wait_for_timeout(2000)
            ss(page, "01_login_form")

            log("Filling credentials...")
            email_input = page.query_selector('input[name="email"]') or page.query_selector('input[type="email"]')
            pw_input = page.query_selector('input[name="password"]') or page.query_selector('input[type="password"]')

            email_input.fill(GHL_EMAIL)
            time.sleep(0.5)
            pw_input.fill(GHL_PASSWORD)
            time.sleep(0.5)

            submit_btn = page.query_selector('button[type="submit"]')
            if submit_btn:
                submit_btn.click()
            else:
                pw_input.press("Enter")

            log("Waiting for post-login redirect...")
            try:
                page.wait_for_url("**/location/**", timeout=30000)
                log("Login successful - redirected to location page")
                results["login"] = "success"
            except Exception:
                # May be at a dashboard or 2FA page
                page.wait_for_timeout(5000)
                current_url = page.url
                log(f"Current URL after login: {current_url}")
                ss(page, "02_after_login")

                if "2fa" in current_url.lower() or "verify" in current_url.lower():
                    log("2FA DETECTED - cannot proceed automatically")
                    results["login"] = "2fa_required"
                    json.dump(results, open(REPORT_DIR / "results.json", "w"), indent=2)
                    return results
                elif "app.gohighlevel.com" in current_url:
                    results["login"] = "success_dashboard"
                else:
                    results["login"] = f"unknown_state:{current_url}"

            page.wait_for_timeout(3000)
            ss(page, "02_logged_in")

            # =====================
            # STEP 2: Navigate to workflows
            # =====================
            wf_url = f"https://app.gohighlevel.com/location/{LOCATION_ID}/automation/workflows"
            log(f"Step 2: Navigating to workflows: {wf_url}")
            page.goto(wf_url, timeout=30000)
            page.wait_for_load_state("networkidle", timeout=20000)
            page.wait_for_timeout(5000)  # React hydration time
            ss(page, "03_workflows_loaded")

            # Check what's on the page
            content = page.content()
            log(f"Page has 'draft' text: {content.lower().count('draft')} times")
            log(f"Page has 'published' text: {content.lower().count('published')} times")

            # =====================
            # STEP 3: Try to activate each target workflow
            # =====================
            for target in TARGET_WORKFLOWS:
                log(f"\nStep 3: Looking for workflow: {target}")

                # Method 1: Find workflow by text content and look for toggle/button
                # Scroll to top first
                page.evaluate("window.scrollTo(0, 0)")
                page.wait_for_timeout(1000)

                # Look for the workflow name text element
                wf_element = None
                try:
                    wf_element = page.query_selector(f'text="{target}"')
                    if not wf_element:
                        # Try partial text match
                        elements = page.query_selector_all(f'*:has-text("{target}")')
                        log(f"  Found {len(elements)} elements with text '{target}'")
                        for el in elements:
                            tag = el.evaluate("el => el.tagName")
                            text = el.inner_text()[:80] if el.inner_text() else ""
                            log(f"    Tag: {tag}, Text: {text}")
                        if elements:
                            wf_element = elements[0]
                except Exception as e:
                    log(f"  Error finding workflow element: {e}")

                if not wf_element:
                    log(f"  Could not find '{target}' on page, trying scroll search...")
                    # Try scrolling through the page to find it
                    for scroll_pos in [500, 1000, 1500, 2000, 2500, 3000]:
                        page.evaluate(f"window.scrollTo(0, {scroll_pos})")
                        page.wait_for_timeout(500)
                        try:
                            elements = page.query_selector_all(f'*:has-text("{target}")')
                            if elements:
                                wf_element = elements[0]
                                log(f"  Found at scroll position {scroll_pos}")
                                break
                        except:
                            pass

                if wf_element:
                    # Take screenshot of the area
                    try:
                        wf_element.scroll_into_view_if_needed()
                        page.wait_for_timeout(500)
                        ss(page, f"04_{target.replace(' ', '_')}_found")
                    except:
                        pass

                    # Method A: Look for a toggle switch near the workflow row
                    # The toggle is typically a switch/checkbox element in the same row
                    try:
                        # Get the parent row
                        row = wf_element.evaluate_handle("""el => {
                            let node = el;
                            for (let i = 0; i < 10; i++) {
                                if (!node.parentElement) break;
                                node = node.parentElement;
                                const tag = node.tagName.toLowerCase();
                                if (tag === 'tr' || tag === 'li' ||
                                    node.classList.contains('workflow-item') ||
                                    node.getAttribute('role') === 'row') {
                                    return node;
                                }
                            }
                            return el.closest('[data-testid]') || el.parentElement.parentElement.parentElement;
                        }""")

                        # Find toggle/switch in the row
                        toggles = row.as_element().query_selector_all('[role="switch"], input[type="checkbox"], .toggle, button.switch') if row.as_element() else []
                        log(f"  Found {len(toggles)} toggles in row")

                        if toggles:
                            for toggle in toggles:
                                checked = toggle.get_attribute("aria-checked") or toggle.get_attribute("checked")
                                log(f"  Toggle checked: {checked}")
                                if checked in [None, "false", False]:
                                    toggle.click()
                                    page.wait_for_timeout(2000)
                                    log(f"  Clicked toggle for {target}")
                                    ss(page, f"05_{target.replace(' ', '_')}_toggled")
                                    results["workflows_activated"].append(target)
                                    break
                    except Exception as e:
                        log(f"  Toggle method failed: {e}")

                    # Method B: Look for context menu / three-dot menu to activate
                    if target not in results["workflows_activated"]:
                        try:
                            # Look for a menu button / kebab menu near the workflow
                            menu_btns = page.query_selector_all('[aria-label*="more"], [aria-label*="actions"], .action-menu, button:has-text("..."), .kebab, .dots-menu')
                            log(f"  Found {len(menu_btns)} menu buttons")
                        except Exception as e:
                            log(f"  Menu method failed: {e}")

                    # Method C: Click into the workflow and use the publish button inside
                    if target not in results["workflows_activated"]:
                        log(f"  Trying click-into-workflow method...")
                        try:
                            # Click on the workflow name to open it
                            wf_element.click()
                            page.wait_for_load_state("networkidle", timeout=15000)
                            page.wait_for_timeout(3000)
                            ss(page, f"06_{target.replace(' ', '_')}_editor")

                            # Look for Publish/Save & Publish/Enable button in the editor
                            publish_selectors = [
                                'button:has-text("Publish")',
                                'button:has-text("Save & Publish")',
                                'button:has-text("Enable")',
                                'button:has-text("Activate")',
                                '[data-testid="publish-btn"]',
                                '.publish-btn',
                            ]

                            for sel in publish_selectors:
                                try:
                                    btn = page.query_selector(sel)
                                    if btn:
                                        log(f"  Found publish button with selector: {sel}")
                                        btn.scroll_into_view_if_needed()
                                        btn.click()
                                        page.wait_for_timeout(3000)
                                        ss(page, f"07_{target.replace(' ', '_')}_published")
                                        log(f"  Clicked publish button for {target}")
                                        results["workflows_activated"].append(target)
                                        break
                                except Exception as e:
                                    log(f"  Selector {sel} failed: {e}")

                            # Go back to workflows list
                            page.go_back()
                            page.wait_for_load_state("networkidle", timeout=15000)
                            page.wait_for_timeout(3000)

                        except Exception as e:
                            log(f"  Click-into-workflow method failed: {e}")
                            # Try to navigate back
                            try:
                                page.goto(wf_url, timeout=20000)
                                page.wait_for_load_state("networkidle", timeout=15000)
                                page.wait_for_timeout(3000)
                            except:
                                pass
                else:
                    log(f"  WARNING: Could not find workflow '{target}' on page at all")
                    results["workflows_failed"].append(f"{target}: not_found_on_page")

            # Final screenshot
            ss(page, "99_final_state")

        except Exception as e:
            log(f"FATAL ERROR: {e}")
            import traceback
            traceback.print_exc()
            try:
                ss(page, "error_state")
            except:
                pass
            results["error"] = str(e)

        finally:
            browser.close()

    json.dump(results, open(REPORT_DIR / "results.json", "w"), indent=2)
    log(f"\n=== RESULTS ===")
    log(f"Login: {results.get('login')}")
    log(f"Activated: {results.get('workflows_activated')}")
    log(f"Failed: {results.get('workflows_failed')}")
    log(f"Screenshots: {results.get('screenshots')}")
    return results


if __name__ == "__main__":
    run()
