import requests
from airflow_commons.internal.mindsite.auth import get_auth
from airflow_commons.internal.mindsite.constants import BASE_URL
from airflow_commons.internal.mindsite.defaults import get_default_date
from airflow_commons.logger import get_logger

from airflow_commons.internal.mindsite.constants import (
    MATCHING_DATA_ENDPOINT,
    CRAWLING_DATA_ENDPOINT,
)


class MindsiteOperator(object):

    def __init__(self, username: str = None, password: str = None):
        """
        Initializes MindsiteOperator instance with given credentials.
        If no credentials were supplied, uses environment variables.

        :param username:
        :param password:
        """
        self.username = username
        self.password = password
        self.logger = get_logger("MindsiteOperator")

    def get_crawling_data(self, date: str = None) -> bytes:
        """
        Fetches crawling data from Mindsite API for the given date.

        :param date: Date in YYYY-MM-DD format. Defaults to today if not provided.
        :return: Crawling data as parquet bytes
        :raises requests.HTTPError: If response status is 4xx or 5xx
        """
        date = date or get_default_date()
        self.logger.info(f"Fetching Mindsite crawling data for date: {date}")
        result = self._fetch_from_mindsite(CRAWLING_DATA_ENDPOINT, date=date)
        self.logger.info("Mindsite crawling data fetched successfully.")
        return result

    def get_matching_data(self, date: str = None) -> bytes:
        """
        Fetches matching data from Mindsite API for the given date.

        :param date: Date in YYYY-MM-DD format. Defaults to today if not provided.
        :return: Matching data as parquet bytes
        :raises requests.HTTPError: If response status is 4xx or 5xx
        """
        date = date or get_default_date()
        self.logger.info(f"Fetching Mindsite matching data for date: {date}")
        result = self._fetch_from_mindsite(MATCHING_DATA_ENDPOINT, date=date)
        self.logger.info("Mindsite matching data fetched successfully.")
        return result

    def _fetch_from_mindsite(self, endpoint: str, date: str) -> bytes:
        """
        Makes a GET request to the given endpoint with the given date.

        :param date: Date in YYYY-MM-DD format
        :return: Response body as bytes
        :raises requests.HTTPError: If response status is 4xx or 5xx
        """
        url = f"{BASE_URL}{endpoint}"
        response = requests.get(
            url, auth=get_auth(self.username, self.password), params={"date": date}
        )
        response.raise_for_status()
        return response.content
