from flask import Flask, request, jsonify
import pandas as pd
from Decision_Tree.Decision_Tree import sideEffectTreatments
import numpy as np
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

def convert_ndarray_to_list(data_dict):
    converted_dict = {}
    for key, value in data_dict.items():
        if isinstance(value, np.ndarray):
            converted_dict[key] = value.tolist()
        else:
            converted_dict[key] = value
    return converted_dict

@app.route('/predict', methods=['OPTIONS', 'GET', 'POST'])
def predict():

    if request.method == 'OPTIONS':
        # Handle CORS preflight request here
        return '', 200
    elif request.method == 'POST':
        try:
            # Extract data from the JSON request
            data = request.get_json()

            
            # Convert the JSON data to a pandas DataFrame
            new_person_data = pd.DataFrame(data)
            print(new_person_data)

            # Call the test function to make predictions
            predictions = sideEffectTreatments(new_person_data)

            # Convert NumPy ndarray predictions to a serializable format
            converted_predictions = convert_ndarray_to_list(predictions)
            
            return jsonify(converted_predictions)
        except Exception as e:
            return jsonify({'error': str(e)})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5500)
