# -- Code Cell --
import pandas as pd 
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

# -- Code Cell --
df = pd.read_csv("dataset.csv")
df.head(5)

# -- Code Cell --
df["Timestamp"] = pd.to_datetime(df["Timestamp"])

# -- Code Cell --
all_points = []
time_stamps = []
y_pred = []

# -- Code Cell --
for i, stm in enumerate(pd.unique(df["Name"])):
    df_stm = df[df["Name"] == stm]
    kmn = KMeans(5, random_state=42, n_init=10)
    kmn.fit(df_stm[["X", "Y"]])
    cnt = kmn.cluster_centers_
    cnt = cnt[cnt[:, 0].argsort()]  # sort rows by X (column 0)
    time_stamps.extend([(df_stm["Timestamp"].iloc[0] - df["Timestamp"].iloc[0]).total_seconds() for i in range(5)])
    all_points.extend(cnt.tolist())
    y_pred.extend([1, 2, 3, 4, 5])

# -- Code Cell --
all_points = np.array(all_points)

# -- Code Cell --
plt.scatter(all_points[:, 0], all_points[:, 1])

# -- Code Cell --
df_idk = pd.DataFrame({
        "X" :all_points[:, 0],
        "y" :all_points[:, 1],
        "time_dif" : time_stamps,
        "class" : y_pred 
})

# -- Code Cell --
df_1 = df_idk[df_idk["class"] == 1]

# -- Code Cell --
from datetime import datetime
from sklearn.linear_model import RANSACRegressor, LinearRegression
plt.scatter(df_1["X"], df_1["y"])

# -- Code Cell --
df_pred_3 = pd.DataFrame({})

# -- Code Cell --
# Build ordered timestamp strings matching df_idk's row order
ordered_names = list(pd.unique(df["Name"]))  # insertion order, matches df_idk
name_to_ts = {
    name: df[df["Name"] == name]["Timestamp"].iloc[0].strftime('%b %d, %Y, %I:%M:%S %p')
    for name in ordered_names
}
for i in range(5):
    df_1 = df_idk[df_idk["class"] == i+1].reset_index(drop=True)
    r_x = RANSACRegressor(LinearRegression(), min_samples=2, residual_threshold=0.8, random_state=42)
    r_y = RANSACRegressor(LinearRegression(), min_samples=2, residual_threshold=0.8, random_state=42)
    r_x.fit(df_1[["time_dif"]], df_1["X"])
    df_1["X"] = r_x.predict(df_1[["time_dif"]])
    r_y.fit(df_1[["time_dif"]], df_1["y"])
    df_1["y"] = r_y.predict(df_1[["time_dif"]])
    dff = pd.DataFrame({
    "id": [f"{name_to_ts[name]}|{i}" for name in ordered_names],
    "subtaskID": "task3",
    "answer": [f"{df_1['X'].iloc[j]:.4f}|{df_1['y'].iloc[j]:.4f}" for j in range(len(df_1))]
})
    df_pred_3 = pd.concat([df_pred_3, dff])

# -- Code Cell --
df_pred_3.to_csv("subi.csv", index= False)

# -- Code Cell --
