import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

df = pd.read_csv('./data_2.csv')
print(f"Initial shape: {df.shape}")

df = df.drop_duplicates()

df = df.fillna(df.mean(numeric_only=True))

print(f"Cleaned shape: {df.shape}")
print(df.head())

X = df[['Study_Hours']]
y = df['Final_Score']

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.20, random_state=42
)

print(f"Training samples: {len(X_train)}")
print(f"Testing samples : {len(X_test)}")

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

slope = model.coef_[0]
intercept = model.intercept_

print(f"Slope (m)    : {slope:.4f}")
print(f"Intercept (c): {intercept:.4f}")
print(f"Equation     : Final_Score = ({slope:.2f} * Study_Hours) + {intercept:.2f}")

y_pred = model.predict(X_test)

mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print(f"Mean Squared Error (MSE) : {mse:.2f}")
print(f"R-squared Score (R2)     : {r2:.4f}")

plt.figure(figsize=(7, 4))
plt.scatter(X, y, color='blue', alpha=0.5, label='Actual Data')
plt.plot(X, model.predict(X), color='red', linewidth=2, label='Fitted Line')
plt.xlabel("Hours Studied")
plt.ylabel("Final Score")
plt.title("Study Hours vs Final Score (Linear Regression)")
plt.legend()
plt.grid(True, linestyle='--', alpha=0.5)
plt.show()
