"""
SQLAlchemy model for matches.

This module defines the database model for storing match information.
"""

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

from app.database import Base


class Match(Base):
    """
    Model for storing match information.
    
    Attributes:
        id: Primary key
        home_team: Name of the home team
        away_team: Name of the away team
        date: Match date and time
        league: League name
        status: Match status (scheduled, in_progress, completed, etc.)
    """
    __tablename__ = "matches"
    
    id = Column(Integer, primary_key=True, index=True)
    home_team = Column(String(255), nullable=False, index=True)
    away_team = Column(String(255), nullable=False, index=True)
    date = Column(DateTime, nullable=False, index=True)
    league = Column(String(255), nullable=False, index=True)
    status = Column(String(50), nullable=False, index=True)
    actual_winner = Column(String(255), nullable=True, index=True, comment='Actual winner: home, away, or draw')
    
    # Relationships
    predictions = relationship("Prediction", back_populates="match", cascade="all, delete-orphan")
    tweets = relationship("Tweet", back_populates="match", cascade="all, delete-orphan")
    posts_reddit = relationship("RedditPost", back_populates="match", cascade="all, delete-orphan")
    rss_articles = relationship("RSSArticle", back_populates="match", cascade="all, delete-orphan")
    
    # Indexes for performance
    __table_args__ = (
        Index('idx_matches_date_league', 'date', 'league'),
        Index('idx_matches_home_away', 'home_team', 'away_team'),
        Index('idx_matches_actual_winner', 'actual_winner'),
    )
    
    def __repr__(self) -> str:
        return f"<Match(id={self.id}, {self.home_team} vs {self.away_team}, date={self.date})>"
    
    def to_dict(self) -> dict:
        """Convert match model to dictionary."""
        return {
            'id': self.id,
            'home_team': self.home_team,
            'away_team': self.away_team,
            'date': self.date.isoformat() if self.date else None,
            'league': self.league,
            'status': self.status,
            'actual_winner': self.actual_winner
        }
