"""
SQLAlchemy model for predictions.

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

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

from app.database import Base


class Prediction(Base):
    """
    Model for storing match predictions.
    
    Attributes:
        id: Primary key
        match_id: Foreign key to matches table
        energy_score: Energy score for the prediction
        confidence: Confidence level of the prediction
        predicted_winner: Predicted winner team name
        created_at: Timestamp when prediction was created
    """
    __tablename__ = "predictions"
    
    id = Column(Integer, primary_key=True, index=True)
    match_id = Column(Integer, ForeignKey("matches.id", ondelete="CASCADE"), nullable=False, index=True)
    energy_score = Column(String(50), nullable=False)
    confidence = Column(String(50), nullable=False)
    predicted_winner = Column(String(255), nullable=False)
    created_at = Column(DateTime, nullable=False, index=True)
    
    # Relationships
    match = relationship("Match", back_populates="predictions")
    user_predictions = relationship("UserPrediction", back_populates="prediction", cascade="all, delete-orphan")
    
    # Indexes for performance
    __table_args__ = (
        Index('idx_predictions_match_id_created', 'match_id', 'created_at'),
        Index('idx_predictions_confidence', 'confidence'),
    )
    
    def __repr__(self) -> str:
        return f"<Prediction(id={self.id}, match_id={self.match_id}, confidence={self.confidence})>"
    
    def to_dict(self) -> dict:
        """Convert prediction model to dictionary."""
        return {
            'id': self.id,
            'match_id': self.match_id,
            'energy_score': self.energy_score,
            'confidence': self.confidence,
            'predicted_winner': self.predicted_winner,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
