#!/usr/bin/env python3
# spdx-license-identifier: MIT
#
# Copyright (c) 2026 MemryX Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


import memryx as mx
import argparse
import shutil
import multiprocessing
import os
import sys
import time

# ANSI color codes for terminal output
BLUE = "\033[94m"
GREEN = "\033[92m"
RED = "\033[91m"
CYAN = "\033[96m"
RESET = "\033[0m"

# Suppress warnings
import warnings
warnings.filterwarnings("ignore")


###############################################################################


max_split_number = multiprocessing.Value('i', 99999)

def compile_model_subproc(model_path, split_number=0, num_chips=4):

    # check if split_number is already known to be invalid
    with max_split_number.get_lock():
        if split_number >= max_split_number.value:
            return

    # make a dir for this split number and change into it
    split_dir = f"split_{split_number}"
    os.makedirs(split_dir, exist_ok=True)
    os.chdir(split_dir)

    # add "../" to the model path since we are now in the split directory
    # note that if model_path is a list, we need to add "../" to each element in the list
    if isinstance(model_path, list):
        model_path = [f"../{p}" for p in model_path]
    else:
        model_path = f"../{model_path}"

    # run mx.NeuralCompiler and save dfp to file in this directory
    try:
        dfp_fname = f"dfp_{split_number}.dfp"
        print(f"{BLUE}[Compiling]{RESET} Compiling model with split_number={split_number}...")
        nc = mx.NeuralCompiler(
            models=model_path,
            verbose=0,
            autocrop=True,
            no_sim_dfp=True,
            num_chips=num_chips,
            effort="hard",
            dfp_fname=dfp_fname,
            split_number=split_number
        )
        dfp = nc.run()
        dfp.write(dfp_fname)
        print(f"{GREEN}[Done]{RESET} Successfully compiled model with split_number={split_number}. DFP saved to split_{split_number}/{dfp_fname}")
    except Exception as e:
        if "overflow sweep" in str(e):
            print(f"{GREEN}[Skip]{RESET} split_number={split_number} is not valid, all valid splits have been exhausted.")
            # update max_split_number to this split number so that future subprocesses will skip it
            with max_split_number.get_lock():
                if split_number < max_split_number.value:
                    max_split_number.value = split_number

            # delete this split directory since it is not valid
            os.chdir("..")
            shutil.rmtree(split_dir)
        else:
            print(f"{RED}[ERROR]{RESET} Error compiling model with split_number={split_number}: {e}")
        dfp = None


def compile_all(model_path, max_jobs=4, max_split_number=30, num_chips=4):

    # for each split number, spawn a subprocess to compile the model with that split number
    # keep the number of concurrent subprocesses to max_jobs
    processes = []
    for split_number in range(max_split_number):
        p = multiprocessing.Process(target=compile_model_subproc, args=(model_path, split_number, num_chips))
        p.start()
        processes.append(p)

        # check the list of processes and join and remove any that have finished
        # then, if there are max_jobs processes running, wait for one to finish before starting a new one
        while len(processes) >= max_jobs:
            for p in processes:
                if not p.is_alive():
                    p.join()
                    processes.remove(p)
                    break
            # sleep for a little bit before checking again
            time.sleep(1)


    # wait for all processes to finish
    for p in processes:
        p.join()

    print(f"\n\n")

###############################################################################

# run all DFPs sequentially and keep track of the max FPS achieved
def run_all_dfps(num_runs=3, models_in_dfp=1, prioritize_model=-1, frames=500, device_id=0):

    max_fps_overall = 0
    best_split_number = -1

    # run for each split number until no more valid splits
    # note: check the directory exists before trying to run the DFP
    max_split_local = 0
    with max_split_number.get_lock():
        max_split_local = max_split_number.value

    for split_number in range(max_split_local):
        split_dir = f"split_{split_number}"
        if not os.path.exists(split_dir):
            continue

        dfp_fname = f"{split_dir}/dfp_{split_number}.dfp"
        if not os.path.exists(dfp_fname):
            continue

        print(f"{BLUE}[Benchmarking]{RESET} Benchmarking DFP from split_number={split_number}...")

        max_fps = 0
        for _ in range(num_runs):
            with mx.Benchmark(dfp=dfp_fname, verbose=1, device_ids=[device_id]) as bm:

                # if prioritize = -1, use the sum of all models' FPS
                if prioritize_model == -1:
                    fps_sum = 0
                    for midx in range(models_in_dfp):
                        _, _, fps = bm.run(frames=frames, model_idx=midx)
                        fps_sum += fps
                elif prioritize_model >= 0 and prioritize_model < models_in_dfp:
                    # otherwise, only use the FPS of the prioritized model index
                    _, _, fps_sum = bm.run(frames=frames, model_idx=prioritize_model)
                else:
                    print(f"{RED}[ERROR]{RESET} Invalid prioritize_model index {prioritize_model} for models_in_dfp={models_in_dfp}")
                    raise ValueError(f"Invalid prioritize_model index {prioritize_model} for models_in_dfp={models_in_dfp}")

                if fps_sum > max_fps:
                    max_fps = fps_sum

        print(f"{GREEN}[Done]{RESET} FPS for split_number={split_number}: {max_fps:.2f} FPS")

        if max_fps > max_fps_overall:
            max_fps_overall = max_fps
            best_split_number = split_number


    # print overall max FPS and move the best DFP from ./split_N/dfp_N.dfp to ./best_dfp.dfp
    print(f"\n\n{GREEN}[RESULT]{RESET} Best FPS achieved: {max_fps_overall:.2f} FPS with split_number={best_split_number}")

    if best_split_number >= 0:
        best_dfp_src = f"split_{best_split_number}/dfp_{best_split_number}.dfp"
        best_dfp_dst = "best_dfp.dfp"
        shutil.copyfile(best_dfp_src, best_dfp_dst)
        print(f"{GREEN}[DONE]{RESET} Best DFP copied to {best_dfp_dst}")


###############################################################################

def main(model_path, max_jobs=4, keep_split_folders=False, prioritize_model=-1, frames=500, num_chips=4, device_id=0):


    # print a nice banner
    mx.utilities.print_mix.print_logo_mx_f3()
    print("╔"+"═"*38+"╗\n"+
          "║    Closed-Loop Compilation Script    ║\n"+
          "╚"+"═"*38+"╝\n")


    # print all the input args
    print(f"{CYAN}[INFO]{RESET} Model path(s): {model_path}")
    print(f"{CYAN}[INFO]{RESET} Max concurrent compilation jobs: {max_jobs}")
    print(f"{CYAN}[INFO]{RESET} Keep split folders: {keep_split_folders}")
    if prioritize_model != -1:
        print(f"{CYAN}[INFO]{RESET} Prioritize model index for benchmarking: {prioritize_model}")
    print(f"{CYAN}[INFO]{RESET} Frames to run for each benchmark: {frames}")
    if num_chips != 4:
        print(f"{CYAN}[INFO]{RESET} Target number of chips for compilation: {num_chips}")
    print(f"{CYAN}[INFO]{RESET} Device ID to use for benchmarking: {device_id}")
    print("\n"+"═"*50+"\n")

    # if model_path is a list, count the number of models to use later in run_all_dfps
    models_in_dfp = 1
    if isinstance(model_path, list):
        models_in_dfp = len(model_path)

    # Compile all model splits
    compile_all(model_path, max_jobs=max_jobs, num_chips=num_chips)

    # Run all DFPs and find the best one
    run_all_dfps(num_runs=3, models_in_dfp=models_in_dfp, prioritize_model=prioritize_model, frames=frames, device_id=device_id)

    # optionally, delete all the intermediate build folders for the splits
    if not keep_split_folders:
        max_split_local = 0
        with max_split_number.get_lock():
            max_split_local = max_split_number.value

        for split_number in range(max_split_local):
            split_dir = f"split_{split_number}"
            if os.path.exists(split_dir):
                shutil.rmtree(split_dir)


###############################################################################

if __name__ == '__main__':

    # get num processors to use for jobs: min(4, num_cpus/2)
    num_cpus = multiprocessing.cpu_count()
    default_njobs = min(4, num_cpus // 2)

    parser = argparse.ArgumentParser(description="Closed-loop compilation script")

    # model arg is a list of strings
    parser.add_argument('-m', '--models', nargs='+', required=True,
                        help='Path(s) to the model file(s).')
    parser.add_argument('-j', '--jobs', type=int, default=default_njobs,
                        help=f'Maximum number of concurrent compilation jobs (default: {default_njobs}).')
    parser.add_argument('-k', '--keep-split-folders', action='store_true',
                        help='Keep all compiled splits (default: False).')
    parser.add_argument('-pm', '--prioritize-model', type=int, default=-1,
                        help='When benchmarking splits for multi-model DFPs, should we prioritize total FPS (-1, default), or a specific model only (0 for first model, 1 for second model, etc.)?')
    parser.add_argument('-f', '--frames', type=int, default=500,
                        help='Number of frames to run for each benchmark (default: 500).')
    parser.add_argument('-c', '--num_chips', type=int, default=4,
                        help='Size (number of chips) of the target MXA device (default: 4)')
    parser.add_argument('-g', '--device_id', type=int, default=0,
                        help='ID of the connected MXA device to use for compilation and benchmarking (default: 0)')

    args = parser.parse_args()
    main(args.models, max_jobs=args.jobs, keep_split_folders=args.keep_split_folders,
         prioritize_model=args.prioritize_model, frames=args.frames, num_chips=args.num_chips, device_id=args.device_id)
