/*
 * Copyright 2025 NXP
 * All rights reserved.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <fastestdet_postprocess.h>
#include <model_config.h>
#include "eiq_app.h"
#include "fsl_debug_console.h"
#include "model.h"
#include "timer.h"
#include "fsl_gpio.h"
#include "model_preprocess.h"

/*******************************************************************************
 * Definitions
 ******************************************************************************/

/*******************************************************************************
 * Prototypes
 ******************************************************************************/

/*******************************************************************************
 * Variables
 ******************************************************************************/
tensor_dims_t inputDims;
tensor_type_t inputType;
uint8_t* inputData;
tensor_dims_t outputDims;
tensor_type_t outputType;
uint8_t* outputData;

/*******************************************************************************
 * Code
 ******************************************************************************/
void eIQApp_Init()
{
    PRINTF("****************************************************************\r\n");
    // Real Core System Clock as reported by the system
    PRINTF("CoreSysClkFreq: %d MHz, %d MHz\r\n", CLOCK_GetCoreSysClkFreq()/1000000, CLOCK_GetFreq(kCLOCK_CoreSysClk)/1000000);
    // This is the indented SystemCoreClock used for initialization
    PRINTF("SystemCoreClock (default init):   %d MHz\r\n", SystemCoreClock/1000000);
    SystemCoreClockUpdate();
    // This is the actual SystemCoreClock after initialization
    PRINTF("SystemCoreClock (system updated): %d MHz\r\n", SystemCoreClock/1000000);
    //DEMO_PrintInfo();

    if (MODEL_Init() != kStatus_Success)
    {
        PRINTF("Failed initializing model\r\n");
        for (;;) {}
    }

    MODEL_PreprocessInit();

    inputData = MODEL_GetInputTensorData(&inputDims, &inputType);
    outputData = MODEL_GetOutputTensorData(&outputDims, &outputType);
}

void eIQApp_Inference_Run(uint8_t *imgData, int32_t imgWidth, int32_t imgHeight, int32_t imgChannels, uint8_t *result, box_data *boxes)
{
	/* Expected tensor dimensions: [batches, height, width, channels] */
	memcpy(inputData, imgData, inputDims.data[2] * inputDims.data[1] * inputDims.data[3]);
	MODEL_Preprocess(inputData);
	MODEL_RunInference();
	*result = Fastestdet_Postprocess((int8_t*)outputData, boxes);
}
