"""
安全辅助类
整合 security 子模块，提供统一访问入口
"""
from typing import Callable, Optional
from playwright.async_api import Page

from ..security import (
    SecurityScanner,
    XSSDetector,
    XSSConfig,
    HeaderChecker,
    HeaderCheckConfig,
)


class SecurityHelper:
    """
    安全辅助类
    整合 security 子模块

    使用方式:
        browser.security.scanner  # SecurityScanner
        browser.security.xss      # XSSDetector
        browser.security.header   # HeaderChecker
    """

    def __init__(self, get_page: Callable[[], Page]):
        """
        初始化安全辅助类

        Args:
            get_page: 获取当前 Page 对象的回调函数
        """
        self._get_page = get_page
        self._scanner: Optional[SecurityScanner] = None
        self._xss: Optional[XSSDetector] = None
        self._header: Optional[HeaderChecker] = None
        self._xss_config: Optional[XSSConfig] = None
        self._header_config: Optional[HeaderCheckConfig] = None

    @property
    def scanner(self) -> SecurityScanner:
        """
        获取安全扫描器

        Returns:
            SecurityScanner: 安全扫描器实例
        """
        if self._scanner is None:
            self._scanner = SecurityScanner(self._get_page())
        return self._scanner

    @property
    def xss(self) -> XSSDetector:
        """
        获取 XSS 检测器

        Returns:
            XSSDetector: XSS 检测器实例
        """
        if self._xss is None:
            self._xss = XSSDetector(self._get_page(), self._xss_config)
        return self._xss

    @property
    def header(self) -> HeaderChecker:
        """
        获取 Header 检查器

        Returns:
            HeaderChecker: Header 检查器实例
        """
        if self._header is None:
            self._header = HeaderChecker(self._get_page(), self._header_config)
        return self._header

    def set_xss_config(self, config: XSSConfig):
        """设置 XSS 检测配置"""
        self._xss_config = config
        self._xss = None

    def set_header_config(self, config: HeaderCheckConfig):
        """设置 Header 检查配置"""
        self._header_config = config
        self._header = None

    def reset(self):
        """
        重置所有实例
        当切换标签页时调用，确保使用正确的 Page 对象
        """
        self._scanner = None
        self._xss = None
        self._header = None
