#!/usr/bin/env python3
"""Find the actual XPaths for Google Maps detail panel."""
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(
        headless=True,
        args=["--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-gpu"]
    )
    page = browser.new_page(
        viewport={"width": 1920, "height": 1080},
        user_agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
        locale="en-IN",
        timezone_id="Asia/Kolkata",
    )
    
    page.goto("https://www.google.com/maps/search/interior+designers+in+Hayathnagar/", timeout=30000)
    page.wait_for_timeout(6000)
    
    # Scroll to load
    for _ in range(3):
        page.evaluate("document.querySelector('[role=\"feed\"]')?.scrollBy(0, 1000)")
        page.wait_for_timeout(2000)
    
    # Click first result
    try:
        link = page.locator('a[href*="maps/place"]').first
        link.click(timeout=10000)
        page.wait_for_timeout(4000)
        
        # Analyze the panel structure
        info = page.evaluate("""
            () => {
                const result = {};
                
                // Get the details panel (the sidebar)
                const sidePanel = document.querySelector('[role="main"] > div > div');
                if (!sidePanel) {
                    // Try the whole page
                    result.error = 'no side panel found';
                    result.bodyClasses = document.body.className.substring(0, 200);
                    return result;
                }
                
                result.panel_html = sidePanel.innerHTML.substring(0, 3000);
                
                // Get all text
                result.all_text = sidePanel.innerText.substring(0, 2000);
                
                // Find phone numbers in text
                const text = sidePanel.innerText;
                const phones = text.match(/[6-9][0-9]{9}|\\+91[\\s-]?[0-9]{10}/g);
                result.phones_found = phones || [];
                
                // Find clickable elements and buttons
                const buttons = sidePanel.querySelectorAll('button, a');
                const btn_info = [];
                buttons.forEach(b => {
                    const dataItemId = b.getAttribute('data-item-id') || '';
                    const href = b.href || '';
                    const ariaLabel = b.getAttribute('aria-label') || '';
                    const cls = b.className.substring(0, 60);
                    btn_info.push({
                        data_item_id: dataItemId.substring(0, 60),
                        href: href.substring(0, 100),
                        aria_label: ariaLabel.substring(0, 80),
                        cls: cls,
                        text: b.innerText.substring(0, 40),
                    });
                });
                result.buttons = btn_info;
                
                return result;
            }
        """)
        
        print("=== ALL TEXT ===")
        print(info.get('all_text', '')[:1500])
        
        print("\n=== BUTTONS / LINKS ===")
        for b in info.get('buttons', []):
            print(f"  data-item-id: {b['data_item_id']}")
            print(f"  href: {b['href']}")
            print(f"  label: {b['aria_label']}")
            print(f"  text: {b['text']}")
            print(f"  class: {b['cls']}")
            print()
        
        if 'phones_found' in info:
            print(f"\n=== PHONES IN TEXT: {info.get('phones_found', [])} ===")
        
        if 'error' in info:
            print(f"ERROR: {info.get('error')}")
            print(f"Body classes: {info.get('bodyClasses')}")
            
    except Exception as e:
        print(f"Click failed: {e}")

    browser.close()
