from typing import Union
import logging
import json


def format_api_results(response: dict, text: dict) -> Union[dict, None]:
    """Extracts relevant fields from Perspective API

    Args:
        response: Dict holding perspective API results
        text: Dict in hodling transcript, start_time, and end_time

    Returns:
        Dict with text, start_time, end_time, toxicity
    """
    logging.info(f'Starting format_api_results with {json.dumps(response)} '
                 f'and {text}.')

    try:
        toxicity = response['attributeScores']['TOXICITY']['summaryScore']['value']
        return {'text': text['transcript'],
                'start_time': text['start_time'] if 'start_time' in text else '',
                'end_time': text['end_time'] if 'end_time' in text else '',
                'toxicity': round(toxicity, 2)}

    except Exception as e:
        logging.error(f'Extracting toxicity fields failed for '
                      f'{json.dumps(response)}')
        logging.error(e)