modify this unity c# script so it's a real ai model. using UnityEngine;
using TMPro;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

/// <summary>
/// AdvancedAIScript enhances conversational AI with multi-word intent recognition,
/// improved sentiment analysis, and coherent dynamic sentence generation.
/// </summary>
public class AdvancedAIScript : MonoBehaviour
{
    [Header("UI Elements")]
    public TMP_InputField userInputField;
    public TMP_Text aiResponseText;
    public Button submitButton;
    public ScrollRect scrollRect; // To auto-scroll to the latest response

    [Header("AI Settings")]
    public int MemoryLimit = 20; // Increased to store more exchanges
    public int TopicMemoryLimit = 5; // Memory for current topic

    private Queue<string> memory = new Queue<string>(); // General memory for context
    private Queue<string> topicMemory = new Queue<string>(); // Memory for topic tracking
    private List<WordData> vocabulary = new List<WordData>();
    private List<Intent> intents = new List<Intent>();
    private List<Entity> entities = new List<Entity>();

    // Word Categories
    private List<string> subjects = new List<string> { "I", "We", "They", "You" };
    private List<string> verbs = new List<string>();
    private List<string> adjectives = new List<string>();
    private List<string> adverbs = new List<string>();
    private List<string> objects = new List<string>();

    private string currentTopic = "";

    private void Start()
    {
        InitializeVocabulary();
        InitializeIntents();
        InitializeEntities();
        CategorizeWords();
        submitButton.onClick.AddListener(OnSubmit);
    }

    private void OnSubmit()
    {
        string userInput = userInputField.text.Trim();
        if (string.IsNullOrEmpty(userInput)) return;

        AddToMemory($"User: {userInput}");
        userInputField.text = string.Empty;

        // Process user input
        ProcessUserInput(userInput);
    }

    private void AddToMemory(string text)
    {
        if (memory.Count >= MemoryLimit)
            memory.Dequeue(); // Remove oldest memory

        memory.Enqueue(text);
    }

    private void AddToTopicMemory(string topic)
    {
        if (topicMemory.Count >= TopicMemoryLimit)
            topicMemory.Dequeue(); // Remove oldest topic

        topicMemory.Enqueue(topic);
    }

    private void ProcessUserInput(string input)
    {
        // Analyze sentiment
        SentimentScore sentiment = AnalyzeSentiment(input); // Changed from float to SentimentScore

        // Detect intents
        List<Intent> detectedIntents = DetectIntents(input);

        // Detect entities
        List<Entity> detectedEntities = DetectEntities(input);

        // Update current topic based on entities
        if (detectedEntities.Count > 0)
        {
            currentTopic = detectedEntities.First().Type;
            AddToTopicMemory(currentTopic);
        }
        else if (topicMemory.Count > 0)
        {
            currentTopic = topicMemory.Last();
        }
        else
        {
            currentTopic = "";
        }

        // Generate response based on intents, sentiment, and topic
        string response = GenerateResponse(detectedIntents, sentiment, currentTopic); // Pass SentimentScore

        // Add AI response to memory
        AddToMemory($"AI: {response}");

        // Display the response
        aiResponseText.text += $"AI: {response}\n";
        ScrollToBottom();
    }

    private void InitializeVocabulary()
    {
        // Initialize vocabulary with words, meanings, synonyms, definitions, and relationships
        vocabulary = new List<WordData>
        {
            // Verbs
            new WordData("enjoy", new WordMeaning(
                type: "action",
                emotion: "positive",
                synonyms: new string[] { "love", "like", "appreciate" },
                category: WordCategory.Verb,
                definition: "To take delight or pleasure in an activity or occasion.",
                antonyms: new string[] { "hate", "dislike" },
                relatedWords: new string[] { "fun", "pleasure" }
            )),
            new WordData("feel", new WordMeaning(
                type: "action",
                emotion: "neutral",
                synonyms: new string[] { "sense", "perceive", "experience" },
                category: WordCategory.Verb,
                definition: "To perceive by touch or be aware of through the senses.",
                antonyms: new string[] { },
                relatedWords: new string[] { "emotion", "sensation" }
            )),
            new WordData("think", new WordMeaning(
                type: "action",
                emotion: "neutral",
                synonyms: new string[] { "believe", "consider", "ponder" },
                category: WordCategory.Verb,
                definition: "To have a particular opinion, belief, or idea about someone or something.",
                antonyms: new string[] { },
                relatedWords: new string[] { "idea", "thought" }
            )),
            new WordData("want", new WordMeaning(
                type: "action",
                emotion: "neutral",
                synonyms: new string[] { "desire", "wish", "need" },
                category: WordCategory.Verb,
                definition: "To have a desire to possess or do something.",
                antonyms: new string[] { },
                relatedWords: new string[] { "desire", "need" }
            )),
            new WordData("do", new WordMeaning(
                type: "action",
                emotion: "neutral",
                synonyms: new string[] { "perform", "execute", "carry out" },
                category: WordCategory.Verb,
                definition: "To perform an action or activity.",
                antonyms: new string[] { },
                relatedWords: new string[] { "action", "activity" }
            )),
            new WordData("prefer", new WordMeaning(
                type: "action",
                emotion: "positive",
                synonyms: new string[] { "favor", "choose", "select" },
                category: WordCategory.Verb,
                definition: "To like (one thing or person) better than another or others.",
                antonyms: new string[] { "disfavor", "reject" },
                relatedWords: new string[] { "choice", "selection" }
            )),
            new WordData("hate", new WordMeaning(
                type: "action",
                emotion: "negative",
                synonyms: new string[] { "dislike", "detest", "loathe" },
                category: WordCategory.Verb,
                definition: "To feel intense or passionate dislike for something or someone.",
                antonyms: new string[] { "love", "enjoy" },
                relatedWords: new string[] { "discontent", "aversion" }
            )),
            new WordData("help", new WordMeaning(
                type: "action",
                emotion: "positive",
                synonyms: new string[] { "assist", "support", "aid" },
                category: WordCategory.Verb,
                definition: "To make it easier or possible for someone to do something by offering one's services or resources.",
                antonyms: new string[] { },
                relatedWords: new string[] { "assistance", "support" }
            )),
            new WordData("discuss", new WordMeaning(
                type: "action",
                emotion: "neutral",
                synonyms: new string[] { "talk about", "converse", "debate" },
                category: WordCategory.Verb,
                definition: "To talk about (something) with another person or group of people.",
                antonyms: new string[] { },
                relatedWords: new string[] { "conversation", "debate" }
            )),

            // Nouns
            new WordData("weather", new WordMeaning(
                type: "weather",
                emotion: "neutral",
                synonyms: new string[] { "climate", "temperature", "forecast" },
                category: WordCategory.Noun,
                definition: "The state of the atmosphere at a place and time regarding heat, cloudiness, dryness, sunshine, wind, rain, etc.",
                antonyms: new string[] { },
                relatedWords: new string[] { "forecast", "temperature" }
            )),
            new WordData("computer", new WordMeaning(
                type: "technology",
                emotion: "neutral",
                synonyms: new string[] { "PC", "laptop", "machine" },
                category: WordCategory.Noun,
                definition: "An electronic device for storing and processing data, typically in binary form, according to instructions given to it in a variable program.",
                antonyms: new string[] { },
                relatedWords: new string[] { "technology", "device" }
            )),
            new WordData("music", new WordMeaning(
                type: "hobby",
                emotion: "positive",
                synonyms: new string[] { "songs", "melodies", "tunes" },
                category: WordCategory.Noun,
                definition: "Vocal or instrumental sounds (or both) combined in such a way as to produce beauty of form, harmony, and expression of emotion.",
                antonyms: new string[] { },
                relatedWords: new string[] { "art", "expression" }
            )),
            new WordData("game", new WordMeaning(
                type: "hobby",
                emotion: "positive",
                synonyms: new string[] { "gaming", "play", "match" },
                category: WordCategory.Noun,
                definition: "An activity one engages in for amusement or fun.",
                antonyms: new string[] { },
                relatedWords: new string[] { "fun", "amusement" }
            )),
            new WordData("food", new WordMeaning(
                type: "hobby",
                emotion: "positive",
                synonyms: new string[] { "meal", "cuisine", "dish" },
                category: WordCategory.Noun,
                definition: "Any nutritious substance that people or animals eat or drink, or that plants absorb, in order to maintain life and growth.",
                antonyms: new string[] { },
                relatedWords: new string[] { "nutrition", "cuisine" }
            )),
            new WordData("idea", new WordMeaning(
                type: "concept",
                emotion: "neutral",
                synonyms: new string[] { "thought", "notion", "plan" },
                category: WordCategory.Noun,
                definition: "A thought or suggestion as to a possible course of action.",
                antonyms: new string[] { },
                relatedWords: new string[] { "concept", "thought" }
            )),
            new WordData("friend", new WordMeaning(
                type: "relationship",
                emotion: "neutral",
                synonyms: new string[] { "buddy", "companion", "pal" },
                category: WordCategory.Noun,
                definition: "A person whom one knows and with whom one has a bond of mutual affection.",
                antonyms: new string[] { },
                relatedWords: new string[] { "companion", "association" }
            )),
            new WordData("time", new WordMeaning(
                type: "concept",
                emotion: "neutral",
                synonyms: new string[] { "moment", "hour", "second" },
                category: WordCategory.Noun,
                definition: "The indefinite continued progress of existence and events.",
                antonyms: new string[] { },
                relatedWords: new string[] { "moment", "duration" }
            )),
            new WordData("movie", new WordMeaning(
                type: "hobby",
                emotion: "positive",
                synonyms: new string[] { "film", "cinema", "flick" },
                category: WordCategory.Noun,
                definition: "A story or event recorded by a camera as a set of moving images and shown in a theater or on television.",
                antonyms: new string[] { },
                relatedWords: new string[] { "cinema", "entertainment" }
            )),
            new WordData("book", new WordMeaning(
                type: "hobby",
                emotion: "neutral",
                synonyms: new string[] { "novel", "literature", "volume" },
                category: WordCategory.Noun,
                definition: "A written or printed work consisting of pages glued or sewn together along one side and bound in covers.",
                antonyms: new string[] { },
                relatedWords: new string[] { "literature", "reading" }
            )),
            new WordData("sport", new WordMeaning(
                type: "hobby",
                emotion: "positive",
                synonyms: new string[] { "game", "athletics", "competition" },
                category: WordCategory.Noun,
                definition: "An activity involving physical exertion and skill in which an individual or team competes against another or others for entertainment.",
                antonyms: new string[] { },
                relatedWords: new string[] { "competition", "exercise" }
            )),

            // Adjectives
            new WordData("happy", new WordMeaning(
                type: "emotion",
                emotion: "positive",
                synonyms: new string[] { "joyful", "content", "pleased" },
                category: WordCategory.Adjective,
                definition: "Feeling or showing pleasure or contentment.",
                antonyms: new string[] { "sad", "unhappy" },
                relatedWords: new string[] { "joy", "contentment" }
            )),
            new WordData("sad", new WordMeaning(
                type: "emotion",
                emotion: "negative",
                synonyms: new string[] { "unhappy", "downcast", "gloomy" },
                category: WordCategory.Adjective,
                definition: "Feeling or showing sorrow; unhappy.",
                antonyms: new string[] { "happy", "content" },
                relatedWords: new string[] { "sorrow", "unhappiness" }
            )),
            new WordData("exciting", new WordMeaning(
                type: "emotion",
                emotion: "positive",
                synonyms: new string[] { "thrilling", "stimulating", "invigorating" },
                category: WordCategory.Adjective,
                definition: "Causing great enthusiasm and eagerness.",
                antonyms: new string[] { "boring", "dull" },
                relatedWords: new string[] { "enthusiasm", "excitement" }
            )),
            new WordData("boring", new WordMeaning(
                type: "emotion",
                emotion: "negative",
                synonyms: new string[] { "monotonous", "tedious", "uninteresting" },
                category: WordCategory.Adjective,
                definition: "Not interesting; tedious.",
                antonyms: new string[] { "exciting", "interesting" },
                relatedWords: new string[] { "tedium", "monotony" }
            )),
            new WordData("fun", new WordMeaning(
                type: "emotion",
                emotion: "positive",
                synonyms: new string[] { "enjoyable", "exciting", "pleasant" },
                category: WordCategory.Adjective,
                definition: "Enjoyable and amusing.",
                antonyms: new string[] { },
                relatedWords: new string[] { "amusement", "entertainment" }
            )),
            new WordData("tired", new WordMeaning(
                type: "emotion",
                emotion: "negative",
                synonyms: new string[] { "exhausted", "weary", "fatigued" },
                category: WordCategory.Adjective,
                definition: "In need of sleep or rest; weary.",
                antonyms: new string[] { },
                relatedWords: new string[] { "fatigue", "weariness" }
            )),
            new WordData("interesting", new WordMeaning(
                type: "emotion",
                emotion: "neutral",
                synonyms: new string[] { "fascinating", "captivating", "engaging" },
                category: WordCategory.Adjective,
                definition: "Arousing curiosity or interest; holding or catching the attention.",
                antonyms: new string[] { "boring", "dull" },
                relatedWords: new string[] { "curiosity", "attention" }
            )),
            new WordData("cold", new WordMeaning(
                type: "weather",
                emotion: "neutral",
                synonyms: new string[] { "chilly", "freezing", "frigid" },
                category: WordCategory.Adjective,
                definition: "Of or at a low or relatively low temperature.",
                antonyms: new string[] { "hot", "warm" },
                relatedWords: new string[] { "temperature", "weather" }
            )),
            new WordData("hot", new WordMeaning(
                type: "weather",
                emotion: "neutral",
                synonyms: new string[] { "warm", "scorching", "boiling" },
                category: WordCategory.Adjective,
                definition: "Having a high degree of heat or a high temperature.",
                antonyms: new string[] { "cold", "cool" },
                relatedWords: new string[] { "temperature", "weather" }
            )),
            new WordData("busy", new WordMeaning(
                type: "state",
                emotion: "neutral",
                synonyms: new string[] { "occupied", "engaged", "tasked" },
                category: WordCategory.Adjective,
                definition: "Having a great deal to do; constantly active.",
                antonyms: new string[] { "idle", "free" },
                relatedWords: new string[] { "activity", "task" }
            )),

            // Adverbs
            new WordData("quickly", new WordMeaning(
                type: "manner",
                emotion: "neutral",
                synonyms: new string[] { "swiftly", "rapidly", "speedily" },
                category: WordCategory.Adverb,
                definition: "At a fast speed; rapidly.",
                antonyms: new string[] { "slowly" },
                relatedWords: new string[] { "speed", "pace" }
            )),
            new WordData("slowly", new WordMeaning(
                type: "manner",
                emotion: "neutral",
                synonyms: new string[] { "leisurely", "gradually", "deliberately" },
                category: WordCategory.Adverb,
                definition: "At a low speed; not quickly.",
                antonyms: new string[] { "quickly", "fast" },
                relatedWords: new string[] { "pace", "speed" }
            )),
            new WordData("happily", new WordMeaning(
                type: "manner",
                emotion: "positive",
                synonyms: new string[] { "joyfully", "cheerfully", "merrily" },
                category: WordCategory.Adverb,
                definition: "In a happy or joyous manner.",
                antonyms: new string[] { "sadly" },
                relatedWords: new string[] { "joy", "happiness" }
            )),
            new WordData("sadly", new WordMeaning(
                type: "manner",
                emotion: "negative",
                synonyms: new string[] { "unhappily", "dejectedly", "gloomily" },
                category: WordCategory.Adverb,
                definition: "In a sad or unhappy manner.",
                antonyms: new string[] { "happily" },
                relatedWords: new string[] { "sorrow", "unhappiness" }
            )),
            new WordData("carefully", new WordMeaning(
                type: "manner",
                emotion: "neutral",
                synonyms: new string[] { "cautiously", "meticulously", "attentively" },
                category: WordCategory.Adverb,
                definition: "In a way that avoids potential problems or dangers; cautiously.",
                antonyms: new string[] { },
                relatedWords: new string[] { "caution", "attention" }
            )),
            new WordData("eagerly", new WordMeaning(
                type: "manner",
                emotion: "positive",
                synonyms: new string[] { "enthusiastically", "keenly", "zealously" },
                category: WordCategory.Adverb,
                definition: "With great eagerness or enthusiasm.",
                antonyms: new string[] { },
                relatedWords: new string[] { "enthusiasm", "zeal" }
            )),
            new WordData("quietly", new WordMeaning(
                type: "manner",
                emotion: "neutral",
                synonyms: new string[] { "silently", "softly", "calmly" },
                category: WordCategory.Adverb,
                definition: "In a quiet manner; making little or no noise.",
                antonyms: new string[] { "loudly" },
                relatedWords: new string[] { "silence", "calm" }
            )),
            new WordData("loudly", new WordMeaning(
                type: "manner",
                emotion: "neutral",
                synonyms: new string[] { "noisily", "raucously", "boisterously" },
                category: WordCategory.Adverb,
                definition: "In a loud manner; making much noise.",
                antonyms: new string[] { "quietly" },
                relatedWords: new string[] { "noise", "volume" }
            )),

            // Add more words to build a rich vocabulary with definitions and relationships
        };
    }

    private void CategorizeWords()
    {
        foreach (var wordData in vocabulary)
        {
            switch (wordData.Meaning.Category)
            {
                case WordCategory.Noun:
                    objects.Add(wordData.Word);
                    objects.AddRange(wordData.Meaning.Synonyms);
                    break;
                case WordCategory.Verb:
                    verbs.Add(wordData.Word);
                    verbs.AddRange(wordData.Meaning.Synonyms);
                    break;
                case WordCategory.Adjective:
                    adjectives.Add(wordData.Word);
                    adjectives.AddRange(wordData.Meaning.Synonyms);
                    break;
                case WordCategory.Adverb:
                    adverbs.Add(wordData.Word);
                    adverbs.AddRange(wordData.Meaning.Synonyms);
                    break;
                default:
                    break;
            }
        }

        // Remove duplicates
        verbs = verbs.Distinct().ToList();
        adjectives = adjectives.Distinct().ToList();
        adverbs = adverbs.Distinct().ToList();
        objects = objects.Distinct().ToList();
    }

    private void InitializeIntents()
    {
        // Define various intents with associated keywords and optional weights
        intents = new List<Intent>
        {
            new Intent("Greeting", new string[] { "hello", "hi", "hey", "greetings" }),
            new Intent("Farewell", new string[] { "bye", "goodbye", "see you", "farewell" }),
            new Intent("EmotionPositive", new string[] { "happy", "joyful", "excited", "pleased", "content", "fun", "interesting", "love", "enjoy" }),
            new Intent("EmotionNegative", new string[] { "sad", "unhappy", "down", "depressed", "tired", "exhausted", "boring", "hate", "dislike" }),
            new Intent("AskWeather", new string[] { "weather", "climate", "forecast", "temperature" }),
            new Intent("AskAboutTopic", new string[] { "learn", "study", "understand", "grasp", "idea" }),
            new Intent("TalkAboutHobbies", new string[] { "game", "music", "food", "sport", "hobby", "create", "play", "movie", "book" }),
            new Intent("Help", new string[] { "help", "assist", "support", "aid" }),
            // New Intent for Inquiry About AI Well-Being
            new Intent("CheckWellBeing", new string[] { "how are you", "how do you do", "how are you doing", "what's up", "how is it going" }),
            // Add more intents as needed
        };
    }

    private void InitializeEntities()
    {
        // Define entities with their types and related topics
        entities = new List<Entity>
        {
            new Entity("weather", "weather"),
            new Entity("climate", "weather"),
            new Entity("temperature", "weather"),
            new Entity("forecast", "weather"),

            new Entity("computer", "technology"),
            new Entity("PC", "technology"),
            new Entity("laptop", "technology"),
            new Entity("machine", "technology"),

            new Entity("music", "hobby"),
            new Entity("game", "hobby"),
            new Entity("food", "hobby"),
            new Entity("sport", "hobby"),
            new Entity("movie", "hobby"),
            new Entity("book", "hobby"),

            new Entity("idea", "concept"),
            new Entity("thought", "concept"),
            new Entity("plan", "concept"),
            new Entity("relationship", "relationship"),
            new Entity("friend", "relationship"),
            // Add more entities as needed
        };
    }

    private SentimentScore AnalyzeSentiment(string input)
    {
        // SentimentScore includes both type and intensity
        float positiveScore = 0;
        float negativeScore = 0;

        foreach (var word in vocabulary)
        {
            if (word.Meaning.Type == "emotion")
            {
                if (word.Meaning.Emotion == "positive" && ContainsWord(input, word.Word))
                {
                    positiveScore += 1.0f;
                }
                else if (word.Meaning.Emotion == "negative" && ContainsWord(input, word.Word))
                {
                    negativeScore += 1.0f;
                }

                // Check synonyms
                foreach (var synonym in word.Meaning.Synonyms)
                {
                    if (word.Meaning.Emotion == "positive" && ContainsWord(input, synonym))
                    {
                        positiveScore += 0.8f; // Synonyms have slightly less weight
                    }
                    else if (word.Meaning.Emotion == "negative" && ContainsWord(input, synonym))
                    {
                        negativeScore += 0.8f;
                    }
                }
            }
        }

        // Normalize scores
        float total = positiveScore + negativeScore;
        if (total == 0)
            return new SentimentScore(Sentiment.Neutral, 0f);

        float normalizedPositive = positiveScore / total;
        float normalizedNegative = negativeScore / total;

        if (normalizedPositive > 0.6f)
            return new SentimentScore(Sentiment.Positive, normalizedPositive);
        else if (normalizedNegative > 0.6f)
            return new SentimentScore(Sentiment.Negative, normalizedNegative);
        else
            return new SentimentScore(Sentiment.Neutral, 0f);
    }

    private List<Intent> DetectIntents(string input)
    {
        List<Intent> detectedIntents = new List<Intent>();

        foreach (var intent in intents)
        {
            foreach (var keyword in intent.Keywords)
            {
                // For phrase-based intents, adjust the matching
                if (intent.Name == "CheckWellBeing")
                {
                    // Use case-insensitive comparison for phrases
                    if (Regex.IsMatch(input, Regex.Escape(keyword), RegexOptions.IgnoreCase))
                    {
                        detectedIntents.Add(intent);
                        break; // Avoid adding the same intent multiple times
                    }
                }
                else
                {
                    // Use whole word matching for single-word intents
                    if (ContainsWord(input, keyword))
                    {
                        detectedIntents.Add(intent);
                        break; // Avoid adding the same intent multiple times
                    }
                }
            }
        }

        return detectedIntents;
    }

    private List<Entity> DetectEntities(string input)
    {
        List<Entity> detectedEntities = new List<Entity>();

        foreach (var entity in entities)
        {
            if (ContainsWord(input, entity.Word))
            {
                detectedEntities.Add(entity);
            }
        }

        return detectedEntities;
    }

    private string GenerateResponse(List<Intent> detectedIntents, SentimentScore sentimentScore, string topic)
    {
        if (detectedIntents.Count == 0 && string.IsNullOrEmpty(topic))
        {
            // If no intent and no topic, generate a generic response
            return ConstructGenericSentence(Sentiment.Neutral);
        }

        // Prioritize intents
        Intent primaryIntent = detectedIntents.FirstOrDefault();

        if (primaryIntent != null)
        {
            switch (primaryIntent.Name)
            {
                case "Greeting":
                    return SelectGreeting();
                case "Farewell":
                    return SelectFarewell();
                case "EmotionPositive":
                case "EmotionNegative":
                    return ConstructEmotionSentence(primaryIntent, sentimentScore);
                case "AskWeather":
                    return ConstructWeatherSentence();
                case "AskAboutTopic":
                    return ConstructLearnSentence();
                case "TalkAboutHobbies":
                    return ConstructHobbySentence();
                case "Help":
                    return ConstructHelpSentence();
                case "CheckWellBeing":
                    return ConstructWellBeingSentence(sentimentScore);
                default:
                    return ConstructGenericSentence(Sentiment.Neutral);
            }
        }
        else if (!string.IsNullOrEmpty(topic))
        {
            // If there's an ongoing topic, continue discussing it
            return ConstructTopicSentence(topic, sentimentScore);
        }
        else
        {
            // Fallback generic sentence
            return ConstructGenericSentence(Sentiment.Neutral);
        }
    }

    private string SelectGreeting()
    {
        string[] greetings = { "Hello!", "Hi there!", "Hey!", "Greetings!" };
        return greetings[Random.Range(0, greetings.Length)];
    }

    private string SelectFarewell()
    {
        string[] farewells = { "Goodbye!", "Bye!", "See you later!", "Farewell!" };
        return farewells[Random.Range(0, farewells.Length)];
    }

    private string ConstructEmotionSentence(Intent intent, SentimentScore sentimentScore)
    {
        // Depending on emotion, adjust adjectives and adverbs
        string adjective = SelectAdjective(null, sentimentScore.Sentiment);
        string verb = "feel";
        string adverb = SelectAdverb(null, sentimentScore.Sentiment);
        string objectWord = SelectObject(null, sentimentScore.Sentiment);

        // Ensure components are relevant and meaningful
        List<string> sentenceComponents = new List<string> { "I", verb };

        if (!string.IsNullOrEmpty(adjective))
            sentenceComponents.Add(adjective);

        if (!string.IsNullOrEmpty(adverb))
            sentenceComponents.Add(adverb);

        if (!string.IsNullOrEmpty(objectWord))
            sentenceComponents.Add(objectWord);

        string sentence = string.Join(" ", sentenceComponents) + ".";

        return Capitalize(sentence);
    }

    private string ConstructWellBeingSentence(SentimentScore sentimentScore)
    {
        // Provide a coherent response based on sentiment
        switch (sentimentScore.Sentiment)
        {
            case Sentiment.Positive:
                return "I'm doing well, thank you!";
            case Sentiment.Negative:
                return "I'm sorry to hear you're feeling that way.";
            case Sentiment.Neutral:
            default:
                return "I'm here to help you!";
        }
    }

    private string ConstructWeatherSentence()
    {
        // Generate a weather-related sentence
        string[] weatherDescriptions = { "sunny", "cloudy", "rainy", "stormy", "windy", "mild", "freezing", "hot" };
        string adjective = weatherDescriptions[Random.Range(0, weatherDescriptions.Length)];
        string verb = "is";
        string noun = "weather";

        // Example: "The weather is sunny today."
        string sentence = $"The {noun} {verb} {adjective} today.";
        return Capitalize(sentence);
    }

    private string ConstructLearnSentence()
    {
        // Generate a learning-related sentence
        string[] actions = { "learn more about", "explore", "understand", "discover" };
        string action = actions[Random.Range(0, actions.Length)];
        string topic = SelectTopic();

        // Example: "I'd like to learn more about computers."
        string sentence = $"I'd like to {action} {topic}.";
        return Capitalize(sentence);
    }

    private string ConstructHobbySentence()
    {
        // Generate a hobby-related sentence
        string[] actions = { "enjoy", "love", "like", "prefer" };
        string action = actions[Random.Range(0, actions.Length)];
        string hobby = SelectObject("hobby");

        // Example: "I enjoy playing games."
        string sentence = $"I {action} {hobby}.";
        return Capitalize(sentence);
    }

    private string ConstructHelpSentence()
    {
        // Generate a help-related sentence
        string[] offers = { "How can I assist you?", "What do you need help with?", "I'm here to help. What can I do for you?", "Let me know how I can support you." };
        return Capitalize(offers[Random.Range(0, offers.Length)]);
    }

    private string ConstructTopicSentence(string topic, SentimentScore sentimentScore)
    {
        // Generate a sentence based on the current topic
        switch (topic.ToLower())
        {
            case "weather":
                return ConstructWeatherSentence();
            case "technology":
                return $"I think technology is fascinating.";
            case "hobby":
                return ConstructHobbySentence();
            case "concept":
                return $"Let's discuss more about that {topic}.";
            case "relationship":
                return $"Maintaining relationships is important.";
            default:
                return ConstructGenericSentence(Sentiment.Neutral);
        }
    }

    private string ConstructGenericSentence(Sentiment sentiment)
    {
        // Generate a generic sentence based on sentiment
        string verb = SelectVerb(null);
        string adjective = SelectAdjective(null, sentiment);
        string adverb = SelectAdverb(null, sentiment);
        string objectWord = SelectObject(null, sentiment);

        // Example structure: "I [verb] [adjective] [adverb] [object]."
        List<string> sentenceComponents = new List<string> { "I", verb };

        if (!string.IsNullOrEmpty(adjective))
            sentenceComponents.Add(adjective);

        if (!string.IsNullOrEmpty(adverb))
            sentenceComponents.Add(adverb);

        if (!string.IsNullOrEmpty(objectWord))
            sentenceComponents.Add(objectWord);

        string sentence = string.Join(" ", sentenceComponents) + ".";
        return Capitalize(sentence);
    }

    private string SelectVerb(Intent intent)
    {
        // Select a verb relevant to the intent
        if (verbs.Count == 0) return "do";

        if (intent == null)
            return verbs[Random.Range(0, verbs.Count)];

        // For specific intents, prioritize certain verbs
        return verbs[Random.Range(0, verbs.Count)];
    }

    private string SelectObject(string category = null, Sentiment sentiment = Sentiment.Neutral)
    {
        // Select an object relevant to the category and sentiment
        List<string> relevantObjects = new List<string>();

        if (category != null)
        {
            relevantObjects = objects.Where(obj => {
                var wd = vocabulary.FirstOrDefault(w => w.Word == obj || w.Meaning.Synonyms.Contains(obj));
                return wd != null && wd.Meaning.Type == category;
            }).ToList();
        }
        else
        {
            relevantObjects = new List<string>(objects);
        }

        if (relevantObjects.Count == 0) return "";

        return relevantObjects[Random.Range(0, relevantObjects.Count)];
    }

    private string SelectAdjective(Intent intent, Sentiment sentiment)
    {
        // Select an adjective based on intent and sentiment
        List<string> relevantAdjectives = new List<string>();

        if (intent != null)
        {
            if (intent.Name.Contains("Emotion"))
            {
                relevantAdjectives = adjectives.Where(adj => 
                    vocabulary.Any(w => (w.Word == adj || w.Meaning.Synonyms.Contains(adj)) 
                    && w.Meaning.Type == "emotion")).ToList();
            }
            else
            {
                // For other intents, use all adjectives or define specific criteria
                relevantAdjectives = adjectives;
            }
        }
        else
        {
            // General adjectives
            relevantAdjectives = new List<string>(adjectives);
        }

        // Filter adjectives based on sentiment
        if (sentiment == Sentiment.Positive)
        {
            relevantAdjectives = relevantAdjectives.Where(adj => 
                vocabulary.Any(w => (w.Word == adj || w.Meaning.Synonyms.Contains(adj)) 
                && w.Meaning.Emotion == "positive")).ToList();
        }
        else if (sentiment == Sentiment.Negative)
        {
            relevantAdjectives = relevantAdjectives.Where(adj => 
                vocabulary.Any(w => (w.Word == adj || w.Meaning.Synonyms.Contains(adj)) 
                && w.Meaning.Emotion == "negative")).ToList();
        }

        if (relevantAdjectives.Count == 0) return "";

        return relevantAdjectives[Random.Range(0, relevantAdjectives.Count)];
    }

    private string SelectAdverb(string category = null, Sentiment sentiment = Sentiment.Neutral)
    {
        // Select an adverb based on sentiment
        List<string> relevantAdverbs = new List<string>();

        relevantAdverbs = new List<string>(adverbs);

        if (sentiment == Sentiment.Positive)
        {
            relevantAdverbs = relevantAdverbs.Where(adj => 
                vocabulary.Any(w => (w.Word == adj || w.Meaning.Synonyms.Contains(adj)) 
                && w.Meaning.Emotion == "positive")).ToList();
        }
        else if (sentiment == Sentiment.Negative)
        {
            relevantAdverbs = relevantAdverbs.Where(adj => 
                vocabulary.Any(w => (w.Word == adj || w.Meaning.Synonyms.Contains(adj)) 
                && w.Meaning.Emotion == "negative")).ToList();
        }

        if (relevantAdverbs.Count == 0) return "";

        return relevantAdverbs[Random.Range(0, relevantAdverbs.Count)];
    }

    private string SelectTopic()
    {
        // Select a random topic from predefined entities
        List<string> topics = entities.Select(e => e.Type).Distinct().ToList();
        if (topics.Count == 0) return "something";
        return topics[Random.Range(0, topics.Count)];
    }

    private bool ContainsWord(string input, string word)
    {
        // Use regex to match whole words only, case-insensitive
        return Regex.IsMatch(input, $@"\b{Regex.Escape(word)}\b", RegexOptions.IgnoreCase);
    }

    private void ScrollToBottom()
    {
        Canvas.ForceUpdateCanvases();
        scrollRect.verticalNormalizedPosition = 0f;
    }

    // *** Added Capitalize Method ***
    private string Capitalize(string input)
    {
        if (string.IsNullOrEmpty(input))
            return input;

        return char.ToUpper(input[0]) + input.Substring(1);
    }
}

// Supporting Classes and Enums

[System.Serializable]
public class WordData
{
    public string Word { get; private set; }
    public WordMeaning Meaning { get; private set; }

    public WordData(string word, WordMeaning meaning)
    {
        Word = word;
        Meaning = meaning;
    }
}

[System.Serializable]
public class WordMeaning
{
    public string Type { get; private set; } // e.g., emotion, action, weather, hobby, concept, relationship
    public string Emotion { get; private set; } // e.g., positive, negative, neutral
    public string[] Synonyms { get; private set; }
    public WordCategory Category { get; private set; }
    public string Definition { get; private set; }
    public string[] Antonyms { get; private set; }
    public string[] RelatedWords { get; private set; }

    public WordMeaning(string type, string emotion, string[] synonyms, WordCategory category, string definition, string[] antonyms, string[] relatedWords)
    {
        Type = type;
        Emotion = emotion;
        Synonyms = synonyms;
        Category = category;
        Definition = definition;
        Antonyms = antonyms;
        RelatedWords = relatedWords;
    }
}

[System.Serializable]
public class Intent
{
    public string Name { get; private set; }
    public string[] Keywords { get; private set; }

    public Intent(string name, string[] keywords)
    {
        Name = name;
        Keywords = keywords;
    }
}

[System.Serializable]
public class Entity
{
    public string Word { get; private set; }
    public string Type { get; private set; }

    public Entity(string word, string type)
    {
        Word = word;
        Type = type;
    }
}

public enum Sentiment
{
    Positive,
    Negative,
    Neutral
}

public enum WordCategory
{
    Noun,
    Verb,
    Adjective,
    Adverb
}

public class SentimentScore
{
    public Sentiment Sentiment { get; private set; }
    public float Score { get; private set; }

    public SentimentScore(Sentiment sentiment, float score)
    {
        Sentiment = sentiment;
        Score = score;
    }
}