"""
SQLAlchemy model for tweets.

This module defines the database model for storing tweets collected
from Twitter, Reddit, and RSS sources.
"""

from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, Index, ForeignKey
from sqlalchemy.orm import relationship

from app.database import Base


class Tweet(Base):
    """
    Model for storing tweets collected from social media sources.
    
    Attributes:
        id: Primary key
        tweet_id: Unique identifier from the source platform
        text: Tweet content
        created_at: Timestamp when the tweet was created
        retweet_count: Number of retweets
        like_count: Number of likes
        match_id: Foreign key to matches table
        source: Source platform (twitter, reddit, rss)
    """
    __tablename__ = "tweets"
    
    id = Column(Integer, primary_key=True, index=True)
    tweet_id = Column(String(255), unique=True, nullable=False, index=True)
    text = Column(String(1000), nullable=False)
    created_at = Column(DateTime, nullable=False, index=True)
    retweet_count = Column(Integer, default=0)
    like_count = Column(Integer, default=0)
    match_id = Column(Integer, ForeignKey('matches.id'), nullable=True, index=True)
    source = Column(String(50), default="twitter")
    
    # Indexes for performance
    __table_args__ = (
        Index('idx_tweets_match_id_source', 'match_id', 'source'),
        Index('idx_tweets_created_at', 'created_at'),
    )
    
    # Relationship with match
    match = relationship("Match", back_populates="tweets")
    
    def __repr__(self) -> str:
        return f"<Tweet(id={self.id}, tweet_id={self.tweet_id}, match_id={self.match_id})>"
    
    def to_dict(self) -> dict:
        """Convert tweet model to dictionary."""
        return {
            'id': self.id,
            'tweet_id': self.tweet_id,
            'text': self.text,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'retweet_count': self.retweet_count,
            'like_count': self.like_count,
            'match_id': self.match_id,
            'source': self.source
        }
