import pandas as pd
from datetime import datetime, timedelta

def calculate_kpis(events_df, date_range):
    """Berechnet KPIs aus Telemetrie-Events für einen bestimmten Zeitraum."""

    # Filtere Events nach Zeitraum
    mask = (events_df['timestamp'] >= date_range[0]) & \
           (events_df['timestamp'] <= date_range[1])
    period_events = events_df[mask]

    # Berechne Erfolgsquote
    total_attempts = len(period_events[period_events['verb'] == 'attempted'])
    successful_attempts = len(period_events[period_events['verb'] == 'passed'])

    success_rate = 0
    if total_attempts > 0:
        success_rate = successful_attempts / total_attempts * 100

    # Berechne Durchschnittliche Bearbeitungszeit
    avg_duration = period_events['duration'].mean()

    return {
        'success_rate': success_rate,
        'avg_duration': avg_duration,
        'total_attempts': total_attempts
    }
