import os
from datetime import datetime, timedelta
import pandas as pd
import matplotlib.pyplot as plt

hazels_dir = os.getenv("SOMEWEAR_ANDROID_HOME")


def download_logs(days):
    # cd into the hazels directory
    os.chdir(hazels_dir)
    print(f"Downloading logs for the last {days} days")
    for i in range(days):
        print(f"Downloading logs for day {i + 1}")

        date = datetime.now() - timedelta(days=i)
        date_str = date.strftime("%Y-%m-%d")
        print(f"Downloading logs for date {date_str}")
        os.system(f"ruby script/get-logs.rb -d {date_str} -o ../logs/android")


def find_date(line):
    date_chunck = line.split('|')[0]
    date_chunck = date_chunck.split(':')[1].strip()
    date = date_chunck.split(' ')[0]
    return date


def filter_map(sorted_map):
    frequency_map = dict(sorted(sorted_map.items(), key=lambda item: item[0]))
    # filter out older than 90 days
    filtered_map = {}
    for date, frequency in frequency_map.items():
        try:
            date_obj = datetime.strptime(date, '%Y-%m-%d')
        except ValueError:
            print(f"error parsing date {date}")
            continue
        date_obj = datetime.strptime(date, '%Y-%m-%d')
        if date_obj > datetime.now() - timedelta(days=90):
            filtered_map[date] = frequency
    return filtered_map


# before running this report, make sure to run the following command in the logs/android directory
# after downloading logs. This generates a file with the output of the grep command. This File
# is used to generate the report.
# grep -R 'upgrade failed=' logs/android > gatt_error_output.txt
def generate_gat_error_report():
    name = 'gatt_error_output'
    file = '/Users/matthewroberts/development/projects/somewear/output-ble-disconnect.txt'
    connects_file = 'onDeviceConnected.txt'

    csv_path = 'output-ble-disconnect.csv'
    frequency_map = {}
    connects_map = {}
    # for each line in file
    with open(file, 'r') as f:
        for line in f:
            date = find_date(line)
            frequency_map[date] = frequency_map.get(date, 0) + 1

    with open(connects_file, 'r') as f:
        for line in f:
            date = find_date(line)
            connects_map[date] = connects_map.get(date, 0) + 1

    sorted_map = filter_map(frequency_map)
    sorted_conntects_map = filter_map(connects_map)

    csv = open(csv_path, 'w')
    csv.write('date,frequency,connects,percentage\n')
    for date, frequency in sorted_map.items():
        connects = sorted_conntects_map.get(date, 0)
        quotient = frequency / connects if connects > 0 else 0
        percentage = round(quotient, 2) * 100
        csv.write(f"{date}, {frequency},{connects},{percentage}\n")

    csv.close()

    df = pd.read_csv(csv_path)

    x_values = df['date']
    y_values = df['frequency']
    y_values_connects = df['connects']

    x_values = pd.to_datetime(x_values)
    plt.plot(x_values, y_values)
    plt.plot(x_values, y_values_connects, color='green')

    plt.legend(['OS GATT Errors', 'Connects'])
    plt.title('Ble Disconnect Frequency')
    plt.xlabel('Date')
    plt.ylabel('Frequency')

    file_name = f'{name}.png'
    plt.savefig(file_name)
    plt.close()
    return file_name


def generate_fw_update_failure_report():
    name = 'upgrade_failure_output'
    file = f'{name}.txt'
    csv_path = 'firmware_update_failures.csv'
    frequency_map = {}
    with open(file, 'r') as f:
        for line in f:
            date = find_date(line)
            frequency_map[date] = frequency_map.get(date, 0) + 1

    sorted_map = filter_map(frequency_map)

    csv = open(csv_path, 'w')
    csv.write('date,frequency\n')
    for date, frequency in sorted_map.items():
        csv.write(f"{date}, {frequency}\n")

    csv.close()

    df = pd.read_csv(csv_path)

    x_values = df['date']
    y_values = df['frequency']

    x_values = pd.to_datetime(x_values)

    plt.plot(x_values, y_values)

    plt.title('Firmware Update Failures')
    plt.xlabel('Date')
    plt.ylabel('Frequency')
    file_name = f'{name}.png'
    plt.savefig(file_name)
    return file_name


def generate_html_report(get_error_image_path, fw_update_image_path):
    html = f"""
    <html>
    <head>
    <title>Logging Reports</title>
    </head>
    <body>
    <h1>Logging Reports</h1>
    <h2>GATT Errors</h2>
    <img src="{get_error_image_path}" alt="GATT Errors">
    <h2>Firmware Update Failures</h2>
    <img src="{fw_update_image_path}" alt="Firmware Update Failures">
    </body>
    </html>
    """
    with open('logging_reports.html', 'w') as f:
        f.write(html)


if __name__ == "__main__":
    get_error_image_path = generate_gat_error_report()
    fw_update_image_path = generate_fw_update_failure_report()

    generate_html_report(get_error_image_path, fw_update_image_path)
