import os
import time
from .client import MonitoringFacade

class MonitoringMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        start_time = time.time()
        response = self.get_response(request)
        duration = (time.time() - start_time)

        tags = {
            "method": request.method,
            "status": str(response.status_code),
            "path": request.path,
            "source": 'lambda' if os.environ.get('AWS_LAMBDA_FUNCTION_NAME') else 'ec2'
        }

        MonitoringFacade.get_instance().send('rx.api.request_count', metric_type='increment', tags=tags)
        MonitoringFacade.get_instance().send('rx.api.request_duration', duration, metric_type='histogram', tags=tags)

        return response
