import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.stats.diagnostic import het_breuschpagan
import statsmodels.api as sm

sns.set_theme(style="whitegrid")
np.random.seed(42)
n_samples = 500

sqft = np.random.normal(2100, 500, n_samples).clip(800, 4500)
bedrooms = np.random.choice([1, 2, 3, 4, 5], size=n_samples, p=[0.1, 0.25, 0.4, 0.2, 0.05])
dist_transit = np.random.exponential(scale=4.0, size=n_samples).clip(0.5, 20.0)
age = np.random.uniform(1, 40, n_samples)
school_rating = np.random.uniform(3.0, 9.8, n_samples)

noise = np.random.normal(0, 25000, n_samples)
price = (150 * sqft) + (12000 * bedrooms) - (8500 * dist_transit) - (1500 * age) + (9000 * school_rating) + 50000 + noise

df = pd.DataFrame({
    "Square_Footage": sqft, "Number_of_Bedrooms": bedrooms, "Distance_to_Transit_km": dist_transit,
    "Age_of_Property": age, "School_Rating": school_rating, "House_Price": price,
})
print("Dataset Head:")
display(df.head())

fig, axes = plt.subplots(1, 2, figsize=(15, 5))
sns.heatmap(df.corr(), annot=True, fmt=".2f", cmap="coolwarm", ax=axes[0]); axes[0].set_title("Correlation matrix")
sns.scatterplot(data=df, x="Square_Footage", y="House_Price", alpha=.5, ax=axes[1]); axes[1].set_title("Price vs square footage")
plt.tight_layout(); plt.show()

features = ["Square_Footage", "Number_of_Bedrooms", "Distance_to_Transit_km", "Age_of_Property", "School_Rating"]
X = df[features]
Y = df["House_Price"]
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.20, random_state=42)
print(f"Training Set Shape: {X_train.shape}")
print(f"Testing Set Shape:  {X_test.shape}")

model = LinearRegression()
model.fit(X_train, Y_train)

true_beta = {"Square_Footage": 150, "Number_of_Bedrooms": 12000, "Distance_to_Transit_km": -8500,
             "Age_of_Property": -1500, "School_Rating": 9000}
coefficients = pd.DataFrame({
    "Feature": X.columns,
    "Coefficient (Beta)": model.coef_,
    "True value": [true_beta[f] for f in X.columns],
})
print(f"Intercept (Beta_0): ${model.intercept_:,.2f}  (true value 50,000)\n")
print("Learned Feature Coefficients:")
print(coefficients.round(2).to_string(index=False))

Y_pred = model.predict(X_test)
mae = mean_absolute_error(Y_test, Y_pred)
mse = mean_squared_error(Y_test, Y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(Y_test, Y_pred)
n, p = len(Y_test), X_test.shape[1]
adj_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)

print("--- MODEL PERFORMANCE METRICS (test set) ---")
print(f"Mean Absolute Error (MAE)       : ${mae:,.2f}")
print(f"Mean Squared Error (MSE)        : {mse:,.2f}")
print(f"Root Mean Squared Error (RMSE)  : ${rmse:,.2f}")
print(f"R-squared Score (R2)            : {r2:.4f}")
print(f"Adjusted R-squared Score        : {adj_r2:.4f}")

residuals = Y_test - Y_pred

# VIF is computed on a design matrix that includes the intercept term
Xc = sm.add_constant(X)
vif_data = pd.DataFrame({
    "Feature": X.columns,
    "VIF": [variance_inflation_factor(Xc.values, i + 1) for i in range(X.shape[1])],
})
print("--- VARIANCE INFLATION FACTOR (VIF) ---")
print(vif_data.round(3).to_string(index=False))

X_train_sm = sm.add_constant(X_train)
ols_model = sm.OLS(Y_train, X_train_sm).fit()
print(ols_model.summary())

fig, axes = plt.subplots(1, 3, figsize=(18, 5))
sns.histplot(residuals, kde=True, ax=axes[0], color="teal"); axes[0].axvline(0, color="k", ls="--"); axes[0].set_title("Residual distribution")
stats.probplot(residuals, dist="norm", plot=axes[1]); axes[1].set_title("Q-Q plot of residuals")
axes[2].scatter(Y_pred, residuals, alpha=.6); axes[2].axhline(0, color="r", ls="--")
axes[2].set_title("Residuals vs fitted values"); axes[2].set_xlabel("Fitted"); axes[2].set_ylabel("Residual")
plt.tight_layout(); plt.show()

bp_stat, bp_p, _, _ = het_breuschpagan(ols_model.resid, ols_model.model.exog)
sw_stat, sw_p = stats.shapiro(residuals)
print(f"Breusch-Pagan test p-value : {bp_p:.4f}  ->", "no evidence of heteroscedasticity" if bp_p > 0.05 else "heteroscedasticity detected")
print(f"Shapiro-Wilk test p-value  : {sw_p:.4f}  ->", "residuals consistent with normality" if sw_p > 0.05 else "residuals deviate from normality")
print(f"Mean of residuals          : {residuals.mean():,.2f}")
