from flask import Flask, request, session
from flask_cors import CORS
import utils.spotify_services as sp
from utils.date_handler import get_3weeks
from utils.csv_gen import generate_csv

app = Flask(__name__)
app.secret_key = ""
app.config["CORS_HEADERS"] = "Content-Type"
CORS(app)

@app.route('/playlist', methods=['GET', 'POST'])
def playlist():
    query = request.get_json()
    country = query['country']
    code = query['code']

    if 'auth_header' not in session:
        sp.authorize(code)

    auth_header = session['auth_header']
    interval = get_3weeks()
    tracklist = generate_csv(interval, country)
    playlist_id = sp.create_playlist(auth_header, country)  # create the playlist
    sp.fill_playlist(tracklist, playlist_id, auth_header)  # fill the playlist
    url = f'http://open.spotify.com/playlist/{playlist_id}'
    return {'url': url}

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