#!/usr/bin/env python3
"""GHL automation using saved session cookies - bypasses login bot detection"""
import os, sys, json, time
from pathlib import Path
from datetime import datetime

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

COOKIE_FILE = Path('/mnt/e/genesis-system/.ghl_session_cookies.json')
LOCATION_ID = 'SWdaQpAVAtRigYcMfder'
REPORT_DIR = Path(f'/mnt/e/genesis-system/reports/ghl_cookies_{datetime.now().strftime("%H%M%S")}')
REPORT_DIR.mkdir(parents=True, exist_ok=True)

def run():
    if not COOKIE_FILE.exists():
        print(f"ERROR: Cookie file not found at {COOKIE_FILE}")
        print("Follow /mnt/e/genesis-system/scripts/ghl_cookie_capture.md to set up")
        return False
    
    cookies = json.loads(COOKIE_FILE.read_text())
    
    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/121.0.0.0 Safari/537.36'
        )
        
        # Inject saved cookies
        # Handle both Cookie Editor format and plain format
        if isinstance(cookies, list) and cookies:
            for c in cookies:
                try:
                    cookie = {
                        'name': c.get('name',''),
                        'value': c.get('value',''),
                        'domain': c.get('domain', '.gohighlevel.com'),
                        'path': c.get('path', '/'),
                    }
                    if c.get('secure'): cookie['secure'] = True
                    ctx.add_cookies([cookie])
                except Exception as e:
                    pass
        
        page = ctx.new_page()
        page.set_default_timeout(20000)
        
        # Go directly to workflows (no login needed with cookies)
        wf_url = f'https://app.gohighlevel.com/location/{LOCATION_ID}/automation/workflows'
        page.goto(wf_url, timeout=30000)
        page.wait_for_load_state('networkidle', timeout=20000)
        page.wait_for_timeout(5000)
        page.screenshot(path=str(REPORT_DIR/'01_workflows.png'), full_page=True)
        
        print(f"URL: {page.url}")
        
        # Find and activate draft workflows
        activated = 0
        content = page.content()
        draft_count = content.lower().count('draft')
        print(f"Draft mentions: {draft_count}")
        
        # Try to click publish buttons
        for selector in ['button:has-text("Publish")', 'button:has-text("Activate")', '[data-testid="toggle"]']:
            btns = page.query_selector_all(selector)
            for btn in btns[:5]:
                try:
                    btn.click()
                    time.sleep(0.5)
                    activated += 1
                except:
                    pass
        
        page.screenshot(path=str(REPORT_DIR/'02_final.png'), full_page=True)
        print(f"Activated: {activated}")
        browser.close()
        return activated

if __name__ == '__main__':
    run()
