"""
Project 3 - Vessel type classification
Starter code: download the data, compute two very simple features per track,
train a 1-nearest-neighbour classifier, and write a valid submission file

Usage:
    python starter_code.py

Requirements: scikit-learn, pandas
"""
import os

import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer

DATA_DIR = "Data"

# ----------------------------------------------------------------------------
# Data
# ----------------------------------------------------------------------------

def load_data(data_dir=DATA_DIR):
    """Return the learning data and the test data.
    
    All files in the archive ("data.zip") are expected to be present in the
    DATA_DIR directory.
    """
    def read(name, **kw):
        return pd.read_csv(os.path.join(data_dir, name), **kw)
    train_tracks = read("train_tracks.csv")
    train_static = read("train_static.csv", index_col="track_id")
    train_labels = read("train_labels.csv", index_col="track_id")
    test_tracks = read("test_tracks.csv")
    test_static = read("test_static.csv", index_col="track_id")
    return train_tracks, train_static, train_labels, test_tracks, test_static


def compute_features(tracks, static):
    """Turn each track (a variable number of rows) into a fixed-size feature vector.

    This naive version only uses two features: the mean speed over ground, computed from
    the track, and the length of the ship.
    """
    g = tracks.groupby("track_id")
    X = pd.DataFrame({
        "sog_mean": g["sog"].mean(),
    })
    X = X.join(static[["length"]])   # missing lengths stay NaN (needs to be handled in the model)
    return X


def write_submission(track_ids, predictions, probabilities, classes, estimated_score,
                     path="submission.csv"):
    """Write a submission file in the expected format.

    Columns: Id, Predicted, then one column P_<class> per class with the predicted probabilities.
    The second line contains your estimation of the accuracy of your model on the test set.
    """
    sub = pd.DataFrame({"Id": track_ids, "Predicted": predictions})
    for k, c in enumerate(classes):
        sub[f"P_{c}"] = probabilities[:, k]
    with open(path, "w") as f:
        f.write(",".join(sub.columns) + "\n")
        f.write(f"Estimated,{estimated_score}" + ",0" * len(classes) + "\n")
        sub.to_csv(f, index=False, header=False)
    print(f"Submission written to '{path}' ({len(sub)} tracks).")


# ----------------------------------------------------------------------------
if __name__ == "__main__":

    train_tracks, train_static, train_labels, test_tracks, test_static = load_data()
    print(f"Learning set: {train_labels.shape[0]} tracks, {len(train_tracks)} positions")
    print(f"Test set:     {test_tracks.track_id.nunique()} tracks, {len(test_tracks)} positions")

    X_train = compute_features(train_tracks, train_static)
    train_labels = train_labels.loc[X_train.index]
    y_train = train_labels["label"].values
    groups = train_labels["vessel_id"].values

    estimated_accuracy = 0.0 # to replace with an estimation of the accuracy

    # test a simple 1-NN model on standardised features and missing values replaced by the
    # median
    model = make_pipeline(SimpleImputer(strategy="median"), StandardScaler(),
                         KNeighborsClassifier(n_neighbors=1))
    
    model.fit(X_train, y_train)
    X_test = compute_features(test_tracks, test_static)
    # Note that for a 1-NN, the predicted probabilities are 0 or 1
    write_submission(X_test.index, model.predict(X_test), model.predict_proba(X_test),
                     classes=model.classes_, estimated_score=estimated_accuracy)
