
    >i'"                        d dl mZ d dlZd dlZd dlmZmZmZm	Z	 d dl
mZ erd dlmZ d dlmZ  ej                   e      Z edd      Z G d	 d
      Zy)    )annotationsN)TYPE_CHECKINGAnyOptionalUnion)	HTTPError)HeaderEntry)CookieParam   i  c                      e Zd ZdZ	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZedd       Zedd       Zedd       Zedd       Z	edd       Z
edd	       Zedd
       Zedd       ZddZddZy)Responsean  HTTP response object for browser-based fetch requests.

    This class provides a standardized interface for handling HTTP responses
    obtained through the browser's fetch API. It mimics the requests.Response
    interface while preserving all browser-specific metadata including cookies,
    headers, and network timing information.

    Key Features:
    - Compatible with requests.Response API for easy migration
    - Preserves both request and response headers for analysis
    - Automatic cookie extraction from Set-Cookie headers
    - Lazy JSON parsing with caching
    - Browser-context aware (respects CORS, security policies)
    - Content available in multiple formats (text, bytes, JSON)

    The response contains all data captured during the browser's fetch execution,
    including redirects, authentication flows, and any browser-applied transformations.
    Nc	                4   || _         || _        || _        || _        |xs g | _        |xs g | _        |xs g | _        || _        |t        v | _	        t        j                  d| d| dt        | j                         dt        | j                                y)a  Initialize a new Response instance with browser fetch results.

        Args:
            status_code: HTTP status code returned by the server (e.g., 200, 404, 500).
            content: Raw response body as bytes. Used for binary data or when
                text encoding is uncertain.
            text: Response body as decoded string. Pre-decoded by browser's fetch API.
            json: Pre-parsed JSON data if response Content-Type was application/json.
                If None, json() method will attempt to parse from text on demand.
            response_headers: Headers received from the server, including Set-Cookie,
                Content-Type, and any custom headers sent by the server.
            request_headers: Headers that were actually sent in the request, including
                browser-generated headers (User-Agent, Accept, etc.) and custom headers.
            cookies: Cookies extracted from Set-Cookie headers during the response.
                These represent new/updated cookies from this specific request.
            url: Final URL after any redirects. May differ from original request URL
                if the server performed redirects during the request.
        zResponse initialized: status=, url=z
, headers=z
, cookies=N)_status_code_content_text_json_response_headers_request_headers_cookies_urlSTATUS_CODE_RANGE_OK_okloggerdebuglen)	selfstatus_codecontenttextjsonresponse_headersrequest_headerscookiesurls	            f/var/www/python/tenders/Scrapper/venv/lib/python3.12/site-packages/pydoll/browser/requests/response.py__init__zResponse.__init__&   s    : (

!1!7R / 522	"66+K=se D41123:c$-->P=QS	
    c                    | j                   S )a>  Check if the request was successful (2xx status codes).

        Returns:
            True if status code is in the 200-399 range, False otherwise.

        Note:
            This follows HTTP conventions where 2xx codes indicate success
            and 3xx codes indicate redirection (still considered "ok").
        )r   r   s    r&   okzResponse.okQ   s     xxr(   c                    | j                   S )a  Get cookies that were set by the server during this response.

        Returns:
            List of cookies extracted from Set-Cookie headers. Each cookie
            contains name and value, with cookie attributes (Path, Domain, etc.)
            automatically handled by the browser.

        Note:
            These are only NEW/UPDATED cookies from this response. Existing
            browser cookies are managed automatically by the browser context.
        )r   r*   s    r&   r$   zResponse.cookies^   s     }}r(   c                    | j                   S )a  Get headers that were actually sent in the HTTP request.

        Returns:
            List of headers sent to the server, including both custom headers
            provided by the user and automatic headers added by the browser
            (User-Agent, Accept, Authorization, etc.).

        Note:
            This shows the ACTUAL headers sent, which may differ from what
            was originally specified due to browser modifications.
        )r   r*   s    r&   r#   zResponse.request_headersm   s     $$$r(   c                    | j                   S )a  Get headers received from the server in the HTTP response.

        Returns:
            List of response headers sent by the server, including standard
            headers (Content-Type, Content-Length, etc.) and any custom headers.

        Note:
            Some security-sensitive headers may be filtered by the browser
            and not appear in this list due to CORS policies.
        )r   r*   s    r&   headerszResponse.headers|   s     %%%r(   c                    | j                   S )zGet the HTTP status code returned by the server.

        Returns:
            Integer status code (e.g., 200 for OK, 404 for Not Found, 500 for Server Error).
        )r   r*   s    r&   r   zResponse.status_code   s        r(   c                    | j                   s.| j                  r"| j                  j                  dd      | _         | j                   S )aZ  Get the response content as a decoded string.

        Returns:
            Response body decoded as UTF-8 string. If no text was provided
            during initialization, it will be decoded from the raw content.

        Note:
            Decoding uses 'replace' error handling to avoid crashes on
            invalid UTF-8 sequences.
        zutf-8replace)errors)r   r   decoder*   s    r&   r    zResponse.text   s6     zzdll,,WY,GDJzzr(   c                    | j                   S )zGet the raw response content as bytes.

        Returns:
            Unmodified response body as bytes. Useful for binary data
            (images, files, etc.) or when you need to handle encoding manually.
        )r   r*   s    r&   r   zResponse.content   s     }}r(   c                    | j                   S )zGet the final URL of the response after any redirects.

        Returns:
            The final URL that was accessed, which may differ from the
            original request URL if redirects occurred.
        )r   r*   s    r&   r%   zResponse.url   s     yyr(   c                   | j                   | j                   S 	 t        j                  | j                        | _         | j                   S # t        j                  $ r&}t
        j                  d       t        d      |d}~ww xY w)a~  Parse and return the response content as JSON data.

        Attempts to parse the response text as JSON. Uses caching to avoid
        re-parsing the same content multiple times.

        Returns:
            Parsed JSON data as dictionary, list, or other JSON-compatible type.

        Raises:
            ValueError: If the response content is not valid JSON or if parsing fails.

        Note:
            - Uses lazy parsing: JSON is only parsed when first accessed
            - Subsequent calls return cached result for better performance
            - If JSON was pre-parsed during initialization, that result is returned
        Nz!Failed to decode response as JSONzResponse is not valid JSON)r   jsonlibloadsr    JSONDecodeErrorr   r   
ValueError)r   excs     r&   r!   zResponse.json   so    " ::!::	D tyy1DJ::&& 	DLL<=9:C	Ds   /A
 
B!A>>Bc                    | j                   t        vrSt        j                  d| j                    d| j                          t        | j                    d| j                         y)a  Raise an HTTPError if the response indicates an HTTP error status.

        Checks the status code and raises an exception for client errors (4xx)
        and server errors (5xx). Successful responses (2xx) and redirects (3xx)
        do not raise an exception.

        Raises:
            HTTPError: If status code is 400 or higher, indicating an error.

        Note:
            This method is compatible with requests.Response.raise_for_status()
            for easy migration from the requests library.
        z&HTTP error status encountered: status=r   z Client Error: for url N)r   r   r   errorr   r   r*   s    r&   raise_for_statuszResponse.raise_for_status   sg     #77LL89I9I8J&QUQZQZP[\ t//00G		{STT	 8r(   )r(    NNNNr@   )r   intr   bytesr    strr!   zOptional[dict[str, Any]]r"   Optional[list[HeaderEntry]]r#   rD   r$   zOptional[list[CookieParam]]r%   rC   )returnbool)rE   zlist[CookieParam])rE   zlist[HeaderEntry])rE   rA   )rE   rC   )rE   rB   )rE   zUnion[dict[str, Any], list])rE   None)__name__
__module____qualname____doc__r'   propertyr+   r$   r#   r/   r   r    r   r%   r!   r?    r(   r&   r   r      s   , )-8<7;/3)
)
 )
 	)

 ')
 6)
 5)
 -)
 )
V 
 
   % % & & ! !      D6Ur(   r   )
__future__r   r!   r8   loggingtypingr   r   r   r   pydoll.exceptionsr   pydoll.protocol.fetch.typesr	   pydoll.protocol.network.typesr
   	getLoggerrH   r   ranger   r   rM   r(   r&   <module>rV      sL    "   6 6 '79			8	$S# RU RUr(   