#!/usr/bin/env python3
"""
REAL Gemini Deep Think Workflow Script
Uses existing Chrome profile to access gemini.google.com
"""

import os
import sys
import time
from datetime import datetime
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError

SCREENSHOTS_DIR = "/mnt/e/genesis-system/deep_think_results/screenshots"
CHROME_USER_DATA = "/mnt/c/Users/P3/AppData/Local/Google/Chrome/User Data"
CHROME_PROFILE = "Default"

os.makedirs(SCREENSHOTS_DIR, exist_ok=True)

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

def wait_and_screenshot(page, name, wait_ms=2000):
    time.sleep(wait_ms / 1000)
    return screenshot(page, name)

def run():
    print("=" * 60)
    print("GEMINI DEEP THINK BROWSER AUTOMATION")
    print(f"Started: {datetime.now().isoformat()}")
    print("=" * 60)

    with sync_playwright() as p:
        print("\n[STEP 1] Launching Chrome with existing user profile...")

        try:
            # Try launching with persistent context (uses real Chrome profile)
            browser = p.chromium.launch_persistent_context(
                user_data_dir=CHROME_USER_DATA,
                channel="chrome",  # Use real Chrome not Chromium
                headless=False,    # Must be visible for real Chrome profile
                slow_mo=500,
                args=[
                    f"--profile-directory={CHROME_PROFILE}",
                    "--no-first-run",
                    "--disable-blink-features=AutomationControlled",
                ]
            )
            print("[OK] Chrome launched with persistent context")
            page = browser.pages[0] if browser.pages else browser.new_page()
        except Exception as e:
            print(f"[WARN] Chrome launch with profile failed: {e}")
            print("[FALLBACK] Trying Chromium without profile...")
            browser_obj = p.chromium.launch(headless=False, slow_mo=300)
            browser = browser_obj
            page = browser.new_page()

        try:
            print("\n[STEP 1] Navigating to gemini.google.com...")
            page.goto("https://gemini.google.com", timeout=30000)
            time.sleep(4)
            screenshot(page, "01_initial_load")

            current_url = page.url
            print(f"[URL] Current URL: {current_url}")
            page_title = page.title()
            print(f"[TITLE] Page title: {page_title}")

            # Check login state
            if "accounts.google.com" in current_url or "signin" in current_url.lower():
                print("\n[STEP 2] NOT LOGGED IN - redirected to Google login")
                screenshot(page, "02_login_page")
                print("[INFO] Login required. Cannot auto-login per protocol.")
                print("[INFO] Please log in manually and re-run this script.")
                return {"status": "needs_login", "url": current_url}

            # Check if we're on Gemini
            if "gemini.google.com" in current_url:
                print("[OK] On Gemini - checking login state...")
                screenshot(page, "02_gemini_page")

                # Look for login indicators
                page_content = page.content()

                # Check for common logged-in indicators
                logged_in_indicators = [
                    page.locator('[data-test-id="profile-icon"]').count() > 0,
                    page.locator('[aria-label="Google Account"]').count() > 0,
                    page.locator('img[alt*="profile"]').count() > 0,
                ]

                logged_out_indicators = [
                    page.locator('text=Sign in').count() > 0,
                    "Sign in" in page.content(),
                ]

                print(f"[CHECK] Logged-in indicators: {logged_in_indicators}")
                print(f"[CHECK] Logged-out indicators: {logged_out_indicators}")

            print("\n[STEP 3] Analyzing Gemini UI structure...")
            time.sleep(3)
            screenshot(page, "03_gemini_ui_full")

            # Get page structure
            print("[INFO] Looking for sidebar elements...")

            # Try to find sidebar / left panel
            sidebar_selectors = [
                '[data-test-id="sidebar"]',
                '.sidebar',
                'nav',
                '[role="navigation"]',
                '[aria-label="Main menu"]',
                '.side-nav',
                'mat-sidenav',
            ]

            for sel in sidebar_selectors:
                count = page.locator(sel).count()
                if count > 0:
                    print(f"[FOUND] Sidebar selector '{sel}': {count} elements")

            # Look for model selector
            print("\n[INFO] Looking for model selector...")
            model_selectors = [
                '[data-test-id="model-selector"]',
                '[aria-label*="model"]',
                '[aria-label*="Model"]',
                'button:has-text("Gemini")',
                'button:has-text("2.5")',
                'button:has-text("Pro")',
                '[class*="model"]',
                'mat-select',
            ]

            for sel in model_selectors:
                try:
                    count = page.locator(sel).count()
                    if count > 0:
                        print(f"[FOUND] Model selector '{sel}': {count} elements")
                        elem = page.locator(sel).first
                        print(f"  Text: {elem.text_content()[:100] if elem.text_content() else 'N/A'}")
                except Exception as e:
                    pass

            # Look for Deep Think / thinking mode
            print("\n[INFO] Looking for Deep Think option...")
            deep_think_selectors = [
                'button:has-text("Deep Think")',
                '[aria-label*="Deep Think"]',
                '[aria-label*="Think"]',
                'text=Deep Think',
                '[data-test-id*="think"]',
                '[class*="think"]',
                'button:has-text("Think")',
            ]

            for sel in deep_think_selectors:
                try:
                    count = page.locator(sel).count()
                    if count > 0:
                        print(f"[FOUND] Deep Think selector '{sel}': {count} elements")
                        elem = page.locator(sel).first
                        print(f"  Text: {elem.text_content()[:100] if elem.text_content() else 'N/A'}")
                except Exception as e:
                    pass

            # Screenshot the full page with scroll
            print("\n[INFO] Taking full page screenshots...")
            page.evaluate("window.scrollTo(0, 0)")
            screenshot(page, "04_top_of_page")

            # Get all visible text to understand the page structure
            visible_text = page.evaluate("""
                () => {
                    const elements = document.querySelectorAll('button, [role="button"], a, [role="menuitem"]');
                    return Array.from(elements).slice(0, 50).map(el => ({
                        tag: el.tagName,
                        text: el.textContent?.trim()?.substring(0, 100),
                        aria: el.getAttribute('aria-label'),
                        class: el.className?.substring(0, 100),
                        id: el.id
                    }));
                }
            """)

            print("\n[INFO] Visible interactive elements:")
            for elem in visible_text[:30]:
                if elem.get('text') or elem.get('aria'):
                    print(f"  [{elem['tag']}] text='{elem.get('text', '')}' aria='{elem.get('aria', '')}' id='{elem.get('id', '')}'")

            # Try to find and click model selector to see options
            print("\n[STEP 3b] Trying to access model selector...")
            try:
                # Common Gemini model button location
                model_btn = page.locator('button').filter(has_text="2.5").first
                if model_btn.count() > 0:
                    print("[OK] Found model button with '2.5'")
                    screenshot(page, "05_before_model_click")
                    model_btn.click()
                    time.sleep(2)
                    screenshot(page, "06_model_dropdown_open")
                else:
                    # Try generic model area
                    selectors_to_try = [
                        'button[jsname]',
                        '[data-test-id="bard-mode-selector"]',
                        '.model-selector',
                    ]
                    for sel in selectors_to_try:
                        elems = page.locator(sel).all()
                        for elem in elems[:5]:
                            txt = elem.text_content() or ""
                            if any(x in txt for x in ['Gemini', 'Pro', 'Flash', 'Ultra', 'model']):
                                print(f"[FOUND] Model-related element: {txt[:50]}")
            except Exception as e:
                print(f"[WARN] Model selector interaction failed: {e}")

            screenshot(page, "07_current_state")

            print("\n[STEP 4] Attempting to find chat input and Deep Think toggle...")

            # Find the chat input area
            input_selectors = [
                'textarea[placeholder*="message"]',
                'textarea[placeholder*="Enter"]',
                'textarea[placeholder*="Ask"]',
                'div[contenteditable="true"]',
                'rich-textarea',
                '[data-test-id="user-input"]',
                'textarea',
            ]

            input_found = False
            for sel in input_selectors:
                count = page.locator(sel).count()
                if count > 0:
                    print(f"[FOUND] Chat input '{sel}': {count} elements")
                    input_found = True
                    break

            # Look for deep think button near input area
            print("\n[INFO] Looking for Deep Think toggle near input area...")
            bottom_area = page.evaluate("""
                () => {
                    // Get all elements in bottom 30% of page
                    const height = window.innerHeight;
                    const elements = document.querySelectorAll('button, [role="button"], [role="switch"], [role="checkbox"]');
                    return Array.from(elements)
                        .filter(el => {
                            const rect = el.getBoundingClientRect();
                            return rect.top > height * 0.6;
                        })
                        .slice(0, 30)
                        .map(el => ({
                            tag: el.tagName,
                            text: el.textContent?.trim()?.substring(0, 100),
                            aria: el.getAttribute('aria-label'),
                            class: el.className?.substring(0, 100),
                        }));
                }
            """)

            print("[INFO] Bottom area elements:")
            for elem in bottom_area:
                if elem.get('text') or elem.get('aria'):
                    print(f"  [{elem['tag']}] text='{elem.get('text', '')}' aria='{elem.get('aria', '')}'")

            screenshot(page, "08_bottom_area")

            # Now attempt the actual workflow
            print("\n[STEP 5] Attempting Deep Think workflow...")

            # Step 5a: Find model selector and switch to 2.5 Pro
            print("[5a] Looking for model selector button...")

            # Gemini typically has a model selector in the top bar or near input
            page_html_snippet = page.evaluate("""
                () => document.querySelector('header')?.innerHTML?.substring(0, 2000) ||
                      document.querySelector('.app-header')?.innerHTML?.substring(0, 2000) ||
                      'no header found'
            """)
            print(f"[HTML] Header snippet: {page_html_snippet[:500]}")

            screenshot(page, "09_pre_workflow")

            print("\n[STEP 5b] Attempting to find and click Deep Think mode...")

            # Try clicking on the thinking/model area
            # Gemini UI often has a button at bottom left of input area
            deep_think_attempt_selectors = [
                '[aria-label*="Deep Think"]',
                '[aria-label*="think"]',
                'button:has-text("Deep Think")',
                '[data-test-id*="deep"]',
                'button:has-text("1.5")',  # old model buttons
                'button:has-text("Advanced")',
                'mat-slide-toggle',
                '[role="switch"]',
            ]

            deep_think_found = False
            for sel in deep_think_attempt_selectors:
                try:
                    count = page.locator(sel).count()
                    if count > 0:
                        print(f"[FOUND] Potential Deep Think: '{sel}' ({count} elements)")
                        elem = page.locator(sel).first
                        print(f"  Text: '{elem.text_content()[:100] if elem.text_content() else ''}'")
                        deep_think_found = True
                except Exception as e:
                    pass

            if not deep_think_found:
                print("[INFO] Deep Think not found via direct selectors - doing full DOM scan...")
                all_interactive = page.evaluate("""
                    () => {
                        const els = document.querySelectorAll('[role="button"], button, [role="switch"], [role="checkbox"], [role="menuitem"]');
                        return Array.from(els).map(el => ({
                            text: el.textContent?.trim()?.substring(0, 80),
                            aria: el.getAttribute('aria-label'),
                            role: el.getAttribute('role'),
                            class: el.className?.substring(0, 80),
                        })).filter(el => el.text || el.aria);
                    }
                """)

                print(f"[INFO] Total interactive elements: {len(all_interactive)}")
                for elem in all_interactive:
                    txt = (elem.get('text') or '').lower()
                    aria = (elem.get('aria') or '').lower()
                    if any(x in txt + aria for x in ['deep', 'think', 'pro', '2.5', 'model', 'ultra', 'reason']):
                        print(f"  RELEVANT: text='{elem.get('text', '')}' aria='{elem.get('aria', '')}'")

            # Final state screenshot
            screenshot(page, "10_final_state")

            # Try to interact with the chat - send test message if input found
            if input_found:
                print("\n[STEP 6] Attempting to send test prompt...")
                test_prompt = "What is the single most important strategic decision for a new AI voice widget product targeting Australian digital agencies in 2026?"

                try:
                    # Try textarea first
                    textarea = page.locator('textarea').first
                    if textarea.count() > 0:
                        textarea.click()
                        time.sleep(0.5)
                        textarea.fill(test_prompt)
                        time.sleep(1)
                        screenshot(page, "11_prompt_entered")

                        # Try to submit with Enter
                        textarea.press("Enter")
                        print("[OK] Prompt submitted via Enter key")
                        time.sleep(5)
                        screenshot(page, "12_after_submit")

                        # Wait for response (up to 120 seconds)
                        print("[WAIT] Waiting for Deep Think response (up to 120s)...")
                        for i in range(24):  # 24 x 5s = 120s
                            time.sleep(5)
                            screenshot(page, f"13_response_progress_{i:02d}")

                            # Check if still loading
                            loading = page.locator('[aria-label*="loading"], .loading, [class*="loading"]').count()
                            if loading == 0 and i > 3:
                                print(f"[OK] Response appears complete after {(i+1)*5}s")
                                break

                        # Get response text
                        response_selectors = [
                            '[data-test-id="response-container"]',
                            '.response-content',
                            'model-response',
                            '[class*="response"]',
                            'message-content',
                        ]

                        response_text = ""
                        for sel in response_selectors:
                            elems = page.locator(sel).all()
                            if elems:
                                response_text = "\n".join([e.text_content() or "" for e in elems[-3:]])
                                if response_text.strip():
                                    print(f"[OK] Got response via '{sel}'")
                                    break

                        if not response_text:
                            # Fallback - get all text from main content area
                            response_text = page.evaluate("""
                                () => {
                                    const main = document.querySelector('main') || document.body;
                                    return main.innerText?.substring(0, 5000);
                                }
                            """)

                        print(f"\n[RESPONSE PREVIEW]\n{response_text[:500]}...")

                        screenshot(page, "14_final_response")

                        return {
                            "status": "success",
                            "response_text": response_text,
                        }

                except Exception as e:
                    print(f"[ERROR] Failed to send prompt: {e}")
                    screenshot(page, "11_input_error")

            print("\n[INFO] Generating workflow documentation...")

            # Collect all screenshots taken
            screenshots = sorted([f for f in os.listdir(SCREENSHOTS_DIR) if f.endswith('.png')])
            print(f"[INFO] Screenshots taken: {len(screenshots)}")
            for s in screenshots:
                print(f"  - {s}")

            return {
                "status": "partial",
                "screenshots": screenshots,
                "message": "UI analyzed but workflow may need adjustment"
            }

        except Exception as e:
            print(f"[ERROR] Main execution failed: {e}")
            import traceback
            traceback.print_exc()
            try:
                screenshot(page, "ERROR_state")
            except:
                pass
            return {"status": "error", "error": str(e)}

        finally:
            print("\n[INFO] Closing browser...")
            browser.close()

if __name__ == "__main__":
    result = run()
    print(f"\n[RESULT] {result}")
