"""
######################################################################
# Script Name:  WGL034_example.py
# Version:      1.0.0
# Author:       Eduard Dercho
# Company:      IBR Messtechnik GmbH & Co. KG  
# Date:         2025-08-22
# Description:  This python script file is an example file on how to
#               link ComGage with the WGL034 measuring mode to a 
#               python script and how to execute an own calculation 
#               method.
#                 
#               The IBR_PythonWrapper.exe calls the "main" function 
#               with a bunch of data from ComGage. For a detailed 
#               explanation please have a look at the description of
#               the main function below.
#
######################################################################
"""
#
#---# Import of additional Python librarys needed for this example :
#
import time
import matplotlib.pyplot as plt
from scipy.optimize import minimize
import numpy as np
import cv2
import json
from shapely.geometry import Polygon, Point
from shapely.ops import unary_union
import ctypes

#
#---# Main Function :
#
def main(comgage_data):
    #
    # Load the arguments of ComGage into separate variables
    #
    results = comgage_data[0]               # Array with 2 results. These result values are set in this function, and are saved into the set registrys of wgl034
    val_num = comgage_data[1]               # Number of values which were saved
    encoder_val_raw = comgage_data[2]       # Array with the raw measuring values of the encoder if one is used
    encoder_val_calc = comgage_data[3]      # Array with the resized measuring values to 3600 values ( 1 value per 0.1° ) of the encoder if one is used
    mea_val_raw = comgage_data[4]           # Array of raw measuring values for each configured probe beginning at index 0. Example: "meaValues[0]" contains all measured values of probe 1.
    mea_val_rot_enc = comgage_data[5]       # Array of rotated and encoded measuring values for each configured probe beginning at index 0.
    mea_val_step1 = comgage_data[6]         # Array with the size of 3600, consists of the measuring values of the probes with their given factors
    mea_val_step2 = comgage_data[7]         # Same like "mea_val_step1" but with axis and middlepoint correction
    mea_val_step3 = comgage_data[8]         # Same like "mea_val_step2" but with removed grooves
    mea_val_step4 = comgage_data[9]         # Same like "mea_val_step3" but with removed fixed angles
    tsDir = comgage_data[10]                # Path of the test scheme directory from ComGage
    toDir = comgage_data[11]                # Path of the test order directory from ComGage
    meaDatDir = comgage_data[12]            # Path of the measuring data directory from ComGage
    picDir = comgage_data[13]               # Path of the picture directory from ComGage
    rifDir = comgage_data[14]               # Path of the reference information directory from ComGage
    #
    # In this example all raw values of probe 1 are first spread in a 360 degree circle.
    # Afterwards the minimum enclosing circle is calculated and the results are saved in a json file and displayed in a window.
    
    # First calculate the radiant values by the given number of values.
    theta_rad = np.linspace(0, 2 * np.pi, val_num, endpoint=False)
    # Now spread the existing raw measuring values of characteristic 1 to the radiant values
    x = mea_val_raw[0][:val_num] * np.cos(theta_rad)
    y = mea_val_raw[0][:val_num] * np.sin(theta_rad)
    points = np.column_stack((x, y)).astype(np.float32)
    
    # --- Create the minimum enclosing circle by the given points ---
    (center_x, center_y), min_enclosing_radius = cv2.minEnclosingCircle(points)
    
    # --- Save results in a json file ---
    result_text = {
        "minimum enclosing circle": {
            "center_x": float(center_x),
            "center_y": float(center_y),
            "radius": float(min_enclosing_radius),
        }
    }
    with open("result.json", "w") as f:
        json.dump(result_text, f, indent=2)

    # --- Visualisation ---
    fig, ax = plt.subplots(figsize=(6, 6))
    ax.set_aspect('equal')
    ax.plot(x, y, '.', markersize=1, label='Messpunkte')

    # Draw the minimum enclosing circle
    huellkreis = plt.Circle((center_x, center_y), min_enclosing_radius, color='red', fill=False, linewidth=1.5, label='Minimum enclosing circle')
    ax.add_patch(huellkreis)
    ax.plot(center_x, center_y, 'ro')

    # Add legend and labels
    ax.legend(loc='upper right')
    ax.set_xlabel("x [mm]")
    ax.set_ylabel("y [mm]")
    ax.grid(True, linestyle='--', linewidth=0.5)

    r_max = max(np.max(np.abs(x)), np.max(np.abs(y))) + 1.0
    ax.set_xlim(-r_max, r_max)
    ax.set_ylim(-r_max, r_max)
    plt.tight_layout()
    # Save this picture in the comgage picture directory with the given name
    plt.savefig(picDir + "\\minimum_enclosing_circle_result.png", dpi=300)
    # Show the drawing and the result
    plt.show()
    plt.close()
    
    # The return value is only used to check if the function has returned. The calculation result is read from ComGage by the value of "results[0]" which is set into the results register
    results[0] = min_enclosing_radius*2
    
    # For Debugging of python and to see the prints, uncomment the line "time.sleep(10)" and activate Debug-mode in wgl034. 
    # This forces the terminal to show and to wait for 10 seconds before exit.
    #time.sleep(10)
    
    return 0