from concurrent.futures import ThreadPoolExecutor, as_completed

import requests
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.data_classes import (
    EventBridgeEvent,
    event_source,
)
from aws_lambda_powertools.utilities.typing import LambdaContext

logger = Logger(__name__)
tracer = Tracer()
urls = [
    'https://bcs7fgb9og.execute-api.sa-east-1.amazonaws.com/health',
    # 'https://api.saladeaula.digital/health',
    'https://id.saladeaula.digital/health',
]


@tracer.capture_lambda_handler
@event_source(data_class=EventBridgeEvent)
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    results = []

    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = [executor.submit(ping, url) for url in urls]

        for future in as_completed(futures):
            results.append(future.result())

    logger.info(results)

    return True


def ping(url: str):
    try:
        r = requests.get(url, timeout=4)
        r.raise_for_status()
    except requests.exceptions.RequestException as exc:
        return {
            'url': url,
            'error': str(exc),
        }
    else:
        return {
            'url': url,
            'status': r.status_code,
        }
