import datetime
import logging
from sqlalchemy.orm import Session
from sqlalchemy import exists, and_

from watcher.tasks.base import lock_task
from watcher.db.base import dbconnect
from watcher.db import Rating, CompositionParticipants, Composition, Shift, Schedule
from watcher.logic.timezone import now

logger = logging.getLogger(__name__)


@lock_task(save_metrics=True, send_to_unistat=True)
@dbconnect
def remove_obsolete_ratings(session: Session):
    """
    Удаляем рейтинги у людей, которых нет в составе
    и которые не дежурили более трех месяце
    """
    query = (
        session.query(Rating.id)
        .join(Schedule, Schedule.id == Rating.schedule_id)
        .join(Composition, Composition.service_id == Schedule.service_id)
        .filter(
            ~exists().where(
                and_(
                    CompositionParticipants.staff_id == Rating.staff_id,
                    CompositionParticipants.composition_id == Composition.id,
                )
            ),
            ~exists().where(
                and_(
                    Shift.staff_id == Rating.staff_id,
                    Shift.end > now() - datetime.timedelta(days=90),
                    Shift.schedule_id == Rating.schedule_id
                )
            )
        )
    )
    logger.info(f'Delete {query.count()} obsolete ratings')
    session.query(Rating).filter(
        Rating.id.in_([obj.id for obj in query])
    ).delete(synchronize_session='fetch')
