import tempfile
import time

from imc_utils.pps_e36311a import PPS_E36311A
from imc_utils.build_config.cortex_m33 import BuildConfigM33
from imc_utils.build_config.test_env import TestEnv
import imc_utils.serial_device

# from ..common_configs import WORKSPACE_ROOT, NVM_RESET_BIN, OPENOCD_SCRIPT

WORKSPACE_ROOT = "/home/ybkim/workspace/imc/imc_freertos_app_m33"
NVM_RESET_BIN = f"{WORKSPACE_ROOT}/imc/utils/nvm_reset.elf"
OPENOCD_SCRIPT = f"{WORKSPACE_ROOT}/imc_freertos_app_m33.cfg"

def main():
    pps = PPS_E36311A()
    config = get_default_build_config()

    config.bench_name = "vBasicMath"
    config.insert_compiler_checkpoints = True
    config.use_checkpoint_voltage_check = False

    pps.set_voltage(3.3, 1)
    pps.set_current(0.1, 1)

    env = TestEnv(WORKSPACE_ROOT, NVM_RESET_BIN, OPENOCD_SCRIPT)

    with tempfile.TemporaryDirectory() as build_dir:
        binary = env.build_binary(config, build_dir)
        env.clear_nvm_and_load_binary(binary, resume=True)
    
    total_iterations = 5
    measured_times = measure_execution_time(total_iterations)
    print(measured_times)


def measure_execution_time(total_iterations):
    ser = imc_utils.serial_device.get_serial()

    num_finished = 0
    start_detected = False
    time_takens = []
    time_total = 0

    ser.read_all()

    while num_finished < total_iterations:
        if ser.readable():
            res = ser.readline()
            try:
                line = res.decode()[: len(res) - 1]
            except:
                continue

        if line.startswith("hardfault"):
            print("\nHARD FAULT")

        if not start_detected:
            if line.startswith("Start benchmark"):
                print("\nbenchmark start detected")
                t_start = time.time()
                start_detected = True
        else:
            if line.startswith("End benchmark"):
                t_end = time.time()
                t_diff = t_end - t_start
                time_takens.append(t_diff)
                time_total += t_diff
                num_finished += 1
                print(
                    f"\nbenchmark end detected, time: {t_diff:.2f} secs, finished: {num_finished}, average: {time_total/num_finished:.2f} secs"
                )
                start_detected = False
                # print(time_takens)
    return time_takens


def get_default_build_config():
    config = BuildConfigM33()
    config.bench_name = "vBasicMath"
    config.insert_compiler_checkpoints = True
    config.enable_extension = True
    config.use_checkpoint_pass_counter = False
    config.use_checkpoint_voltage_check = True
    config.bench_infinite_loop = True
    return config


if __name__ == "__main__":
    main()

