import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
from tensorflow.keras.optimizers import Adam
from sklearn.preprocessing import MinMaxScaler
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_percentage_error

# 📌 1. DATA IMPORT
file_path = "DATA.xlsx"
df = pd.read_excel(file_path, header=None)

years = df.iloc[0, 1:].values.astype(int)
ghg_values = df.iloc[1, 1:].values.astype(float)
f1 = df.iloc[2, 1:].values.astype(float)
f2 = df.iloc[3, 1:].values.astype(float)
f3 = df.iloc[4, 1:].values.astype(float)

features = np.vstack([f1, f2, f3]).T
data = np.column_stack((features, ghg_values))

# 📌 2. NORMALIZATION
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(data)

# 📌 3. SEQUENCE OLUŞTURMA
def create_sequences(data, time_steps=5):
    X, y = [], []
    for i in range(len(data) - time_steps):
        X.append(data[i:i + time_steps, :])
        y.append(data[i + time_steps, -1])
    return np.array(X), np.array(y)

time_steps = 5
X, y = create_sequences(scaled_data, time_steps)

# 📌 4. MODEL (Faktörlü)
model = Sequential([
    LSTM(64, activation="elu", return_sequences=True, input_shape=(time_steps, X.shape[2])),
    Dropout(0.2),
    LSTM(32, activation="elu"),
    Dense(1)
])
model.compile(optimizer=Adam(learning_rate=0.001), loss="mse")
model.fit(X, y, epochs=100, batch_size=8, verbose=0)

# 📌 5. FITTING
predicted_scaled_all = model.predict(X)
predicted_all = scaler.inverse_transform(
    np.hstack((np.zeros((len(predicted_scaled_all), X.shape[2]-1)), predicted_scaled_all)))[:, -1]
y_actual_all = scaler.inverse_transform(
    np.hstack((np.zeros((len(y), X.shape[2]-1)), y.reshape(-1, 1))))[:, -1]

mape_all = mean_absolute_percentage_error(y_actual_all, predicted_all)
print(f"\n📌 Tüm dönem için MAPE: {mape_all:.4f}")

# 📌 6. PREDICTION (modelin GHG çıktıları üzerinden zincirleme)
ghg_only = predicted_scaled_all.reshape(-1, 1)
X_ghg = np.array([ghg_only[i:i + time_steps] for i in range(len(ghg_only) - time_steps)])
y_ghg = predicted_scaled_all[time_steps:]

ghg_model = Sequential([
    LSTM(64, activation="elu", return_sequences=True, input_shape=(time_steps, 1)),
    Dropout(0.2),
    LSTM(32, activation="elu"),
    Dense(1)
])
ghg_model.compile(optimizer=Adam(learning_rate=0.001), loss="mse")
ghg_model.fit(X_ghg, y_ghg, epochs=100, batch_size=8, verbose=0)

n_future = 12
future_years = np.arange(years[-1] + 1, years[-1] + n_future + 1)
current_input = ghg_only[-time_steps:].reshape(1, time_steps, 1)
future_predictions = []

for _ in range(n_future):
    next_scaled = ghg_model.predict(current_input, verbose=0)
    next_val = scaler.inverse_transform(
        np.hstack((np.zeros((1, X.shape[2]-1)), next_scaled)))[:, -1][0]
    future_predictions.append(next_val)
    current_input = np.concatenate([current_input[:, 1:, :], next_scaled.reshape(1, 1, 1)], axis=1)

# 📌 7. VISUALIZATION
plt.figure(figsize=(12, 6))
plt.plot(years, ghg_values, marker="o", label="Gerçek GHG", color="blue")
plt.plot(years[time_steps:], predicted_all, marker="o", linestyle="--", label="Model Tahmini (1993–2018)", color="green")
plt.plot(future_years, future_predictions, marker="o", linestyle="--", label="Gelecek Tahmin (2019–2030)", color="red")
plt.xlabel("Yıl")
plt.ylabel("GHG Emisyon")
plt.title("GHG Emisyon Tahmini: 1993–2030")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()

# 📌 8. FACTOR ANALYSIS (Lineer Regresyon)
factor_scaler = MinMaxScaler()
X_scaled_factors = factor_scaler.fit_transform(features)
reg = LinearRegression()
reg.fit(X_scaled_factors, ghg_values)
coefs = reg.coef_
factors = ["Faktör 1", "Faktör 2", "Faktör 3"]
effects = ["Pozitif" if c > 0 else "Negatif" for c in coefs]

# Grafik
plt.figure(figsize=(8, 5))
bars = plt.bar(factors, coefs, color=["green" if c > 0 else "red" for c in coefs])
plt.title("Faktörlerin GHG Emisyonuna Etkisi")
plt.axhline(0, color="black", linewidth=0.8)
plt.ylabel("Etki Katsayısı")
for bar, value in zip(bars, coefs):
    plt.text(bar.get_x() + bar.get_width()/2, bar.get_height(), f"{value:.2f}", ha="center", va="bottom" if value > 0 else "top")
plt.tight_layout()
plt.show()

# 📌 9. RESULTS
past_years = years[time_steps:]
results_past = pd.DataFrame({
    "Yıl": past_years,
    "Gerçek GHG": y_actual_all,
    "Tahmin GHG": predicted_all
})
results_future = pd.DataFrame({
    "Yıl": future_years,
    "Gerçek GHG": [np.nan] * n_future,
    "Tahmin GHG": future_predictions
})
full_results = pd.concat([results_past, results_future], ignore_index=True)
print("\n📌 Model Tahmin Sonuçları Tablosu (1993–2030):")
print(full_results.to_string(index=False))
