"""
SQLAlchemy model for RSS articles.

This module defines the database model for storing RSS articles
collected from various RSS feeds.
"""

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

from app.database import Base


class RSSArticle(Base):
    """
    Model for storing RSS articles collected from sports feeds.
    
    Attributes:
        id: Primary key
        article_id: Unique identifier from RSS feed
        title: Article title
        content: Article content/description
        published_at: Timestamp when article was published
        source_url: URL of the RSS feed source
        match_id: Foreign key to matches table
        source: Source feed name (ESPN, BBC Sport, etc.)
    """
    __tablename__ = "rss_articles"
    
    id = Column(Integer, primary_key=True, index=True)
    article_id = Column(String(255), unique=True, nullable=False, index=True)
    title = Column(String(500), nullable=False)
    content = Column(Text, nullable=True)
    published_at = Column(DateTime, nullable=False, index=True)
    source_url = Column(String(1000), nullable=False)
    match_id = Column(Integer, ForeignKey('matches.id'), nullable=True, index=True)
    source = Column(String(100), default="rss")
    
    # Indexes for performance
    __table_args__ = (
        Index('idx_rss_articles_match_id_source', 'match_id', 'source'),
        Index('idx_rss_articles_published_at', 'published_at'),
        Index('idx_rss_articles_source_url', 'source_url'),
    )
    
    # Relationship with match
    match = relationship("Match", back_populates="rss_articles")
    
    def __repr__(self) -> str:
        return f"<RSSArticle(id={self.id}, article_id={self.article_id}, match_id={self.match_id})>"
    
    def to_dict(self) -> dict:
        """Convert RSS article model to dictionary."""
        return {
            'id': self.id,
            'article_id': self.article_id,
            'title': self.title,
            'content': self.content,
            'published_at': self.published_at.isoformat() if self.published_at else None,
            'source_url': self.source_url,
            'match_id': self.match_id,
            'source': self.source
        }
