"""
Chase Notification Service
Sends email notifications to users when songs they're chasing are played.
"""
from sqlmodel import Session, select
from models import ChaseSong, User, Song, Show, Performance, Venue
from helpers import create_notification


def notify_chase_users(session: Session, song_id: int, show_id: int, performance_id: int):
    """
    Send notifications to all users chasing this song.
    Called after a new performance is imported.
    """
    from services.email_service import send_chase_notification_email
    
    # Get song, show, and venue info for the notification
    song = session.get(Song, song_id)
    show = session.get(Show, show_id)
    
    if not song or not show:
        return 0
    
    venue = session.get(Venue, show.venue_id) if show.venue_id else None
    
    # Find all users chasing this song who haven't caught it yet
    chase_songs = session.exec(
        select(ChaseSong)
        .where(ChaseSong.song_id == song_id)
        .where(ChaseSong.caught_at.is_(None))  # Not yet caught
    ).all()
    
    notified_count = 0
    
    for chase in chase_songs:
        user = session.get(User, chase.user_id)
        if not user:
            continue
        
        # Create in-app notification
        create_notification(
            session,
            user_id=user.id,
            title="Chase Alert!",
            message=f"{song.title} was played at {venue.name if venue else 'a show'}!",
            type="chase",
            link=f"/performances/{performance_id}"  # Link to performance page
        )
        
        # Send email if user has chase alerts enabled
        if user.preferences and user.preferences.email_on_chase:
            show_date = show.date.strftime("%Y-%m-%d") if show.date else "Unknown date"
            venue_name = venue.name if venue else "Unknown venue"
            
            # Get performance slug for link
            perf = session.get(Performance, performance_id)
            perf_link = f"/performances/{perf.slug}" if perf and perf.slug else f"/shows/{show.slug}"
            
            send_chase_notification_email(
                to_email=user.email,
                song_title=song.title,
                show_date=show_date,
                venue_name=venue_name,
                link=perf_link
            )
            notified_count += 1
    
    return notified_count


def check_new_performances_for_chases(session: Session, performance_ids: list):
    """
    Check a list of newly imported performances and notify chase users.
    Call this after batch importing shows.
    """
    total_notified = 0
    
    for perf_id in performance_ids:
        perf = session.get(Performance, perf_id)
        if perf:
            count = notify_chase_users(session, perf.song_id, perf.show_id, perf.id)
            total_notified += count
    
    if total_notified > 0:
        print(f"📧 Sent {total_notified} chase notification emails")
    
    return total_notified
