import tempfile
import time
import pickle
import pandas as pd

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
from imc_utils.serial_watch import SerialWatcher

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()

    benchmarks = [
        "vBasicMath",
        "vCrc",
        "vFFT",
        "vSha",
        "vStringSearch",
        "vMatMul",
        "vConv2d",
        "vAes",
    ]
    # benchmarks = ["vBasicMath"]

    n_divisions = 5

    for benchmark in benchmarks:
        all_records = []
        bench_repeat_count = config.bench_repeat_count_small[benchmark]

        config.bench_name = benchmark
        config.bench_repeat_count = bench_repeat_count

        step = bench_repeat_count / n_divisions
        step_int = int(step) if step >= 1 else 1
        static_loop_pass_counts = list(range(0, bench_repeat_count, step_int))
        static_loop_pass_counts.append(bench_repeat_count)

        for loop_pass_count in static_loop_pass_counts:

            config.loop_pass_count = loop_pass_count

            pps.set_voltage(3.3, 1)
            pps.set_current(0.1, 1)
            pps.output_on(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 = 1
            watcher = SerialWatcher(benchmark, total_iterations)
            records = watcher.run()
            for record in records:
                record.update(
                    {
                        "loop_pass_count": loop_pass_count,
                    }
                )
                all_records.append(record)
        df = pd.DataFrame(all_records)
        print(df)
        save_records(benchmark, df)
    pps.output_off(1)


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
    config.split_loop = True
    config.enable_static_loop_pass_count = True
    config.loop_pass_count = 0
    return config


def save_records(bench_name, df):
    with open(f"output/{bench_name}.pickle", "wb") as f:
        pickle.dump(df, f)


if __name__ == "__main__":
    main()
