from flask import Flask, request, jsonify
import joblib
import json
import numpy as np

app = Flask(__name__)

model  = joblib.load("../models/random_forest_stunting.pkl")
with open("../models/label_mapping.json", "r") as f:
    label_mapping = json.load(f)

@app.route('/', methods=['GET'])
def home():
    return jsonify({
        "message" : "API Deteksi Stunting",
        "version" : "1.0",
        "endpoint": "/predict"
    })

@app.route('/predict', methods=['POST'])
def predict():
    try:
        data = request.get_json()
        # Ambil input
        jk         = 0 if str(data['jenis_kelamin']).upper() == 'L' else 1
        usia       = float(data['usia_bulan'])
        berat      = float(data['berat_badan'])
        tinggi     = float(data['tinggi_badan'])
        # Klasifikasi
        features   = np.array([[jk, usia, berat, tinggi]])
        pred       = model.predict(features)[0]
        prob       = model.predict_proba(features)[0]
        label      = label_mapping[str(pred)]

        return jsonify({
            "status"           : "success",
            "input"            : {
                "jenis_kelamin": data['jenis_kelamin'],
                "usia_bulan"   : usia,
                "berat_badan"  : berat,
                "tinggi_badan" : tinggi
            },
            "prediksi"         : label,
            "probabilitas"     : {
                label_mapping[str(i)]: round(float(p), 4)
                for i, p in enumerate(prob)
            }
        })

    except Exception as e:
        return jsonify({
            "status" : "error",
            "message": str(e)
        }), 400

if __name__ == '__main__':
    app.run(debug=True, port=5000)

    