import time
import logging


def _scroll_to_top() -> None:
    """Scroll to the top of the page using keyboard and wheel as fallback."""
    try:
        import pyautogui as _pg
        # Primary: Ctrl+Home reaches very top in most apps/browsers
        try:
            _pg.hotkey('ctrl', 'home')
            time.sleep(0.2)
        except Exception:
            pass
        # Secondary: press Home as additional nudge
        try:
            _pg.press('home')
            time.sleep(0.1)
        except Exception:
            pass
        # Fallback: a few strong wheel scroll ups
        try:
            for _ in range(6):
                _pg.scroll(800)  # positive -> up
                time.sleep(0.05)
        except Exception:
            pass
    except Exception:
        pass


def navigate_home_via_rekognition(app) -> bool:
    """Try to navigate back to Home/Dashboard by finding a button via AWS Rekognition.

    Steps:
    1) Scroll to the top of the page to maximize chance the button is visible.
    2) Capture a full-resolution screenshot using the app's analyzer if available.
    3) Search for common Home/Dashboard labels via Rekognition and click the first match.

    Returns True if a click was performed, False otherwise.
    """
    try:
        import pyautogui as _pg
        from .openai_analyzer import OpenAIAnalyzer
    except Exception:
        return False

    try:
        _scroll_to_top()

        # Acquire analyzer
        analyzer = getattr(app, 'screenshot_manager', None)
        analyzer = analyzer.openai_analyzer if analyzer else OpenAIAnalyzer(app)

        # Capture screenshot
        screenshot_path = analyzer.capture_full_resolution_screenshot()
        if not screenshot_path:
            return False

        # Prefer Rekognition-based search for robustness
        labels = [
            'Home', 'HOME', 'home',
            'Dashboard', 'DASHBOARD', 'dashboard',
        ]

        target_coords = None
        for label in labels:
            try:
                coords = analyzer.find_text_coordinates_rekognition(screenshot_path, label)
            except Exception:
                coords = None
            if coords and len(coords) == 2 and all(isinstance(c, (int, float)) for c in coords):
                target_coords = (int(coords[0]), int(coords[1]))
                try:
                    logging.info(f"[Recovery] Rekognition found '{label}' at {target_coords}")
                except Exception:
                    pass
                break

        if not target_coords:
            return False

        x, y = target_coords
        # Move and click the target
        try:
            _pg.moveTo(x, y, duration=0.35)
            _pg.click(x, y)
            # Allow page to load/navigate
            time.sleep(2.0)
            return True
        except Exception:
            return False
    except Exception:
        return False


