# AUTO-GENERATED FILE - DO NOT EDIT
# This file was automatically generated by the XDK build tool.
# Any manual changes will be overwritten on the next generation.

"""
Auto-generated news client for the X API.

This module provides a client for interacting with the news endpoints of the X API.

All methods, parameters, and response models are generated from the OpenAPI specification.

Generated automatically - do not edit manually.
"""

from __future__ import annotations
from typing import Dict, List, Optional, Any, Union, cast, TYPE_CHECKING
import requests
import time


if TYPE_CHECKING:
    from ..client import Client
from .models import (
    SearchResponse,
    GetResponse,
)


class NewsClient:
    """Client for news operations"""


    def __init__(self, client: Client):
        self.client = client


    def search(
        self,
        query: str,
        max_results: int = None,
        max_age_hours: int = None,
        news_fields: List = None,
    ) -> SearchResponse:
        """
        Search News
        Retrieves a list of News stories matching the specified search query.
        Args:
            query: The search query.
            max_results: The number of results to return.
            max_age_hours: The maximum age of the News story to search for.
            news_fields: A comma separated list of News fields to display.
            Returns:
            SearchResponse: Response data
        """
        url = self.client.base_url + "/2/news/search"
        if self.client.bearer_token:
            self.client.session.headers["Authorization"] = (
                f"Bearer {self.client.bearer_token}"
            )
        elif self.client.access_token:
            self.client.session.headers["Authorization"] = (
                f"Bearer {self.client.access_token}"
            )
        # Ensure we have a valid access token
        if self.client.oauth2_auth and self.client.token:
            # Check if token needs refresh
            if self.client.is_token_expired():
                self.client.refresh_token()
        params = {}
        if query is not None:
            params["query"] = query
        if max_results is not None:
            params["max_results"] = max_results
        if max_age_hours is not None:
            params["max_age_hours"] = max_age_hours
        if news_fields is not None:
            params["news.fields"] = ",".join(str(item) for item in news_fields)
        headers = {}
        # Prepare request data
        json_data = None
        # Make the request
        response = self.client.session.get(
            url,
            params=params,
            headers=headers,
        )
        # Check for errors
        response.raise_for_status()
        # Parse the response data
        response_data = response.json()
        # Convert to Pydantic model if applicable
        return SearchResponse.model_validate(response_data)


    def get(self, id: Any, news_fields: List = None) -> GetResponse:
        """
        Get news stories by ID
        Retrieves news story by its ID.
        Args:
            id: The ID of the news story.
            news_fields: A comma separated list of News fields to display.
            Returns:
            GetResponse: Response data
        """
        url = self.client.base_url + "/2/news/{id}"
        url = url.replace("{id}", str(id))
        if self.client.bearer_token:
            self.client.session.headers["Authorization"] = (
                f"Bearer {self.client.bearer_token}"
            )
        elif self.client.access_token:
            self.client.session.headers["Authorization"] = (
                f"Bearer {self.client.access_token}"
            )
        # Ensure we have a valid access token
        if self.client.oauth2_auth and self.client.token:
            # Check if token needs refresh
            if self.client.is_token_expired():
                self.client.refresh_token()
        params = {}
        if news_fields is not None:
            params["news.fields"] = ",".join(str(item) for item in news_fields)
        headers = {}
        # Prepare request data
        json_data = None
        # Make the request
        response = self.client.session.get(
            url,
            params=params,
            headers=headers,
        )
        # Check for errors
        response.raise_for_status()
        # Parse the response data
        response_data = response.json()
        # Convert to Pydantic model if applicable
        return GetResponse.model_validate(response_data)
