from typing import Any, Dict, List, Optional


class RequestInfo:
    def __init__(self, request):
        """
        Wrap a Playwright request object to expose useful fields.
        """
        self.url: str = request.url
        self.method: str = request.method
        self.type: str = request.resource_type
        self.request_headers: Dict[str, str] = request.headers
        self.request_id: Optional[str] = getattr(request, "_request_id", None)
        self.frame_id: Optional[str] = getattr(request.frame, "name", None) if getattr(request, "frame", None) else None
        parent_frame = None
        if getattr(request, "frame", None) and getattr(request.frame, "parent_frame", None):
            parent_frame = getattr(request.frame.parent_frame, "name", None)
        self.parent_frame_id: Optional[str] = parent_frame
        self.initiator: Optional[Any] = getattr(request, "_initiator", None)
        self.timestamp: float = getattr(request, "_timestamp", 0.0)
        self.source: Optional[str] = getattr(request, "_source", None)

    # -----------------------------
    # Headers helpers
    # -----------------------------
    def get_referer(self) -> Optional[str]:
        return self.request_headers.get("referer") or self.request_headers.get("Referer")

    def is_referred(self) -> bool:
        return "referer" in self.request_headers or "Referer" in self.request_headers

    # -----------------------------
    # Filtering helpers
    # -----------------------------
    def is_filtered(self, filter_obj: Optional[Dict[str, Dict[str, bool]]]) -> bool:
        """
        Example filter_obj format:
        {
            "type": {"xhr": True, "document": True},
            "method": {"GET": True, "POST": True}
        }
        """
        if filter_obj is None:
            return True
        type_match = filter_obj.get("type", {}).get(self.type, False)
        method_match = filter_obj.get("method", {}).get(self.method, False)
        return type_match and method_match

    def __repr__(self):
        return f"<RequestInfo url={self.url} type={self.type} method={self.method} referer={self.get_referer()}>"
