/**
 * SentenceGenerator.js
 * Helper for generating contextual educational sentences from vocabulary words
 * Handles proper grammar, articles, verb conjugation, and context variety
 */

export class SentenceGenerator {
    constructor() {
        // Vowel sounds for article detection
        this._vowelSounds = ['a', 'e', 'i', 'o', 'u'];

        // Special cases for articles (words starting with 'u' that use 'a')
        this._aExceptions = ['university', 'uniform', 'unicorn', 'unique', 'unit', 'union'];

        // Common irregular verbs (present tense 3rd person)
        this._irregularVerbs = {
            'go': 'goes',
            'do': 'does',
            'have': 'has',
            'be': 'is',
            'say': 'says',
            'try': 'tries',
            'fly': 'flies',
            'cry': 'cries',
            'study': 'studies'
        };

        // Sentence templates by word type with proper grammar
        this._templates = {
            'noun': {
                beginner: [
                    (w) => `This is ${this._getArticle(w)} ${w}.`,
                    (w) => `I see ${this._getArticle(w)} ${w}.`,
                    (w) => `Look at the ${w}!`,
                    (w) => `I have ${this._getArticle(w)} ${w}.`,
                    (w) => `Where is the ${w}?`
                ],
                intermediate: [
                    (w) => `The ${w} is on the table.`,
                    (w) => `I need ${this._getArticle(w)} ${w} for this task.`,
                    (w) => `Can you find the ${w}?`,
                    (w) => `She bought ${this._getArticle(w)} ${w} yesterday.`,
                    (w) => `The ${w} looks beautiful today.`
                ],
                advanced: [
                    (w) => `The ${w} represents an important concept in our discussion.`,
                    (w) => `Without ${this._getArticle(w)} ${w}, this would be impossible.`,
                    (w) => `The ${w} has become increasingly popular recently.`,
                    (w) => `Many people underestimate the value of ${this._getArticle(w)} ${w}.`,
                    (w) => `The ${w} plays a crucial role in this process.`
                ]
            },
            'verb': {
                beginner: [
                    (w) => `I ${w} every day.`,
                    (w) => `Please ${w} this.`,
                    (w) => `Can you ${w}?`,
                    (w) => `Let's ${w} together.`,
                    (w) => `Don't ${w} too fast.`
                ],
                intermediate: [
                    (w) => `She ${this._conjugateThirdPerson(w)} every morning.`,
                    (w) => `They will ${w} tomorrow.`,
                    (w) => `We should ${w} more often.`,
                    (w) => `He ${this._conjugateThirdPerson(w)} very well.`,
                    (w) => `I want to ${w} better.`
                ],
                advanced: [
                    (w) => `The ability to ${w} effectively is essential.`,
                    (w) => `She has been ${this._getGerund(w)} for years.`,
                    (w) => `Learning to ${w} requires practice and patience.`,
                    (w) => `He ${this._conjugateThirdPerson(w)} with remarkable skill.`,
                    (w) => `They decided to ${w} despite the challenges.`
                ]
            },
            'adjective': {
                beginner: [
                    (w) => `It is ${w}.`,
                    (w) => `The house is ${w}.`,
                    (w) => `This looks ${w}.`,
                    (w) => `How ${w}!`,
                    (w) => `Very ${w} indeed.`
                ],
                intermediate: [
                    (w) => `The weather seems quite ${w} today.`,
                    (w) => `She appears ${w} and happy.`,
                    (w) => `This is more ${w} than before.`,
                    (w) => `The ${w} building stands tall.`,
                    (w) => `Everyone feels ${w} about it.`
                ],
                advanced: [
                    (w) => `The ${w} atmosphere created a perfect ambiance.`,
                    (w) => `His ${w} demeanor impressed everyone.`,
                    (w) => `The situation became increasingly ${w}.`,
                    (w) => `She maintained a ${w} attitude throughout.`,
                    (w) => `The ${w} nature of the problem requires attention.`
                ]
            },
            'adverb': {
                beginner: [
                    (w) => `Walk ${w}.`,
                    (w) => `Do it ${w}.`,
                    (w) => `Move ${w}.`,
                    (w) => `Talk ${w}.`,
                    (w) => `Run ${w}.`
                ],
                intermediate: [
                    (w) => `He speaks ${w} and clearly.`,
                    (w) => `She works ${w} every day.`,
                    (w) => `They arrived ${w} at the meeting.`,
                    (w) => `The car moves ${w} down the road.`,
                    (w) => `Please listen ${w} to the instructions.`
                ],
                advanced: [
                    (w) => `The team performed ${w} under pressure.`,
                    (w) => `She ${w} explained the complex concept.`,
                    (w) => `The project progressed ${w} despite setbacks.`,
                    (w) => `He ${w} adapted to the new environment.`,
                    (w) => `The strategy was ${w} implemented.`
                ]
            },
            'preposition': {
                beginner: [
                    (w) => `The book is ${w} the table.`,
                    (w) => `Go ${w} the door.`,
                    (w) => `Look ${w} the window.`,
                    (w) => `It's ${w} the box.`,
                    (w) => `Put it ${w} here.`
                ],
                intermediate: [
                    (w) => `The cat jumped ${w} the fence.`,
                    (w) => `We walked ${w} the park together.`,
                    (w) => `She placed it ${w} the shelf.`,
                    (w) => `They traveled ${w} the mountains.`,
                    (w) => `The bird flew ${w} the trees.`
                ],
                advanced: [
                    (w) => `The discussion centered ${w} the main topic.`,
                    (w) => `Success depends ${w} consistent effort.`,
                    (w) => `The solution lies ${w} these principles.`,
                    (w) => `Progress moved ${w} expectations.`,
                    (w) => `The argument stands ${w} scrutiny.`
                ]
            }
        };
    }

    /**
     * Get appropriate article (a/an) for a word
     * @param {string} word - The word to check
     * @returns {string} - "a" or "an"
     */
    _getArticle(word) {
        if (!word) return 'a';

        const firstLetter = word.charAt(0).toLowerCase();

        // Check exceptions (words starting with 'u' but pronounced with consonant sound)
        if (this._aExceptions.some(exception => word.toLowerCase().startsWith(exception))) {
            return 'a';
        }

        // Check if starts with vowel sound
        return this._vowelSounds.includes(firstLetter) ? 'an' : 'a';
    }

    /**
     * Conjugate verb to 3rd person singular present
     * @param {string} verb - Base form of verb
     * @returns {string} - Conjugated verb
     */
    _conjugateThirdPerson(verb) {
        if (!verb) return verb;

        // Check irregular verbs
        if (this._irregularVerbs[verb.toLowerCase()]) {
            return this._irregularVerbs[verb.toLowerCase()];
        }

        // Regular conjugation rules
        const lowerVerb = verb.toLowerCase();

        // Verbs ending in -y preceded by consonant: try -> tries
        if (lowerVerb.endsWith('y') && lowerVerb.length > 1) {
            const beforeY = lowerVerb.charAt(lowerVerb.length - 2);
            if (!'aeiou'.includes(beforeY)) {
                return verb.slice(0, -1) + 'ies';
            }
        }

        // Verbs ending in -s, -x, -z, -ch, -sh: add -es
        if (lowerVerb.endsWith('s') || lowerVerb.endsWith('x') ||
            lowerVerb.endsWith('z') || lowerVerb.endsWith('ch') ||
            lowerVerb.endsWith('sh')) {
            return verb + 'es';
        }

        // Verbs ending in -o: add -es
        if (lowerVerb.endsWith('o')) {
            return verb + 'es';
        }

        // Default: add -s
        return verb + 's';
    }

    /**
     * Convert verb to gerund form (present participle)
     * @param {string} verb - Base form of verb
     * @returns {string} - Gerund form
     */
    _getGerund(verb) {
        if (!verb) return verb;

        const lowerVerb = verb.toLowerCase();

        // Verbs ending in -e: remove -e and add -ing (make -> making)
        if (lowerVerb.endsWith('e') && lowerVerb !== 'be') {
            return verb.slice(0, -1) + 'ing';
        }

        // Verbs ending in -ie: change to -ying (lie -> lying)
        if (lowerVerb.endsWith('ie')) {
            return verb.slice(0, -2) + 'ying';
        }

        // Single syllable verbs ending in consonant-vowel-consonant: double last letter
        // (run -> running, stop -> stopping)
        if (lowerVerb.length >= 3) {
            const last = lowerVerb.slice(-1);
            const secondLast = lowerVerb.slice(-2, -1);
            const thirdLast = lowerVerb.slice(-3, -2);

            const isConsonant = (c) => !'aeiou'.includes(c);

            if (isConsonant(last) && !isConsonant(secondLast) && isConsonant(thirdLast)) {
                // But not for verbs ending in w, x, y
                if (!'wxy'.includes(last)) {
                    return verb + last + 'ing';
                }
            }
        }

        // Default: add -ing
        return verb + 'ing';
    }

    /**
     * Determine difficulty level from word frequency or context
     * @param {Object} data - Word data
     * @returns {string} - "beginner", "intermediate", or "advanced"
     */
    _getDifficultyLevel(data) {
        // You can enhance this with actual word frequency data or CEFR levels
        // For now, use simple heuristics

        if (data.level) {
            return data.level; // If explicitly provided
        }

        // Simple heuristic: word length
        const wordLength = (data.word || '').length;
        if (wordLength <= 5) return 'beginner';
        if (wordLength <= 8) return 'intermediate';
        return 'advanced';
    }

    /**
     * Generate a contextual sentence from a vocabulary word
     * @param {string} word - The vocabulary word
     * @param {Object} data - Word data including type and translation
     * @returns {Object} - Generated sentence with English and translation
     */
    generateSentence(word, data) {
        if (!word || !data) {
            console.warn('Invalid word or data for sentence generation');
            return {
                english: `This is ${word}.`,
                translation: `${data?.user_language || word}`
            };
        }

        const type = (data.type || 'noun').toLowerCase();
        const translation = data.user_language ? data.user_language.split('；')[0].trim() : word;
        const difficulty = this._getDifficultyLevel({...data, word});

        // Get templates for this type and difficulty
        const typeTemplates = this._templates[type] || this._templates['noun'];
        const difficultyTemplates = typeTemplates[difficulty] || typeTemplates['beginner'];

        // Select random template
        const randomTemplate = difficultyTemplates[Math.floor(Math.random() * difficultyTemplates.length)];

        // Generate sentence using template function
        const englishSentence = randomTemplate(word);

        // Create translation with highlighted word
        const highlightedWord = `**${word}**`;
        const translationText = `${translation} - ${englishSentence.replace(new RegExp(`\\b${word}\\b`, 'gi'), highlightedWord)}`;

        return {
            english: englishSentence,
            translation: translationText,
            difficulty: difficulty,
            wordType: type
        };
    }

    /**
     * Split long text into individual sentences
     * @param {string} text - Long text to split
     * @returns {Array} - Array of sentences
     */
    splitTextIntoSentences(text) {
        if (!text || typeof text !== 'string') return [];

        // Clean the text
        text = text.trim();

        // Split by common sentence endings (., !, ?)
        // But preserve abbreviations like "Mr.", "Dr.", etc.
        const sentences = text.split(/(?<=[.!?])\s+(?=[A-Z])/);

        return sentences
            .map(s => s.trim())
            .filter(s => s.length > 0 && s.length < 200) // Filter out too long or empty
            .filter(s => {
                // Filter out sentences that are just numbers or too short
                const words = s.split(/\s+/);
                return words.length >= 3 && words.length <= 30;
            });
    }

    /**
     * Validate generated sentence quality
     * @param {Object} sentence - Generated sentence object
     * @returns {boolean} - True if sentence meets quality standards
     */
    isValidSentence(sentence) {
        if (!sentence || !sentence.english) return false;

        const words = sentence.english.split(/\s+/);

        // Must have at least 2 words
        if (words.length < 2) return false;

        // Must end with proper punctuation
        if (!/[.!?]$/.test(sentence.english)) return false;

        // Must start with capital letter
        if (!/^[A-Z]/.test(sentence.english)) return false;

        return true;
    }

    /**
     * Generate multiple sentences from a word list
     * @param {Array} wordList - Array of {word, data} objects
     * @param {number} count - Number of sentences to generate
     * @returns {Array} - Array of sentence objects
     */
    generateMultipleSentences(wordList, count = 10) {
        const sentences = [];

        for (let i = 0; i < Math.min(count, wordList.length); i++) {
            const {word, data} = wordList[i];
            const sentence = this.generateSentence(word, data);

            if (this.isValidSentence(sentence)) {
                sentences.push({
                    type: 'vocabulary',
                    english: sentence.english,
                    translation: sentence.translation,
                    context: data.type || 'vocabulary',
                    difficulty: sentence.difficulty,
                    wordType: sentence.wordType
                });
            }
        }

        return sentences;
    }
}

// Export singleton instance
export const sentenceGenerator = new SentenceGenerator();
