import openpyxl
from openpyxl.styles import PatternFill
import pandas as pd

def fill_cell(ws, cell, color):
    fill = PatternFill(start_color=color, end_color=color, fill_type='solid')
    cell.fill = fill

def calculate_and_fill_deviation(ws, row, absolute_deviations):
    if absolute_deviations:
        average_deviation = sum(absolute_deviations) / len(absolute_deviations)
        deviation_cell = ws.cell(row=row[0].row, column=4)  # Angenommen, die 'Abweichung'-Spalte ist Spalte D
        deviation_cell.value = average_deviation
        # Färbe die Zelle basierend auf der durchschnittlichen Abweichung
        if average_deviation < 5:
            fill_color = 'FF00FF00'  # Grün
        elif 5 <= average_deviation < 10:
            fill_color = 'FFFFFF00'  # Gelb
        else:
            fill_color = 'FFFF0000'  # Rot
        fill_cell(ws, deviation_cell, fill_color)

def color_cells_based_on_deviation(testruns_excel_file_path, testcases_excel_file_path):
    wb_testruns = openpyxl.load_workbook(testruns_excel_file_path)
    ws_testruns = wb_testruns.active
    df_testcases = pd.read_excel(testcases_excel_file_path)

    for row in ws_testruns.iter_rows(min_row=2, max_row=ws_testruns.max_row):
        deviations = []
        absolute_deviations = []

        for cell in row[4:]:
            header_cell_value = ws_testruns.cell(row=1, column=cell.column).value
            if header_cell_value and "Testcase" in header_cell_value:
                testcase_num = int(header_cell_value.split('_')[1])
                expected_pulse_row = df_testcases[df_testcases['Testcase'] == testcase_num]
                if not expected_pulse_row.empty:
                    expected_pulse = expected_pulse_row.iloc[0]['Puls']
                    actual_pulse = cell.value
                    if actual_pulse is not None and expected_pulse is not None:
                        relative_deviation = (actual_pulse - expected_pulse) / expected_pulse * 100
                        absolute_deviation = abs(relative_deviation)
                        deviations.append(relative_deviation)
                        absolute_deviations.append(absolute_deviation)

                        if absolute_deviation < 5:
                            fill_color = 'FF00FF00'  # Grün
                        elif 5 <= absolute_deviation < 10:
                            fill_color = 'FFFFA500' if relative_deviation < 0 else 'FFFFFF00'  # Orange für niedriger, Gelb für höher
                        else:
                            fill_color = 'FFC0CB' if relative_deviation < 0 else 'FFFF0000'  # Rosa für niedriger, Rot für höher
                        fill_cell(ws_testruns, cell, fill_color)

        calculate_and_fill_deviation(ws_testruns, row, absolute_deviations)

    wb_testruns.save(testruns_excel_file_path)
