"""Prediction repository"""
from typing import Optional, List
from datetime import datetime
from sqlalchemy.orm import Session
from app.core.db.models.prediction import Prediction
from app.core.db.models.match import Match


class PredictionRepository:
    """Repository for prediction operations"""
    
    def __init__(self, db: Session):
        self.db = db
    
    def get_by_match_id(self, match_id: int, model_id: Optional[int] = None) -> List[Prediction]:
        """Get predictions for a match"""
        query = self.db.query(Prediction).filter(Prediction.match_id == match_id)
        if model_id:
            query = query.filter(Prediction.model_id == model_id)
        return query.all()
    
    def get_latest_for_match(self, match_id: int, model_id: Optional[int] = None) -> Optional[Prediction]:
        """Get latest prediction for a match (optionally for a specific model)."""
        q = self.db.query(Prediction).filter(Prediction.match_id == match_id)
        if model_id is not None:
            q = q.filter(Prediction.model_id == model_id)
        return q.order_by(Prediction.calculated_at.desc()).first()

    def get_upcoming(
        self,
        league_id: Optional[int] = None,
        model_id: Optional[int] = None,
        limit: int = 100
    ) -> List[Prediction]:
        """Get upcoming predictions"""
        query = self.db.query(Prediction).join(Match).filter(
            Match.status == "scheduled"
        )
        
        if league_id:
            query = query.filter(Match.league_id == league_id)
        
        if model_id:
            query = query.filter(Prediction.model_id == model_id)
        
        return query.order_by(Match.match_date).limit(limit).all()
    
    def create(self, prediction: Prediction) -> Prediction:
        """Create a new prediction"""
        self.db.add(prediction)
        self.db.commit()
        self.db.refresh(prediction)
        return prediction
    
    def update_or_create(self, match_id: int, model_id: int, **kwargs) -> Prediction:
        """Update or create prediction"""
        prediction = self.db.query(Prediction).filter(
            Prediction.match_id == match_id,
            Prediction.model_id == model_id
        ).first()
        
        if prediction:
            for key, value in kwargs.items():
                setattr(prediction, key, value)
            prediction.calculated_at = datetime.utcnow()
        else:
            prediction = Prediction(match_id=match_id, model_id=model_id, **kwargs)
            self.db.add(prediction)
        
        self.db.commit()
        self.db.refresh(prediction)
        return prediction

