import requests
from loguru import logger

from scripts.constants.app_constants import ApiConstants


class GetBetaInfo:
    def __init__(self):
        self.beta_details_url = ApiConstants.beta_details_url
        self.beta_mapping_url = ApiConstants.beta_mapping_url

    def make_request(self, tag_id, headers):
        try:
            payload = ApiConstants.payload
            payload['tag_id'] = tag_id
            response = requests.post(self.beta_details_url, headers=headers, json=payload)
            response.raise_for_status()
            response_data = response.json()
            data_field = response_data.get('data', {})
            beta_limit_list = []

            for beta in data_field.get('tableContent', {}).get('bodyContent', []):
                beta_limit_list.append(
                    {beta.get('product', ''): {"max": beta.get('upperLimit', ''),
                                               "min": beta.get('lowerLimit', '')}}
                )

            return beta_limit_list

        except requests.exceptions.RequestException as e:
            logger.info(f"Request error: {e}")
            return []

    def fetch_beta_mapping(self, tag_id, headers):
        try:
            payload = ApiConstants.payload
            payload['tag_id'] = tag_id
            response = requests.post(self.beta_mapping_url, headers=headers, json=payload)
            response.raise_for_status()
            response_data = response.json()
            data_field = response_data.get('data', {})
            mapping_list = []
            mapping_dict = {}
            for beta in data_field['tableData']['bodyContent']:
                mapping_list.append({beta['prod_id']: beta['product_name']})
                mapping_dict[beta['prod_id']] = beta['product_name']
            return mapping_dict

        except requests.exceptions.RequestException as e:
            logger.info(f"Request error: {e}")
            return []

    def beta_range(self, tag_id, headers):
        beta_details = self.make_request(tag_id, headers)
        beta_mapping = self.fetch_beta_mapping(tag_id, headers)
        final_dict = {}
        for item in beta_details:
            for k, v in item.items():
                final_dict[beta_mapping[k]] = v
        return final_dict
