from flask import Flask, request, jsonify
from flask_cors import CORS

import pandas as pd
import numpy as np

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

app = Flask(__name__)
CORS(app)

@app.route('/api/', methods=['POST'])
def check_score():
    data = request.get_json()
    print(data)
    old_intercept = data['old_intercept']
    new_intercept = data['new_intercept']
    old_coef = np.array(data['old_coef'])
    new_coef = np.array(data['new_coef'])
    n = data['n']

    df = pd.read_csv('./data/Fish.csv')
    _, df_test = train_test_split(df, test_size=0.2, shuffle=True, random_state=12)

    X_test = df_test[['Height', 'Width']]
    y_test = df_test['Weight']

    model = LinearRegression()

    model.intercept_ = old_intercept
    model.coef_ = old_coef
    pred_old = model.predict(X_test)

    model.intercept_ = (n * old_intercept + new_intercept) / n + 1
    model.coef_ = (n * old_coef + new_coef) / n + 1
    pred_fl = model.predict(X_test)
    
    old_score = np.sqrt(mean_squared_error(y_test, pred_old))
    fl_score = np.sqrt(mean_squared_error(y_test, pred_fl))
    result = {'score': fl_score,
                'old_score': old_score,
                'best': 1 if fl_score <= old_score else 0}
    return jsonify(result)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')