#!/usr/bin/env python3
"""
Activate B-008-WF-1.1. Webchat workflow in Bunker FNQ GHL sub-account.
Toggles from DRAFT → Published/Active.
"""

import time
import os
from pathlib import Path
from datetime import datetime
from playwright.sync_api import sync_playwright, expect

# Credentials
GHL_EMAIL = "kinan@agileadpt.com"
GHL_PASSWORD = "SystemBird505*"
GHL_URL = "https://app.gohighlevel.com"

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

def screenshot(page, name):
    path = SCREENSHOT_DIR / f"{name}.png"
    page.screenshot(path=str(path), full_page=False)
    print(f"  [screenshot] {path}")
    return path

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

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

        # STEP 1: Navigate to GHL
        print("\n[1] Navigating to GHL login...")
        page.goto("https://app.leadconnectorhq.com/login", wait_until="networkidle", timeout=30000)
        time.sleep(2)
        screenshot(page, "01_login_page")
        print(f"  Title: {page.title()}")
        print(f"  URL: {page.url}")

        # STEP 2: Fill login credentials
        print("\n[2] Entering credentials...")
        try:
            email_field = page.wait_for_selector('input[type="email"], input[name="email"], input[placeholder*="email" i]', timeout=10000)
            email_field.fill(GHL_EMAIL)
            print(f"  Email entered: {GHL_EMAIL}")
        except Exception as e:
            print(f"  ERROR finding email field: {e}")
            screenshot(page, "02_email_error")
            # Try alternate selectors
            page.fill('input[type="email"]', GHL_EMAIL)

        time.sleep(0.5)

        try:
            password_field = page.wait_for_selector('input[type="password"]', timeout=5000)
            password_field.fill(GHL_PASSWORD)
            print(f"  Password entered")
        except Exception as e:
            print(f"  ERROR finding password field: {e}")
            screenshot(page, "02_password_error")

        time.sleep(0.5)
        screenshot(page, "02_credentials_filled")

        # STEP 3: Submit login
        print("\n[3] Submitting login...")
        try:
            # Try clicking a sign-in button
            login_btn = page.locator('button[type="submit"], button:has-text("Sign In"), button:has-text("Login"), button:has-text("Log In")')
            login_btn.first.click()
        except Exception as e:
            print(f"  Trying keyboard Enter: {e}")
            page.keyboard.press("Enter")

        print("  Waiting for dashboard to load...")
        time.sleep(5)
        screenshot(page, "03_after_login")
        print(f"  URL after login: {page.url}")
        print(f"  Title: {page.title()}")

        # Check if we need 2FA or are logged in
        current_url = page.url
        if "login" in current_url:
            print("  Still on login page - checking for issues...")
            page_text = page.inner_text("body")
            if "2fa" in page_text.lower() or "verify" in page_text.lower():
                print("  2FA required - cannot proceed")
                browser.close()
                return
            screenshot(page, "03_login_issue")
            print("  Page content snippet:", page_text[:500])

        # STEP 4: Find Bunker FNQ sub-account
        print("\n[4] Looking for Bunker FNQ or Tradie Chatbots sub-account...")
        time.sleep(3)
        screenshot(page, "04_dashboard")
        print(f"  Current URL: {page.url}")

        # Check if already in agency view or sub-account
        page_text = page.inner_text("body")
        print(f"  Page text snippet: {page_text[:300]}")

        # Look for sub-account switcher or search
        # GHL agency view typically shows a list of sub-accounts
        bunker_found = False

        # Try to find "Bunker FNQ" text on the page
        if "Bunker" in page_text or "bunker" in page_text.lower():
            print("  Found 'Bunker' reference on page")
            bunker_found = True

        # Try clicking on the location/sub-account switcher
        try:
            # GHL typically has a dropdown or search for switching sub-accounts
            switcher = page.locator('[data-testid="location-switcher"], .location-switcher, [class*="switcher"]').first
            if switcher.is_visible():
                print("  Found location switcher, clicking...")
                switcher.click()
                time.sleep(2)
                screenshot(page, "04_switcher_open")
        except Exception as e:
            print(f"  No switcher found: {e}")

        # Try searching for Bunker FNQ
        try:
            search = page.locator('input[placeholder*="search" i], input[placeholder*="Search" i]').first
            if search.is_visible(timeout=3000):
                print("  Found search box, searching for Bunker FNQ...")
                search.fill("Bunker")
                time.sleep(2)
                screenshot(page, "04_search_results")
        except Exception as e:
            print(f"  No search field found: {e}")

        # Navigate to agency accounts list
        print("\n  Navigating to agency accounts list...")
        page.goto("https://app.gohighlevel.com/", wait_until="networkidle", timeout=20000)
        time.sleep(3)
        screenshot(page, "04b_agency_home")
        print(f"  URL: {page.url}")

        # Look for accounts listing
        page_content = page.inner_text("body")
        if "Bunker" in page_content:
            print("  'Bunker' found on page!")
            # Find and click on it
            try:
                bunker_link = page.locator('text=Bunker FNQ').first
                bunker_link.click()
                time.sleep(3)
                screenshot(page, "05_bunker_selected")
                print(f"  Navigated to Bunker FNQ. URL: {page.url}")
            except Exception as e:
                print(f"  Could not click Bunker FNQ directly: {e}")
                try:
                    bunker_link = page.locator('text=Bunker').first
                    bunker_link.click()
                    time.sleep(3)
                    screenshot(page, "05_bunker_selected")
                    print(f"  Navigated. URL: {page.url}")
                except Exception as e2:
                    print(f"  Error: {e2}")

        # STEP 5: Navigate to Automation > Workflows
        print("\n[5] Navigating to Automation > Workflows...")
        current_url = page.url

        # Extract location ID from URL if present
        location_id = None
        if "/location/" in current_url:
            parts = current_url.split("/location/")
            if len(parts) > 1:
                location_id = parts[1].split("/")[0]
                print(f"  Location ID: {location_id}")

        # Try direct navigation to workflows
        if location_id:
            workflows_url = f"https://app.gohighlevel.com/location/{location_id}/automation/workflows"
            print(f"  Navigating to: {workflows_url}")
            page.goto(workflows_url, wait_until="networkidle", timeout=20000)
        else:
            # Try to navigate via sidebar
            print("  Looking for Automation in sidebar...")
            try:
                automation_link = page.locator('a[href*="automation"], [data-link-name*="automation" i], text=Automation').first
                automation_link.click()
                time.sleep(2)
                screenshot(page, "05_automation_menu")

                # Look for Workflows submenu
                workflows_link = page.locator('text=Workflows, a[href*="workflows"]').first
                workflows_link.click()
                time.sleep(2)
            except Exception as e:
                print(f"  Navigation error: {e}")

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

        # STEP 6: Look for the Webchat workflow
        print("\n[6] Searching for B-008-WF-1.1. Webchat workflow...")
        page_content = page.inner_text("body")

        # Check what's on the page
        if "B-008" in page_content or "Webchat" in page_content or "webchat" in page_content.lower():
            print("  Found webchat workflow reference on page!")
        else:
            print("  Webchat not visible yet, checking page content...")
            print(f"  Page snippet: {page_content[:500]}")

        # Look for the workflow in the list
        workflows_found = []
        try:
            # Find all workflow items
            workflow_items = page.locator('[class*="workflow"], [data-testid*="workflow"], .workflow-list-item, tr, [class*="row"]').all()
            print(f"  Found {len(workflow_items)} potential workflow items")
            for item in workflow_items[:20]:
                try:
                    text = item.inner_text().strip()
                    if text and len(text) > 3:
                        workflows_found.append(text[:100])
                except:
                    pass
        except Exception as e:
            print(f"  Error finding workflow items: {e}")

        if workflows_found:
            print("  Workflows visible:")
            for w in workflows_found[:10]:
                print(f"    - {w}")

        # STEP 7: Try to find and click on the webchat workflow
        print("\n[7] Looking for Webchat workflow to activate...")

        webchat_workflow_found = False

        # Try different selectors for the webchat workflow
        selectors_to_try = [
            'text="B-008-WF-1.1. Webchat"',
            'text="Webchat"',
            '*:has-text("B-008")',
            '*:has-text("Webchat")',
        ]

        for selector in selectors_to_try:
            try:
                el = page.locator(selector).first
                if el.is_visible(timeout=2000):
                    print(f"  Found workflow with selector: {selector}")
                    screenshot(page, "07_workflow_found")

                    # Get the workflow row/container
                    workflow_text = el.inner_text()
                    print(f"  Workflow text: {workflow_text[:200]}")

                    # Try clicking on it to open
                    el.click()
                    time.sleep(3)
                    screenshot(page, "07_workflow_opened")
                    print(f"  URL after click: {page.url}")
                    webchat_workflow_found = True
                    break
            except Exception as e:
                pass  # Try next selector

        if not webchat_workflow_found:
            print("  Webchat workflow not found with direct selectors")
            print("  Checking for any DRAFT workflows...")

            # Look for any DRAFT label
            try:
                draft_items = page.locator('text=Draft, text=DRAFT, [class*="draft"]').all()
                print(f"  Found {len(draft_items)} DRAFT items")
                for item in draft_items[:5]:
                    try:
                        parent = item.locator("..").locator("..").locator("..")
                        print(f"    Draft item: {parent.inner_text()[:100]}")
                    except:
                        print(f"    Draft item text: {item.inner_text()[:50]}")
            except Exception as e:
                print(f"  Error finding drafts: {e}")

        # STEP 8: Activate the workflow (toggle from Draft to Published)
        print("\n[8] Attempting to activate workflow...")
        current_url = page.url

        if "workflow" in current_url and "editor" in current_url.lower():
            print("  In workflow editor - looking for publish/activate button...")

            # Look for Draft toggle or Publish button
            publish_selectors = [
                'button:has-text("Publish")',
                'button:has-text("Save & Publish")',
                '[data-testid*="publish"]',
                'text=Publish',
                'button:has-text("Enable")',
                '[class*="toggle"]',
            ]

            for selector in publish_selectors:
                try:
                    btn = page.locator(selector).first
                    if btn.is_visible(timeout=2000):
                        print(f"  Found button with selector: {selector}")
                        print(f"  Button text: {btn.inner_text()}")
                        screenshot(page, "08_before_publish")
                        btn.click()
                        time.sleep(2)
                        screenshot(page, "08_after_publish")
                        print(f"  Clicked publish/activate button!")
                        print(f"  URL: {page.url}")
                        break
                except Exception as e:
                    pass
        else:
            print(f"  Not in workflow editor. URL: {current_url}")

            # Try to find the toggle/enable button directly in the list
            try:
                # GHL workflow list has toggle switches
                toggle = page.locator('[class*="toggle"]:near(:text("Webchat"))').first
                if toggle.is_visible(timeout=3000):
                    print("  Found toggle near Webchat!")
                    screenshot(page, "08_toggle_found")
                    toggle.click()
                    time.sleep(2)
                    screenshot(page, "08_toggle_clicked")
                    print("  Toggled!")
            except Exception as e:
                print(f"  No toggle found near Webchat: {e}")

        # STEP 9: Verify status
        print("\n[9] Taking final screenshot to verify status...")
        time.sleep(2)
        screenshot(page, "09_final_state")

        final_content = page.inner_text("body")
        print(f"  Final URL: {page.url}")

        # Check if workflow shows as published/active
        if "published" in final_content.lower() or "active" in final_content.lower():
            print("  SUCCESS: Workflow appears to be active/published!")
        elif "draft" in final_content.lower():
            print("  RESULT: Workflow still shows as draft")

        print(f"\n  Screenshots saved to: {SCREENSHOT_DIR}")
        print(f"  Total screenshots: {len(list(SCREENSHOT_DIR.glob('*.png')))}")

        # STEP 10: List all DRAFT workflows
        print("\n[10] Listing all DRAFT workflows...")
        if "workflow" in page.url.lower():
            page.go_back()
            time.sleep(2)

        # Navigate back to workflows list if needed
        page_content = page.inner_text("body")

        # Find all draft indicators
        draft_count = page_content.lower().count("draft")
        print(f"  'Draft' appears {draft_count} times on page")

        screenshot(page, "10_workflows_overview")

        browser.close()
        print("\n" + "=" * 60)
        print("AUTOMATION COMPLETE")
        print(f"Screenshots: {SCREENSHOT_DIR}")
        print("=" * 60)

if __name__ == "__main__":
    run()
