
from flask import session, render_template, redirect, request, url_for, jsonify, Response, stream_with_context
from flask_login import (
    current_user,
    login_user,
    logout_user
)

from flask_dance.contrib.github import github
from yaml import safe_load, dump 
from os import path, makedirs, remove

from apps import db, login_manager
from apps.authentication import blueprint
from apps.authentication.forms import LoginForm, CreateAccountForm
from apps.authentication.models import Users, ConfigUpdates

from apps.authentication.util import verify_pass
import json
import httpx
import subprocess
import time
import requests
import instaloader
import asyncio

from bs4 import BeautifulSoup

from io import BytesIO
from PIL import Image
from datetime import datetime
from apify_client import ApifyClient
from shutil import copyfile

client = ApifyClient("apify_api_81ye2bXaSCqldjha7EwqLXLrpsCeZF3Yl0ut")
base_dir = path.dirname(path.abspath(__file__))
profile_output_dir = path.join(base_dir, "..", "static", "assets", "img", "team")
img_output_dir = path.join(base_dir, "..", "static", "assets", "img")
    
    
@blueprint.route('/')
def route_default():
    return redirect(url_for('authentication_blueprint.login'))

# Login & Registration

@blueprint.route("/github")
def login_github():
    """ Github login """
    if not github.authorized:
        return redirect(url_for("github.login"))

    res = github.get("/user")
    return redirect(url_for('home_blueprint.dashboard'))

@blueprint.route('/login', methods=['GET', 'POST'])
def login():
    login_form = LoginForm(request.form)
    if 'login' in request.form:

        # read form data
        username = request.form['username']
        password = request.form['password']

        # Locate user
        user = Users.query.filter_by(username=username).first()

        # Check the password
        if user and verify_pass(password, user.password):
            login_user(user)
            return redirect(url_for('home_blueprint.dashboard'))
            
        # Something (user or pass) is not ok
        return render_template('accounts/login.html',
                               msg='Utilisateur ou mot de passe incorrect',
                               form=login_form)

    if not current_user.is_authenticated:
        return render_template('accounts/login.html',
                               form=login_form)
    return redirect(url_for('home_blueprint.dashboard'))


@blueprint.route('/register', methods=['GET', 'POST'])
def register():
    create_account_form = CreateAccountForm(request.form)
    if 'register' in request.form:

        username = request.form['username']
        email = request.form['email']

        # Check if the username exists
        user = Users.query.filter_by(username=username).first()
        if user:
            return render_template('accounts/register.html',
                                   msg='Utilisateur déjà inscrit',
                                   success=False,
                                   form=create_account_form)

        # Check if the email exists
        user = Users.query.filter_by(email=email).first()
        if user:
            return render_template('accounts/register.html',
                                   msg='Email déjà enregistré',
                                   success=False,
                                   form=create_account_form)

        # else we can create the user
        user = Users(**request.form)
        db.session.add(user)
        db.session.commit()

        create_default_picture_for_user(username)

        # Delete user from session after registration
        logout_user()

        return render_template('accounts/register.html',
                               msg='Compte créé avec succès.',
                               success=True,
                               form=create_account_form)

    else:
        return render_template('accounts/register.html', form=create_account_form)

def create_default_picture_for_user(username):
    default_profile_picture = path.join(profile_output_dir, "profile-picture-1.jpg")
    default_profile_cover_picture = path.join(img_output_dir, "profile-cover-picture-1.jpg")
    custom_profile_picture_path = path.join(profile_output_dir, f"profile-picture-{username}.jpg")
    custom_profile_cover_picture_path = path.join(img_output_dir, f"profile-cover-picture-{username}.jpg")
    
    if not path.exists(default_profile_picture):
        raise FileNotFoundError(f"La photo de profil par défaut {default_profile_picture} est introuvable.")

    if not path.exists(default_profile_cover_picture):
        raise FileNotFoundError(f"La photo de couverture par défaut {default_profile_cover_picture} est introuvable.")
    
    copyfile(default_profile_picture, custom_profile_picture_path)
    copyfile(default_profile_cover_picture, custom_profile_cover_picture_path)
    
@blueprint.route('/logout')
def logout():
    logout_user()
    session.pop('profile_data', None)
    session.pop('today_date', None)
    
    return redirect(url_for('authentication_blueprint.login'))

async def update_profiles(user_id):
    users = ConfigUpdates.query.filter_by(user_id=user_id).all()
    if not users:
        print("Aucun utilisateur trouvé pour ce user_id")
        return []

    usernames = [user.insta_username for user in users]

    results = await scrape_user(usernames)

    for user in users:
        if user.insta_username in results:
            result = results[user.insta_username]

            user.followers_count = result['followersCount']
            user.following_count = result['followsCount']
            user.posts_count = result['postsCount']

            convert_image_to_jpg(result['profilePicUrl'], user.insta_username)

            print(f"Profil mis à jour pour : {user.insta_username}")
        else:
            print(f"Aucune donnée pour {user.insta_username}")

    db.session.commit()

    profile_data = [{
        'insta_username': user.insta_username,
        'followers_count': user.followers_count,
        'following_count': user.following_count,
        'posts_count': user.posts_count
    } for user in users]

    return profile_data

@blueprint.route('/treatment', methods=['GET', 'POST'])
def treatment():
    try:
        config_updates = {
            "insta_username": request.form.get("insta-username", ""),
            "app_id": request.form.get("app-id", ""),
            "speed_multiplier": request.form.get("speed-multiplier", "1"),
            "use_cloned_app": request.form.get("use-cloned-app", "false") == "on",
            "allow_untested_ig_version": request.form.get("allow-untested-ig-version", "false") == "on",
            "screen_sleep": request.form.get("screen-sleep", "false") == "on",
            "screen_record": request.form.get("screen-record", "false") == "on",
            "debug": request.form.get("debug", "false") == "on",
            "close_apps": request.form.get("close-apps", "false") == "on",
            "kill_atx_agent": request.form.get("kill-atx-agent", "false") == "on",
            "restart_atx_agent": request.form.get("restart-atx-agent", "false") == "on",
            "disable_block_detection": request.form.get("disable-block-detection", "false") == "on",
            "disable_filters": request.form.get("disable-filters", "false") == "on",
            "dont_type": request.form.get("dont-type", "false") == "on",
            
            # Sources
            "blogger_followers": process_list_input(request.form.get("blogger-followers", "")),
            "blogger_following": process_list_input(request.form.get("blogger-following", "")),
            "blogger_post_likers": process_list_input(request.form.get("blogger-post-likers", "")),
            "blogger": process_list_input(request.form.get("blogger", "")),
            "hashtag_likers_top": process_list_input(request.form.get("hashtag-likers-top", "")),
            "hashtag_likers_recent": process_list_input(request.form.get("hashtag-likers-recent", "")),
            "hashtag_posts_top": process_list_input(request.form.get("hashtag-posts-top", "")),
            "hashtag_posts_recent": process_list_input(request.form.get("hashtag-posts-recent", "")),
            "place_posts_top": process_list_input(request.form.get("place-posts-top", "")),
            "place_posts_recent": process_list_input(request.form.get("place-posts-recent", "")),
            "place_likers_top": process_list_input(request.form.get("place-likers-top", "")),
            "place_likers_recent": process_list_input(request.form.get("place-likers-recent", "")),
            "interact_from_file": process_list_input(request.form.get("interact-from-file", "")),
            "posts_from_file": process_list_input(request.form.get("posts-from-file", "")),
            "working_hours": process_list_input(request.form.get("working-hours", "")),
            "remove_followers_from_file": process_list_input(request.form.get("remove-followers-from-file", "")),
            "delete_removed_followers": request.form.get("delete-removed-followers", "false") == "on",
            "unfollow_from_file": process_list_input(request.form.get("unfollow-from-file", "")),
            
            # Actions
            "feed_likes": request.form.get("feed-likes", "0"),
            "unfollow": request.form.get("unfollow", "0"),
            "unfollow_any": request.form.get("unfollow-any", "0"),
            "unfollow_non_followers": request.form.get("unfollow-non-followers", "0"),
            "unfollow_any_non_followers": request.form.get("unfollow-any-non-followers", "0"),
            "unfollow_any_followers": request.form.get("unfollow-any-followers", "0"),
            "delete_interacted_users": request.form.get("delete-interacted-users", "false") == "on",
            "sort_followers": request.form.get("sort-followers", "false") == "on",
            "unfollow_delay": request.form.get("unfollow-delay", "15"),
            
            # Temps d'interaction
            "watch_video_time": request.form.get("watch-video-time", "15-35"),
            "watch_photo_time": request.form.get("watch-photo-time", "3-4"),
            
            # Limites
            "interactions_count": request.form.get("interactions-count", "0"),
            "likes_count": request.form.get("like-count", "0"),
            "likes_percentage": request.form.get("likes-percentage", "100"),
            "stories_count": request.form.get("stories-count", "0"),
            "stories_percentage": request.form.get("stories-percentage", "100"),
            "max_comments_pro_user": request.form.get("max-comments-pro-user", "1-2"),
            "interact_percentage": request.form.get("interact-percentage", "30-40"),
            "follow_percentage": request.form.get("follow-percentage", "30-40"),
            "follow_limit": request.form.get("follow-limit", "0"),
            "skipped_list_limit": request.form.get("skipped-list-limit", "10-15"),
            "skipped_posts_limit": request.form.get("skipped-posts-limit", "5"),
            "min_following": request.form.get("min-following", "0"),
            "total_likes_limit": request.form.get("total-likes-limit", "0"),
            "total_comments_limit": request.form.get("total-comments-limit", "0"),
            "total_pm_limit": request.form.get("total-pm-limit", "0"),
            
            "total_follows_limit": request.form.get("total-follows-limit", "0"),
            "total_unfollows_limit": request.form.get("total-unfollows-limit", "0"),
            "total_watches_limit": request.form.get("total-watches-limit", "0"),
            "total_successful_interactions_limit": request.form.get("total-successful-interactions-limit", "0"),
            "total_interactions_limit": request.form.get("total-interactions-limit", "0"),
            "total_sessions": request.form.get("total-sessions", "1"),
            
            # Terminer si la limite est atteinte
            "end_if_likes_limit_reached": request.form.get("end-if-likes-limit-reached", "false") == "on",
            "end_if_follows_limit_reached": request.form.get("end-if-follows-limit-reached", "false") == "on",
            "end_if_watches_limit_reached": request.form.get("end-if-watches-limit-reached", "false") == "on",
            "end_if_comments_limit_reached": request.form.get("end-if-comments-limit-reached", "false") == "on",
            "end_if_pm_limit_reached": request.form.get("end-if-pm-limit-reached", "false") == "on",
            
            # Répétitions et délais
            "repeat": request.form.get("repeat", "280-320"),
            "time_delta": request.form.get("time-delta", "10-15"),
        }

        # Sauvegarde dans la base de données
        config_update = ConfigUpdates(
            user_id=current_user.id,
            **config_updates
        )
        db.session.add(config_update)
        db.session.commit()

        print("Configuration sauvegardée avec succès dans la base de données !")

        profile_data = asyncio.run(update_profiles(current_user.id))
        today_date = datetime.now().strftime("%d/%m/%Y")

        session['profile_data'] = profile_data
        session['today_date'] = today_date

        # Exportation dans le fichier config.yml
        insta_username = config_updates["insta_username"]
        user_dir = path.join(base_dir, "..", "..", "accounts", insta_username)
        makedirs(user_dir, exist_ok=True)
        config_file_path = path.join(user_dir, "config.yml")

        if path.exists(config_file_path):
            remove(config_file_path)

        try:
            with open(config_file_path, "r") as file:
                config_data = safe_load(file)
        except FileNotFoundError:
            config_data = {}

        # Mise à jour du fichier YAML
        config_data.update({
            "username": config_updates["insta_username"],
            "app-id": config_updates["app_id"],
            "speed-multiplier": config_updates["speed_multiplier"],
            "use-cloned-app": config_updates["use_cloned_app"],
            "allow-untested-ig-version": config_updates["allow_untested_ig_version"],
            "screen-sleep": config_updates["screen_sleep"],
            "screen-record": config_updates["screen_record"],
            "debug": config_updates["debug"],
            "close-apps": config_updates["close_apps"],
            "kill-atx-agent": config_updates["kill_atx_agent"],
            "restart-atx-agent": config_updates["restart_atx_agent"],
            "disable-block-detection": config_updates["disable_block_detection"],
            "disable-filters": config_updates["disable_filters"],
            "dont-type": config_updates["dont_type"],
            # Sources (extraction des données JSON directement depuis la table)
            "blogger-followers": config_updates["blogger_followers"],
            "blogger-following": config_updates["blogger_following"],
            "blogger-post-likers": config_updates["blogger_post_likers"],
            "blogger": config_updates["blogger"],
            "hashtag-likers-top": config_updates["hashtag_likers_top"],
            "hashtag-likers-recent": config_updates["hashtag_likers_recent"],
            "hashtag-posts-top": config_updates["hashtag_posts_top"],
            "hashtag-posts-recent": config_updates["hashtag_posts_recent"],
            "place-posts-top": config_updates["place_posts_top"],
            "place-posts-recent": config_updates["place_posts_recent"],
            "place-likers-top": config_updates["place_likers_top"],
            "place-likers-recent": config_updates["place_likers_recent"],
            "interact-from-file": config_updates["interact_from_file"],
            "posts-from-file": config_updates["posts_from_file"],
            "delete-interacted-users": config_updates["delete_interacted_users"],
            "working-hours": config_updates["working_hours"],
            # Temps d'interaction
            "watch-video-time": config_updates["watch_video_time"],
            "watch-photo-time": config_updates["watch_photo_time"],
            # Actions
            "feed": config_updates["feed_likes"],
            "unfollow": config_updates["unfollow"],
            "unfollow-any": config_updates["unfollow_any"],
            "unfollow-non-followers": config_updates["unfollow_non_followers"],
            "unfollow-any-non-followers": config_updates["unfollow_any_non_followers"],
            "unfollow-any-followers": config_updates["unfollow_any_followers"],
            "unfollow-from-file": config_updates["unfollow_from_file"],
            "sort-followers-newest-to-oldest": config_updates["sort_followers"],
            "unfollow-delay": config_updates["unfollow_delay"],
            "remove-followers-from-file": config_updates["remove_followers_from_file"],
            "delete-removed-followers": config_updates["delete_removed_followers"],
            # Limites
            "interactions-count": config_updates["interactions_count"],
            "likes-count": config_updates["likes_count"],
            "likes-percentage": config_updates["likes_percentage"],
            "stories-count": config_updates["stories_count"],
            "stories-percentage": config_updates["stories_percentage"],
            "max-comments-pro-user": config_updates["max_comments_pro_user"],
            "interact-percentage": config_updates["interact_percentage"],
            "follow-percentage": config_updates["follow_percentage"],
            "follow-limit": config_updates["follow_limit"],
            "skipped-list-limit": config_updates["skipped_list_limit"],
            "skipped-posts-limit": config_updates["skipped_posts_limit"],
            "min-following": config_updates["min_following"],
            "total-likes-limit": config_updates["total_likes_limit"],
            "total-follows-limit": config_updates["total_follows_limit"],
            "total-unfollows-limit": config_updates["total_unfollows_limit"],
            "total-watches-limit": config_updates["total_watches_limit"],
            "total-successful-interactions-limit": config_updates["total_successful_interactions_limit"],
            "total-interactions-limit": config_updates["total_interactions_limit"],
            "total-comments-limit": config_updates["total_comments_limit"],
            "total-pm-limit": config_updates["total_pm_limit"],
            "end-if-likes-limit-reached": config_updates["end_if_likes_limit_reached"],
            "end-if-follows-limit-reached": config_updates["end_if_follows_limit_reached"],
            "end-if-watches-limit-reached": config_updates["end_if_watches_limit_reached"],
            "end-if-comments-limit-reached": config_updates["end_if_comments_limit_reached"],
            "end-if-pm-limit-reached": config_updates["end_if_pm_limit_reached"],
            # Sessions
            "repeat": config_updates["repeat"],
            "total-sessions": config_updates["total_sessions"],
            "time-delta": config_updates["time_delta"],
       })

        with open(config_file_path, "w") as file:
            dump(config_data, file, default_flow_style=False, sort_keys=False)
        
        clear_file(config_file_path)

        print("Configuration exportée avec succès!")

        return jsonify({
            "success": True,
            "message": f"Traitement et sauvegarde du paramétrage du profil \"{insta_username}\" exécutés avec succès!"
        }), 200

        #return render_template('home/dashboard.html', profile_data=profile_data, today_date=today_date)

    except Exception as e:
        print(f"Erreur lors de la validation et sauvegarde du profil : {str(e)}")
        return render_template('home/page-500.html'), 500

@blueprint.route('/refresh_profiles', methods=['GET', 'POST'])
def refresh_profiles():
    try:
        profile_data = asyncio.run(update_profiles(current_user.id))
        today_date = datetime.now().strftime("%d/%m/%Y")

        session['profile_data'] = profile_data
        session['today_date'] = today_date

        return jsonify({"success": True, "message": "Configuration et mise à jour profil exécutées avec succès!"}), 200

    except Exception as e:
        print(f"Erreur lors de la mise à jour : {str(e)}")
        return render_template('home/page-500.html'), 500
        
@blueprint.route('/search-profile', methods=['GET', 'POST'])
def search_profile():
    query = request.json.get('query', '').strip()

    profile_data = session.get('profile_data', [])

    matching_profiles = [
        profile 
        for profile in profile_data 
        if query.lower() in profile['insta_username'].lower()
    ]

    if not matching_profiles:
        return jsonify({"success": False, "message": "Aucun profil correspondant."}), 404

    return jsonify({"success": True, "profiles": matching_profiles}), 200

@blueprint.route('/filter', methods=['POST'])
def filter():
    try:
        data = request.get_json()
        
        filter_insta_username = data.get('filter_insta_username')
        
        user_dir = path.join(base_dir, "..", "..", "accounts", filter_insta_username)  
        
        makedirs(user_dir, exist_ok=True)  

        filters_file_path = path.join(user_dir, "filters.yml")

        try:
            with open(filters_file_path, "r") as file:
                filter_data = safe_load(file)
        except FileNotFoundError:
            filter_data = {}

        filter_updates = {
            "skip_if_private": data.get("skip_if_private", "false") == "on",
            "skip_if_public": data.get("skip_if_public", "false") == "on",
            "skip_business": data.get("skip_business", "false") == "on",
            "skip_non_business": data.get("skip_non_business", "false") == "on",
            "skip_following": data.get("skip_following", "false") == "on",
            "skip_follower": data.get("skip_follower", "false") == "on",
            "skip_if_link_in_bio": data.get("skip_if_link_in_bio", "false") == "on",
            "follow_private_or_empty": data.get("follow_private_or_empty", "false") == "on",
        }

        for key, value in filter_updates.items():
            filter_data[key] = value

        with open(filters_file_path, "w") as file:
            dump(filter_data, file, default_flow_style=False, sort_keys=False)

        clear_file(filters_file_path)

        return jsonify({"success": True, "message": "Filtres mis à jour avec succès"}), 200

    except Exception as e:
        print(f"Erreur lors de mise à jour des filtres : {str(e)}")
        return jsonify({"success": False, "message": "Erreur lors de mise à jour des filtres."}), 500

@blueprint.route('/update_interaction', methods=['POST'])
def update_interaction():
    if not current_user.is_authenticated:
        return jsonify({'error': 'User not authenticated'}), 401

    user = Users.query.get(current_user.id)

    if not user:
        return jsonify({'error': 'User not found'}), 404

    user.interaction_count = request.json.get('interaction_count', user.interaction_count)
    db.session.commit()

    return jsonify({'success': True, 'interaction_count': user.interaction_count})

@blueprint.route('/get_interaction', methods=['GET'])
def get_interaction():
    if not current_user.is_authenticated:
        return jsonify({'error': 'User not authenticated'}), 401

    user = Users.query.get(current_user.id)

    if not user:
        return jsonify({'error': 'User not found'}), 404
    
    return jsonify({'interaction_count': user.interaction_count})

@blueprint.route('/launch_bot', methods=['GET', 'POST'])
def launch_bot():
    insta_username = request.args.get('insta_username')

    if not insta_username:
        return 'Nom d\'utilisateur Instagram manquant', 400

    config_path = f"accounts/{insta_username}/config.yml"
    
    def generate_logs():
        try:
            process = subprocess.Popen(
                ['python3', 'run_bot.py', '--config', config_path],
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                bufsize=1,
            )
            for line in iter(process.stdout.readline, ''):
                yield f"data: {line.strip()}\n\n"
            process.stdout.close()
            process.wait()
            if process.returncode != 0:
                yield f"data: Erreur lors de l'exécution du bot. Code retour : {process.returncode}\n\n"
        except Exception as e:
            yield f"data: Une erreur s'est produite : {str(e)}\n\n"

    return Response(stream_with_context(generate_logs()), content_type='text/event-stream')

def process_list_input(input_value):
    if input_value:
        items = [item.strip() for item in input_value.split(',')]
        return f"[ {', '.join(items)} ]"
    return []  

#def scrape_user(username: str, client):
 #           result = client.get(
  #             f"https://i.instagram.com/api/v1/users/web_profile_info/?username={username}",
   #         )
    #        data = json.loads(result.content)
     #       return data["data"]["user"]

async def scrape_user(usernames: list):
    """Scrape plusieurs utilisateurs en une seule fois."""
    try:
        run_input = {
            "usernames": usernames  # Regroupe tous les utilisateurs
        }

        # Appel unique à l'API pour tous les utilisateurs
        run = client.actor("apify/instagram-profile-scraper").call(run_input=run_input)
        dataset_id = run["defaultDatasetId"]
        dataset = client.dataset(dataset_id)

        items = await asyncio.to_thread(list, dataset.iterate_items())

        # Associe les résultats aux noms d'utilisateur
        result = {item['username']: item for item in items}
        return result

    except Exception as e:
        print(f"Erreur lors du scraping : {e}")
        return {}

def clear_file(file_path):
    try:
        with open(file_path, 'r') as file:
            content = file.read()
        
        updated_content = content.replace("'", "")
        
        with open(file_path, 'w') as file:
            file.write(updated_content)
        
    except Exception as e:
        print(f"Une erreur s'est produite : {e}")
        return render_template('home/page-500.html'), 500

def convert_image_to_jpg(image_url, username):
    response = httpx.get(image_url)

    if response.status_code == 200:
        img = Image.open(BytesIO(response.content))
        
        img = img.convert('RGB')  
        output_image_path = path.join(profile_output_dir, username + ".jpg")
        img.save(output_image_path, "JPEG")  

        print(f"Image convertie avec succès sous : {output_image_path})")
        
        return None
    else:
        print(f"Erreur lors du téléchargement de l'image (status code {response.status_code})")
        return None

  
ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png', 'gif'}
    
def get_profile_picture_path():
    filename = f"profile-picture-{current_user.username}.jpg"
    return path.join(profile_output_dir, filename)

def get_profile_cover_picture_path():
    filename = f"profile-cover-picture-{current_user.username}.jpg"
    return path.join(img_output_dir, filename)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@blueprint.route('/upload-profile', methods=['POST'])
def upload_profile():
    if 'file' not in request.files:
        return jsonify({'success': False, 'message': 'Aucun fichier sélectionné.'}), 400

    file = request.files['file']

    if file and allowed_file(file.filename):
        try:
            profile_picture_path = get_profile_picture_path()
            file.save(profile_picture_path)
            return jsonify({'success': True, 'message': 'Image mise à jour avec succès.'}), 200
        except Exception as e:
            return jsonify({'success': False, 'message': f'Erreur lors de l\'enregistrement : {str(e)}'}), 500
    else:
        return jsonify({'success': False, 'message': 'Fichier invalide. Veuillez choisir une image JPG, PNG ou GIF.'}), 400

@blueprint.route('/upload-cover', methods=['POST'])
def upload_cover():
    if 'file' not in request.files:
        return jsonify({'success': False, 'message': 'Aucun fichier sélectionné.'}), 400

    file = request.files['file']

    if file and allowed_file(file.filename):
        try:
            profile_cover_picture_path = get_profile_cover_picture_path()
            file.save(profile_cover_picture_path)
            return jsonify({'success': True, 'message': 'Image mise à jour avec succès.'}), 200
        except Exception as e:
            return jsonify({'success': False, 'message': f'Erreur lors de l\'enregistrement : {str(e)}'}), 500
    else:
        return jsonify({'success': False, 'message': 'Fichier invalide. Veuillez choisir une image JPG, PNG ou GIF.'}), 400

@blueprint.route('/upload_file', methods=['POST'])
def upload_file():
    username = request.form.get('username')
    if not username:
        return jsonify({"success": False, "error": "Nom d'utilisateur manquant."}), 400

    UPLOAD_FOLDER = path.join(path.abspath(path.dirname(__file__)), "..", "..", "accounts", username)  
    makedirs(UPLOAD_FOLDER, exist_ok=True)  

    if 'file' not in request.files:
        return jsonify({"success": False, "error": "Aucun fichier envoyé."}), 400

    file = request.files['file']

    if file.filename == '':
        return jsonify({"success": False, "error": "Aucun fichier sélectionné."}), 400

    try:
        file.save(path.join(UPLOAD_FOLDER, file.filename))
        return jsonify({"success": True, "message": f"Fichier {file.filename} importé avec succès dans le dossier de {username} !"})
    except Exception as e:
        return jsonify({"success": False, "error": str(e)}), 500

# Errors

@login_manager.unauthorized_handler
def unauthorized_handler():
    return render_template('home/page-403.html'), 403


@blueprint.errorhandler(403)
def access_forbidden(error):
    return render_template('home/page-403.html'), 403


@blueprint.errorhandler(404)
def not_found_error(error):
    return render_template('home/page-404.html'), 404


@blueprint.errorhandler(500)
def internal_error(error):
    return render_template('home/page-500.html'), 500
