from flask import Flask, jsonify
import pickle
import pandas as pd

app = Flask(__name__)

# =============================
# LOAD MODEL

with open("model_pegas.pkl", "rb") as f:
    model_pegas = pickle.load(f)

print("Model PeGas berhasil dimuat")

# ROUTE TEST

@app.route("/")
def home():
    return jsonify({
        "status": "API PeGas aktif"
    })


# PREDIKSI 30 HARI

@app.route("/predict_30days")
def predict_30days():

    future = model_pegas.make_future_dataframe(periods=30)

    future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)

    forecast = model_pegas.predict(future)

    result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(30)

    return jsonify(result.to_dict(orient="records"))


# PREDIKSI 3 BULAN

@app.route("/predict_3months")
def predict_3months():

    future = model_pegas.make_future_dataframe(periods=90)

    future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)

    forecast = model_pegas.predict(future)

    result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(90)

    return jsonify(result.to_dict(orient="records"))


# PREDIKSI 6 BULAN

@app.route("/predict_6months")
def predict_6months():

    future = model_pegas.make_future_dataframe(periods=180)

    future['is_pengetatan'] = (future['ds'] >= '2025-10-01').astype(int)

    forecast = model_pegas.predict(future)

    result = forecast[['ds','yhat','yhat_lower','yhat_upper']].tail(180)

    return jsonify(result.to_dict(orient="records"))

# RUN FLASK

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