from app import db
from datetime import datetime

class Vocabulary(db.Model):
    """Model for storing vocabulary words saved by students"""
    __tablename__ = 'vocabulary'
    
    id = db.Column(db.Integer, primary_key=True)
    student_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    word = db.Column(db.String(100), nullable=False)
    pronunciation = db.Column(db.String(100))
    definition = db.Column(db.Text, nullable=False)
    context = db.Column(db.Text)  # Sentence or context where the word appears
    source = db.Column(db.Text)   # Where the word was found or learned
    synonyms = db.Column(db.Text)  # Stored as comma-separated values
    antonyms = db.Column(db.Text)  # Stored as comma-separated values
    example = db.Column(db.Text)
    date_added = db.Column(db.DateTime, default=datetime.utcnow)
    
    # Define relationship with User model
    # student = db.relationship('User', backref=db.backref('vocabulary_words', lazy=True))

    def __repr__(self):
        return f'<Vocabulary {self.word}>'
    
    # Helper methods to handle comma-separated values
    def get_synonyms_list(self):
        """Convert comma-separated synonyms string to list"""
        if not self.synonyms:
            return []
        return [syn.strip() for syn in self.synonyms.split(',')]

    def get_antonyms_list(self):
        """Convert comma-separated antonyms string to list"""
        if not self.antonyms:
            return []
        return [ant.strip() for ant in self.antonyms.split(',')]

    def to_dict(self):
        """Convert model to dictionary for API responses"""
        return {
            'id': self.id,
            'word': self.word,
            'pronunciation': self.pronunciation,
            'definition': self.definition,
            'context': self.context,
            'source': self.source,
            'synonyms': self.get_synonyms_list(),
            'antonyms': self.get_antonyms_list(),
            'example': self.example,
            'date_added': self.date_added.strftime('%Y-%m-%d %H:%M:%S')
        }