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

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


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


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(SCREENSHOT_FOLDER, exist_ok=True)

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

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