"""
Add a vocabulary entry for a specific user
"""
import os
import sqlite3
from datetime import datetime
import sys

def add_vocabulary_for_user(user_id):
    """Add a vocabulary entry for the specified user"""
    
    # Determine the database path
    root_dir = os.path.dirname(os.path.abspath(__file__))
    instance_db = os.path.join(root_dir, 'instance', 'app.db')
    root_db = os.path.join(root_dir, 'app.db')
    
    if os.path.exists(instance_db):
        db_path = instance_db
    elif os.path.exists(root_db):
        db_path = root_db
    else:
        print(f"ERROR: Database not found at {instance_db} or {root_db}")
        return False
    
    print(f"Using database at: {db_path}")
    
    try:
        # Connect to the database
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # Verify user exists
        cursor.execute("SELECT id, username FROM users WHERE id = ?", (user_id,))
        user = cursor.fetchone()
        
        if not user:
            print(f"ERROR: User with ID {user_id} not found.")
            return False
        
        print(f"Adding vocabulary entry for user: {user[1]} (ID: {user[0]})")
        
        # Add vocabulary entry
        current_time = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
        cursor.execute('''
        INSERT INTO vocabulary (student_id, word, pronunciation, definition, synonyms, antonyms, example, date_added)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ''', (
            user_id,
            'Serendipity',
            '/ˌsɛrənˈdɪpɪti/',
            'The occurrence and development of events by chance in a happy or beneficial way.',
            'fate,chance,luck,providence',
            'misfortune,design,intent,plan',
            'They were not looking to make this discovery; it was serendipity.',
            current_time
        ))
        
        # Commit the changes
        conn.commit()
        print(f"Vocabulary entry added successfully for user {user_id}!")
        
        # Verify entry was added
        cursor.execute('''
        SELECT id, word FROM vocabulary WHERE student_id = ? ORDER BY date_added DESC LIMIT 1
        ''', (user_id,))
        entry = cursor.fetchone()
        
        if entry:
            print(f"Confirmed: Entry ID {entry[0]} with word '{entry[1]}' was added.")
        else:
            print("WARNING: Could not verify the entry was added.")
            
        conn.close()
        return True
        
    except Exception as e:
        print(f"ERROR: {e}")
        return False

if __name__ == "__main__":
    if len(sys.argv) > 1:
        try:
            user_id = int(sys.argv[1])
            success = add_vocabulary_for_user(user_id)
            if success:
                print("\nSuccess! The vocabulary entry has been added.")
            else:
                print("\nFailed to add vocabulary entry.")
        except ValueError:
            print(f"ERROR: Invalid user ID format: {sys.argv[1]}")
    else:
        print("Please provide a user ID as a command line argument.")
        print("Example usage: python add_vocabulary_entry.py 3")