import jwt  # PyJWT
from jwt import InvalidTokenError
from jwt import ExpiredSignatureError
import os
from flask import jsonify, abort, session
from deezer_downloader.configuration import config

#def setJwtInCookieToResponse(request, response):
#    jwt_token = request.args.get("jwt")
#    if not jwt_token:
#        return response
#    
#    response.set_cookie(
#        "access_token",
#        jwt_token,
#        max_age=60*60*24,
#        httponly=True,
#        secure=True  # True si HTTPS
#    )
#    return response

def addJwtInUserSession(request):
    if 'user_uid' in session:
        return
    
    jwt_token = request.args.get(config["nextcloud"]["jwt_name_parameter"])
    if not jwt_token:
        return abort(403)
    
    try:
        decoded = jwt.decode(jwt_token, config["nextcloud"]["public_key"], algorithms=["ES256"])
        iss = decoded.get("iss")
        iat = decoded.get("iat")
        exp = decoded.get("exp")
        userdata = decoded.get("userdata", {})
        email = userdata.get("email")
        uid = userdata.get("uid")
        display_name = userdata.get("displayName")

        print("✅ JWT décodé :")
        print("Iss:", iss)
        print("Issued At:", iat)
        print("Expires:", exp)
        print("Email:", email)
        print("UID:", uid)
        print("Display Name:", display_name)

        session['user_uid'] = uid 
        session['user_email'] = email 
        session['user_displayName'] = display_name 
        session['user_base_dir'] = config["download_dirs"]["base"]
        
        print(f"✅ Download base dir set to: {session['user_base_dir']}")
    except ExpiredSignatureError:
        abort(403)
    except InvalidTokenError as e:
        print("❌ Erreur de validation du token :", e)