#!/usr/bin/env python3
"""GHL workflow activation - with proper React SPA wait times"""
import os, sys, json, time
from datetime import datetime
from pathlib import Path

os.environ['LD_LIBRARY_PATH'] = '/mnt/e/genesis-system/.venvs/playwright-libs/'

GHL_EMAIL = 'kinan@agileadapt.com'
GHL_PASSWORD = 'SystemBird505*'
LOCATION_ID = 'SWdaQpAVAtRigYcMfder'
REPORT_DIR = Path(f'/mnt/e/genesis-system/reports/ghl_workflows_{datetime.now().strftime("%H%M%S")}')
REPORT_DIR.mkdir(parents=True, exist_ok=True)

def run():
    from playwright.sync_api import sync_playwright
    
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True, 
            args=['--no-sandbox','--disable-gpu','--disable-dev-shm-usage'])
        ctx = browser.new_context(
            viewport={'width':1920,'height':1080},
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36'
        )
        page = ctx.new_page()
        
        try:
            # Login
            print("Navigating to GHL...")
            page.goto('https://app.gohighlevel.com/', timeout=30000)
            page.wait_for_load_state('domcontentloaded')
            
            # Wait for React to render form
            print("Waiting for login form...")
            page.wait_for_selector('input[name="email"]', timeout=15000)
            page.wait_for_timeout(2000)
            page.screenshot(path=str(REPORT_DIR/'00_login_form_ready.png'))
            
            print("Filling login credentials...")
            page.fill('input[name="email"]', GHL_EMAIL)
            page.fill('input[name="password"]', GHL_PASSWORD)
            page.click('button[type="submit"]')
            
            # Wait for post-login redirect
            print("Waiting for post-login navigation...")
            page.wait_for_url('**/location/**', timeout=30000)
            page.wait_for_load_state('networkidle', timeout=20000)
            page.wait_for_timeout(3000)
            print(f"Logged in: {page.url}")
            page.screenshot(path=str(REPORT_DIR/'01_logged_in.png'))
            
            # Navigate to workflows
            wf_url = f'https://app.gohighlevel.com/location/{LOCATION_ID}/automation/workflows'
            print(f"Navigating to workflows at {wf_url}...")
            page.goto(wf_url, timeout=30000)
            
            # Wait for React to render workflows list
            print("Waiting for workflows to load...")
            page.wait_for_load_state('networkidle', timeout=20000)
            page.wait_for_timeout(5000)  # Extra wait for React hydration
            page.screenshot(path=str(REPORT_DIR/'02_workflows_loaded.png'), full_page=True)
            
            # Try to find workflow elements
            content = page.content()
            
            # Count key indicators
            draft_count = content.lower().count('draft')
            published_count = content.lower().count('published')
            workflow_count = content.lower().count('workflow')
            toggle_count = len(page.query_selector_all('[role="switch"], input[type="checkbox"]'))
            
            print(f"Drafts found: {draft_count}")
            print(f"Published: {published_count}")
            print(f"Workflow mentions: {workflow_count}")
            print(f"Toggle elements: {toggle_count}")
            
            # Try scrolling to load more
            page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
            page.wait_for_timeout(2000)
            page.screenshot(path=str(REPORT_DIR/'03_after_scroll.png'), full_page=True)
            
            # Try clicking "Draft" filter if exists
            try:
                draft_filter = page.query_selector('button:has-text("Draft")')
                if draft_filter:
                    draft_filter.click()
                    page.wait_for_timeout(2000)
                    page.screenshot(path=str(REPORT_DIR/'04_draft_filter.png'), full_page=True)
                    print("Clicked Draft filter")
            except Exception as e:
                print(f"No draft filter: {e}")
            
            # Try to find and click publish/activate buttons
            publish_btns = page.query_selector_all('button:has-text("Publish"), button:has-text("Activate"), button:has-text("Enable")')
            print(f"Publish buttons found: {len(publish_btns)}")
            
            activated = 0
            for btn in publish_btns[:10]:  # Activate up to 10
                try:
                    btn.scroll_into_view_if_needed()
                    btn.click()
                    page.wait_for_timeout(1000)
                    activated += 1
                    print(f"Activated workflow {activated}")
                except Exception as e:
                    print(f"Could not click: {e}")
            
            page.screenshot(path=str(REPORT_DIR/'05_final.png'), full_page=True)
            
            results = {
                'login': 'success',
                'drafts_on_page': draft_count,
                'published_on_page': published_count,
                'toggle_elements': toggle_count,
                'activated': activated,
                'screenshots': str(REPORT_DIR)
            }
            
            json.dump(results, open(REPORT_DIR/'results.json','w'), indent=2)
            print(f"\nResults: {json.dumps(results, indent=2)}")
            
        except Exception as e:
            print(f"Error: {e}")
            page.screenshot(path=str(REPORT_DIR/'error.png'))
            results = {
                'error': str(e),
                'screenshots': str(REPORT_DIR)
            }
            json.dump(results, open(REPORT_DIR/'results.json','w'), indent=2)
        
        finally:
            browser.close()

if __name__ == '__main__':
    run()
