from playwright.sync_api import Page, Response
from pwauto.utils.logger import logger
from pwauto.utils.config import config


class BasePage:
    """
    所有页面对象的基类（Base Page Object）
    封装了 Playwright 的原生操作，加入了日志、重试和统一配置。
    """

    def __init__(self, page: Page):
        self.page = page
        self.logger = logger

    def navigate(self, path: str = "") -> Response:
        """
        导航到指定路径。
        自动拼接 config.BASE_URL，只需要传相对路径即可。
        """
        url = f"{config.BASE_URL}{path}"
        self.logger.info(f"Navigating to: {url}")
        return self.page.goto(url, timeout=config.TIMEOUT)

    def click(self, selector: str, name: str = None):
        """
        点击元素，带有自动日志记录。
        :param name: 给元素起个可读的名字，方便日志展示（如：'登录按钮'）
        """
        element_label = name if name else selector
        self.logger.info(f"Clicking: [{element_label}]")
        try:
            self.page.click(selector, timeout=config.TIMEOUT)
        except Exception as e:
            self.logger.error(f"Clicking [{element_label}] failed! Error: {e}")
            raise

    def fill(self, selector: str, value: str, name: str = None, ignore_sensitive: bool = False):
        """
        在输入框填入内容，日志自动隐藏敏感信息。
        :param ignore_sensitive: 是否忽略敏感信息，默认不忽略
        """
        element_label = name if name else selector
        value_mask = "********" if ignore_sensitive else value
        self.logger.info(f"Filling: [{element_label}] -> {value_mask}")
        self.page.fill(selector, value, timeout=config.TIMEOUT)

    def get_text(self, selector: str) -> str:
        """获取元素文本内容"""
        text = self.page.inner_text(selector, timeout=config.TIMEOUT)
        self.logger.debug(f"Getting text: [{selector}] -> '{text}'")
        return text

    def wait_for_load(self):
        """等待页面网络完全空闲（强力加载等待）"""
        self.page.wait_for_load_state("networkidle")