import pickle
import pandas as pd
import numpy as np
from sklearn.metrics import mean_absolute_error

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

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

print("Model berhasil dimuat")

# ======================
# LOAD DATA
# ======================

df_gabungan = pd.read_excel("Data_Gabungan.xlsx")
df_eka = pd.read_excel("Data_Penjualan_Eka.xlsx")

# PREPROCESSING

df_gabungan['ds'] = pd.to_datetime(df_gabungan['tanggal_penjualan'])
df_eka['ds'] = pd.to_datetime(df_eka['tanggal_penjualan'])

df_gab_w = df_gabungan.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})
df_eka_w = df_eka.resample('W', on='ds')[['jumlah']].sum().reset_index().rename(columns={'jumlah':'y'})

# REGRESSOR

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

# HITUNG RASIO

overlap = pd.merge(df_gab_w, df_eka_w, on='ds', suffixes=('_gab','_eka'))

ratio = overlap['y_eka'].sum() / overlap['y_gab'].sum()

print("Rasio:", ratio)

# PREDIKSI

forecast = model_pegas.predict(df_gab_w)

eval_df = pd.merge(df_eka_w[['ds','y']], forecast[['ds','yhat']], on='ds')

y_true = eval_df['y'].values
y_pred_scaled = eval_df['yhat'].values * ratio

# EVALUASI

mae = mean_absolute_error(y_true, y_pred_scaled)

mape = np.mean(
    np.abs((y_true[y_true>0] - y_pred_scaled[y_true>0]) / y_true[y_true>0])
) * 100

print("----------------------------")
print("HASIL EVALUASI MODEL PEGAS")
print("MAE :", round(mae,2), "tabung")
print("MAPE:", round(mape,2), "%")
print("----------------------------")