import datetime
from collections import defaultdict

from django.db.models import Q
from scrobbles.models import Scrobble


def compute_reading_pace_vs_activity(user, period="all_time"):
    """Compare reading pace (seconds per session) when music is playing vs. not.

    For each Book scrobble with a playback_position_seconds value, checks
    whether there is an overlapping Track scrobble and groups the data.
    Returns average session duration for both groups.
    """
    from trends.utils import get_date_range

    start, end = get_date_range(period)
    base_filters = Q(user=user, timestamp__isnull=False)
    if start:
        base_filters &= Q(timestamp__gte=start)
    if end:
        base_filters &= Q(timestamp__lte=end)

    book_scrobbles = list(
        Scrobble.objects.filter(
            base_filters,
            media_type="Book",
            playback_position_seconds__isnull=False,
            played_to_completion=True,
        )
        .select_related("book")
        .order_by("-timestamp")
    )

    if not book_scrobbles:
        return {"with_music": None, "without_music": None}

    track_scrobbles = list(
        Scrobble.objects.filter(
            base_filters,
            media_type="Track",
            played_to_completion=True,
        ).order_by("-timestamp")
    )

    track_ranges = []
    for ts in track_scrobbles:
        p_start = ts.timestamp
        p_end = ts.stop_timestamp
        if p_end is None:
            try:
                p_end = p_start + datetime.timedelta(hours=12)
            except AttributeError:
                p_end = p_start
        track_ranges.append((p_start, p_end))

    with_music_durations = []
    without_music_durations = []

    for bs in book_scrobbles:
        b_start = bs.timestamp
        b_end = bs.stop_timestamp
        if b_end is None:
            try:
                b_end = b_start + datetime.timedelta(hours=12)
            except AttributeError:
                b_end = b_start

        has_overlap = False
        for p_start, p_end in track_ranges:
            if b_start <= p_end and p_start <= b_end:
                has_overlap = True
                break

        duration = bs.playback_position_seconds
        if has_overlap:
            with_music_durations.append(duration)
        else:
            without_music_durations.append(duration)

    def _stats(durations):
        if not durations:
            return None
        return {
            "avg_seconds": int(sum(durations) / len(durations)),
            "sessions_count": len(durations),
            "total_seconds": sum(durations),
        }

    return {
        "with_music": _stats(with_music_durations),
        "without_music": _stats(without_music_durations),
    }
