#assistant_dialogue.py

import json
import webbrowser

def analyser_intention(phrase, base):
    phrase = phrase.lower().strip()  # Mise en minuscule et suppression des espaces inutiles

    # 1. Vérifier les phrases exactes
    for intention, contenu in base.items():
        phrases_exactes = contenu.get("phrases", [])
        
        if phrase in [p.lower() for p in phrases_exactes]:  # Vérifie si la phrase correspond
            return intention

    # 2. Vérifier les mots-clés si aucune phrase exacte ne correspond
    for intention, contenu in base.items():
        mots_cles = contenu.get("mots_cles", [])
        
        for mot in mots_cles:
            if mot in phrase:
                return intention

    # Si aucune correspondance trouvée
    return phrase
#gestion des différentes intentions
def recherche(intention):
    phrase = input( "Dis-moi ce que tu veux chercher sur Google !")
    return traiter_action(intention, phrase)

def video(intention):
    phrase = input( "Quelle vidéo veux-tu regarder sur YouTube ?")
    return traiter_action(intention, phrase)

'''Génération de la réponse à l'intention (penser à créer une fonction de gestion de l'intention)
Si l'intention n'est pas reconnue, l'utilisateur à la posibilité de rajouter une attention
dans la base, où à lier sa phrase à une intention existante.'''
def generer_reponse(intention):
    """Génère une réponse adaptée à l'intention."""
    if intention == "salut":
        return "Salut ! Comment puis-je t'aider ?"
    elif intention == "recherche":
        return recherche(intention)
    elif intention == "youtube":
        return video(intention)
    else:
        base = charger_base_de_donnees()
        print("Ta demande correspond-elle à une des intentions de la base de données :")
        for intentions in base.keys():
            print(f"- {intentions}")
        print(intention)
        intention_demandee = input("Si oui, laquelle? Si non, tape: None : ")
        return ajouter_intention(base,intention, intention_demandee)

def traiter_action(intention, phrase):
    """Effectue une action en fonction de l'intention."""
    if intention == "recherche":
        mots_cles = phrase.replace("recherche", "").strip()
        url = f"https://www.google.com/search?q={mots_cles}"
        webbrowser.open(url)
        return f"Recherche Google lancée pour : {mots_cles}"
    elif intention == "youtube":
        mots_cles = phrase.replace("youtube", "").strip()
        url = f"https://www.youtube.com/results?search_query={mots_cles}"
        webbrowser.open(url)
        return f"Recherche YouTube lancée pour : {mots_cles}"
    else:
        return ajouter_intention(base, phrase, intention)
    

def charger_base_de_donnees(nom_fichier="base_de_donnees.json"):
    """Charge une base JSON existante ou en crée une vide."""
    try:
        with open(nom_fichier, "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        base = {}
    return base

def sauvegarder_base_de_donnees(base, nom_fichier="base_de_donnees.json"):
    """Sauvegarde une base JSON."""
    with open(nom_fichier, "w") as f:
        json.dump(base, f, indent=4)

def ajouter_intention(base, phrase, intention, fichier="base_de_donnees.json"):
    """Ajoute une nouvelle phrase pour une intention donnée dans la base de données."""
    # Vérifier si l'intention existe déjà dans la base

    if intention in base:
        # Ajouter la phrase dans la liste des phrases si elle n'y est pas déjà
        if phrase not in base[intention]["phrases"]:
            base[intention]["phrases"].append(phrase)
            print(f"Phrase ajoutée à l'intention '{intention}' : {phrase}")
            return generer_reponse(intention)
        else:
            print(f"La phrase '{phrase}' est déjà présente dans l'intention '{intention}'.")
            return generer_reponse(intention)
    else:
        # Créer une nouvelle intention avec cette phrase
        base[intention] = {
            "phrases": [phrase],
            "mots_cles": []
        }
        print(f"Nouvelle intention créée : '{intention}' avec la phrase '{phrase}'.")
        return "Notre équipe va mettre en place cette nouvelle intention"
    sauvegarder_base(base, fichier)
        

def sauvegarder_base(base, fichier="base_de_donnees.json"):
    """Sauvegarde la base de données dans un fichier JSON."""
    with open(fichier, "w", encoding="utf-8") as f:
        json.dump(base, f, indent=4, ensure_ascii=False)

