import os
import time
from appium.webdriver.webdriver import WebDriver
from typing import Dict, List, Any

class HelperUtils:
    """Helper utilities for Appium actions and screenshots."""

    SCREENSHOT_FOLDER = os.path.join("reports", "screenshots")
    DEFAULT_LOCATOR = "unknown"
    DEFAULT_VALUE = "no_value"
    DEFAULT_ACTION = "unknown"

    @staticmethod
    def get_element_details(driver: WebDriver) -> List[Dict[str, Any]]:
        """Return a list of dictionaries with text, resource-id, and content-desc for all elements."""
        elements_info = []

        try:
            all_elements = driver.find_elements_by_xpath("//*")
            for element in all_elements:
                try:
                    text = element.text
                    resource_id = element.get_attribute("resource-id")
                    content_desc = element.get_attribute("content-desc")

                    if text or resource_id or content_desc:
                        elements_info.append({
                            "text": text,
                            "resource-id": resource_id,
                            "content-desc": content_desc
                        })
                except Exception:
                    continue
        except Exception as e:
            print(f"Error collecting element details: {e}")

        return elements_info

    @staticmethod
    def get_screenshot_path(action: Dict[str, Any]) -> str:
        """Return a screenshot file path based on current timestamp and action."""
        timestamp = time.strftime("%Y%m%d-%H%M%S")
        os.makedirs(HelperUtils.SCREENSHOT_FOLDER, exist_ok=True)

        locator = action.get("locator", HelperUtils.DEFAULT_LOCATOR)
        value = action.get("value", HelperUtils.DEFAULT_VALUE).replace("/", "_").replace(":", "_")
        action_type = action.get("action", HelperUtils.DEFAULT_ACTION)

        filename = f"{timestamp}_{action_type}_{locator}_{value}.png"
        return os.path.join(HelperUtils.SCREENSHOT_FOLDER, filename)


__all__ = ["HelperUtils"]
