package com.storycove.service;

import com.storycove.config.SolrProperties;
import com.storycove.dto.*;
import com.storycove.dto.LibraryOverviewStatsDto.StoryWordCountDto;
import com.storycove.repository.CollectionRepository;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.params.StatsParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@ConditionalOnProperty(
    value = "storycove.search.engine",
    havingValue = "solr",
    matchIfMissing = false
)
public class LibraryStatisticsService {

    private static final Logger logger = LoggerFactory.getLogger(LibraryStatisticsService.class);
    private static final int WORDS_PER_MINUTE = 250;

    @Autowired(required = false)
    private SolrClient solrClient;

    @Autowired
    private SolrProperties properties;

    @Autowired
    private LibraryService libraryService;

    @Autowired
    private CollectionRepository collectionRepository;

    /**
     * Get overview statistics for a library
     */
    public LibraryOverviewStatsDto getOverviewStatistics(String libraryId) throws IOException, SolrServerException {
        LibraryOverviewStatsDto stats = new LibraryOverviewStatsDto();

        // Collection Overview
        stats.setTotalStories(getTotalStories(libraryId));
        stats.setTotalAuthors(getTotalAuthors(libraryId));
        stats.setTotalSeries(getTotalSeries(libraryId));
        stats.setTotalTags(getTotalTags(libraryId));
        stats.setTotalCollections(getTotalCollections(libraryId));
        stats.setUniqueSourceDomains(getUniqueSourceDomains(libraryId));

        // Content Metrics - use Solr Stats Component
        WordCountStats wordStats = getWordCountStatistics(libraryId);
        stats.setTotalWordCount(wordStats.sum);
        stats.setAverageWordsPerStory(wordStats.mean);
        stats.setLongestStory(getLongestStory(libraryId));
        stats.setShortestStory(getShortestStory(libraryId));

        // Reading Time
        stats.setTotalReadingTimeMinutes(wordStats.sum / WORDS_PER_MINUTE);
        stats.setAverageReadingTimeMinutes(wordStats.mean / WORDS_PER_MINUTE);

        return stats;
    }

    /**
     * Get total number of stories in library
     */
    private long getTotalStories(String libraryId) throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.setRows(0); // We only want the count

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);
        return response.getResults().getNumFound();
    }

    /**
     * Get total number of authors in library
     */
    private long getTotalAuthors(String libraryId) throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.setRows(0);

        QueryResponse response = solrClient.query(properties.getCores().getAuthors(), query);
        return response.getResults().getNumFound();
    }

    /**
     * Get total number of series using faceting on seriesId
     */
    private long getTotalSeries(String libraryId) throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.addFilterQuery("seriesId:[* TO *]"); // Only stories that have a series
        query.setRows(0);
        query.setFacet(true);
        query.addFacetField("seriesId");
        query.setFacetLimit(-1); // Get all unique series

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);
        FacetField seriesFacet = response.getFacetField("seriesId");

        return (seriesFacet != null && seriesFacet.getValues() != null)
                ? seriesFacet.getValueCount()
                : 0;
    }

    /**
     * Get total number of unique tags using faceting
     */
    private long getTotalTags(String libraryId) throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.setRows(0);
        query.setFacet(true);
        query.addFacetField("tagNames");
        query.setFacetLimit(-1); // Get all unique tags

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);
        FacetField tagsFacet = response.getFacetField("tagNames");

        return (tagsFacet != null && tagsFacet.getValues() != null)
                ? tagsFacet.getValueCount()
                : 0;
    }

    /**
     * Get total number of collections
     */
    private long getTotalCollections(String libraryId) {
        // Collections are stored in the database, not indexed in Solr
        return collectionRepository.countByIsArchivedFalse();
    }

    /**
     * Get number of unique source domains using faceting
     */
    private long getUniqueSourceDomains(String libraryId) throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.addFilterQuery("sourceDomain:[* TO *]"); // Only stories with a source domain
        query.setRows(0);
        query.setFacet(true);
        query.addFacetField("sourceDomain");
        query.setFacetLimit(-1);

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);
        FacetField domainFacet = response.getFacetField("sourceDomain");

        return (domainFacet != null && domainFacet.getValues() != null)
                ? domainFacet.getValueCount()
                : 0;
    }

    /**
     * Get word count statistics using Solr Stats Component
     */
    private WordCountStats getWordCountStatistics(String libraryId) throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.setRows(0);
        query.setParam(StatsParams.STATS, true);
        query.setParam(StatsParams.STATS_FIELD, "wordCount");

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);

        WordCountStats stats = new WordCountStats();

        // Extract stats from response
        var fieldStatsInfo = response.getFieldStatsInfo();
        if (fieldStatsInfo != null && fieldStatsInfo.get("wordCount") != null) {
            var fieldStat = fieldStatsInfo.get("wordCount");

            Object sumObj = fieldStat.getSum();
            Object meanObj = fieldStat.getMean();

            stats.sum = (sumObj != null) ? ((Number) sumObj).longValue() : 0L;
            stats.mean = (meanObj != null) ? ((Number) meanObj).doubleValue() : 0.0;
        }

        return stats;
    }

    /**
     * Get the longest story in the library
     */
    private StoryWordCountDto getLongestStory(String libraryId) throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.addFilterQuery("wordCount:[1 TO *]"); // Exclude stories with 0 words
        query.setSort("wordCount", SolrQuery.ORDER.desc);
        query.setRows(1);
        query.setFields("id", "title", "authorName", "wordCount");

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);

        if (response.getResults().isEmpty()) {
            return null;
        }

        SolrDocument doc = response.getResults().get(0);
        return createStoryWordCountDto(doc);
    }

    /**
     * Get the shortest story in the library (excluding 0 word count)
     */
    private StoryWordCountDto getShortestStory(String libraryId) throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.addFilterQuery("wordCount:[1 TO *]"); // Exclude stories with 0 words
        query.setSort("wordCount", SolrQuery.ORDER.asc);
        query.setRows(1);
        query.setFields("id", "title", "authorName", "wordCount");

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);

        if (response.getResults().isEmpty()) {
            return null;
        }

        SolrDocument doc = response.getResults().get(0);
        return createStoryWordCountDto(doc);
    }

    /**
     * Helper method to create StoryWordCountDto from Solr document
     */
    private StoryWordCountDto createStoryWordCountDto(SolrDocument doc) {
        String id = (String) doc.getFieldValue("id");
        String title = (String) doc.getFieldValue("title");
        String authorName = (String) doc.getFieldValue("authorName");
        Object wordCountObj = doc.getFieldValue("wordCount");
        int wordCount = (wordCountObj != null) ? ((Number) wordCountObj).intValue() : 0;
        long readingTime = wordCount / WORDS_PER_MINUTE;

        return new StoryWordCountDto(id, title, authorName, wordCount, readingTime);
    }

    /**
     * Helper class to hold word count statistics
     */
    private static class WordCountStats {
        long sum = 0;
        double mean = 0.0;
    }

    /**
     * Get top tags statistics
     */
    public TopTagsStatsDto getTopTagsStatistics(String libraryId, int limit) throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.setRows(0);
        query.setFacet(true);
        query.addFacetField("tagNames");
        query.setFacetLimit(limit);
        query.setFacetSort("count"); // Sort by count (most popular first)

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);
        FacetField tagsFacet = response.getFacetField("tagNames");

        List<TopTagsStatsDto.TagStatsDto> topTags = new ArrayList<>();
        if (tagsFacet != null && tagsFacet.getValues() != null) {
            for (FacetField.Count count : tagsFacet.getValues()) {
                topTags.add(new TopTagsStatsDto.TagStatsDto(count.getName(), count.getCount()));
            }
        }

        return new TopTagsStatsDto(topTags);
    }

    /**
     * Get top authors statistics
     */
    public TopAuthorsStatsDto getTopAuthorsStatistics(String libraryId, int limit) throws IOException, SolrServerException {
        TopAuthorsStatsDto stats = new TopAuthorsStatsDto();

        // Top authors by story count
        stats.setTopAuthorsByStories(getTopAuthorsByStoryCount(libraryId, limit));

        // Top authors by total words
        stats.setTopAuthorsByWords(getTopAuthorsByWordCount(libraryId, limit));

        return stats;
    }

    private List<TopAuthorsStatsDto.AuthorStatsDto> getTopAuthorsByStoryCount(String libraryId, int limit)
            throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.setRows(0);
        query.setFacet(true);
        query.addFacetField("authorId");
        query.setFacetLimit(limit);
        query.setFacetSort("count");

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);
        FacetField authorFacet = response.getFacetField("authorId");

        List<TopAuthorsStatsDto.AuthorStatsDto> topAuthors = new ArrayList<>();
        if (authorFacet != null && authorFacet.getValues() != null) {
            for (FacetField.Count count : authorFacet.getValues()) {
                String authorId = count.getName();
                long storyCount = count.getCount();

                // Get author name and total words
                SolrQuery authorQuery = new SolrQuery("authorId:" + authorId);
                authorQuery.addFilterQuery("libraryId:" + libraryId);
                authorQuery.setRows(1);
                authorQuery.setFields("authorName");

                QueryResponse authorResponse = solrClient.query(properties.getCores().getStories(), authorQuery);
                String authorName = "";
                if (!authorResponse.getResults().isEmpty()) {
                    authorName = (String) authorResponse.getResults().get(0).getFieldValue("authorName");
                }

                // Get total words for this author
                long totalWords = getAuthorTotalWords(libraryId, authorId);

                topAuthors.add(new TopAuthorsStatsDto.AuthorStatsDto(authorId, authorName, storyCount, totalWords));
            }
        }

        return topAuthors;
    }

    private List<TopAuthorsStatsDto.AuthorStatsDto> getTopAuthorsByWordCount(String libraryId, int limit)
            throws IOException, SolrServerException {
        // First get all unique authors
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.setRows(0);
        query.setFacet(true);
        query.addFacetField("authorId");
        query.setFacetLimit(-1); // Get all authors
        query.setFacetSort("count");

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);
        FacetField authorFacet = response.getFacetField("authorId");

        List<TopAuthorsStatsDto.AuthorStatsDto> allAuthors = new ArrayList<>();
        if (authorFacet != null && authorFacet.getValues() != null) {
            for (FacetField.Count count : authorFacet.getValues()) {
                String authorId = count.getName();
                long storyCount = count.getCount();

                // Get author name
                SolrQuery authorQuery = new SolrQuery("authorId:" + authorId);
                authorQuery.addFilterQuery("libraryId:" + libraryId);
                authorQuery.setRows(1);
                authorQuery.setFields("authorName");

                QueryResponse authorResponse = solrClient.query(properties.getCores().getStories(), authorQuery);
                String authorName = "";
                if (!authorResponse.getResults().isEmpty()) {
                    authorName = (String) authorResponse.getResults().get(0).getFieldValue("authorName");
                }

                // Get total words for this author
                long totalWords = getAuthorTotalWords(libraryId, authorId);

                allAuthors.add(new TopAuthorsStatsDto.AuthorStatsDto(authorId, authorName, storyCount, totalWords));
            }
        }

        // Sort by total words and return top N
        return allAuthors.stream()
                .sorted(Comparator.comparingLong(TopAuthorsStatsDto.AuthorStatsDto::getTotalWords).reversed())
                .limit(limit)
                .collect(Collectors.toList());
    }

    private long getAuthorTotalWords(String libraryId, String authorId) throws IOException, SolrServerException {
        SolrQuery query = new SolrQuery("authorId:" + authorId);
        query.addFilterQuery("libraryId:" + libraryId);
        query.setRows(0);
        query.setParam(StatsParams.STATS, true);
        query.setParam(StatsParams.STATS_FIELD, "wordCount");

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);

        var fieldStatsInfo = response.getFieldStatsInfo();
        if (fieldStatsInfo != null && fieldStatsInfo.get("wordCount") != null) {
            var fieldStat = fieldStatsInfo.get("wordCount");
            Object sumObj = fieldStat.getSum();
            return (sumObj != null) ? ((Number) sumObj).longValue() : 0L;
        }

        return 0L;
    }

    /**
     * Get rating statistics
     */
    public RatingStatsDto getRatingStatistics(String libraryId) throws IOException, SolrServerException {
        RatingStatsDto stats = new RatingStatsDto();

        // Get average rating using stats component
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.addFilterQuery("rating:[* TO *]"); // Only rated stories
        query.setRows(0);
        query.setParam(StatsParams.STATS, true);
        query.setParam(StatsParams.STATS_FIELD, "rating");

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);
        long totalRated = response.getResults().getNumFound();

        var fieldStatsInfo = response.getFieldStatsInfo();
        if (fieldStatsInfo != null && fieldStatsInfo.get("rating") != null) {
            var fieldStat = fieldStatsInfo.get("rating");
            Object meanObj = fieldStat.getMean();
            stats.setAverageRating((meanObj != null) ? ((Number) meanObj).doubleValue() : 0.0);
        }

        stats.setTotalRatedStories(totalRated);

        // Get total stories to calculate unrated
        long totalStories = getTotalStories(libraryId);
        stats.setTotalUnratedStories(totalStories - totalRated);

        // Get rating distribution using faceting
        SolrQuery distQuery = new SolrQuery("*:*");
        distQuery.addFilterQuery("libraryId:" + libraryId);
        distQuery.addFilterQuery("rating:[* TO *]");
        distQuery.setRows(0);
        distQuery.setFacet(true);
        distQuery.addFacetField("rating");
        distQuery.setFacetLimit(-1);

        QueryResponse distResponse = solrClient.query(properties.getCores().getStories(), distQuery);
        FacetField ratingFacet = distResponse.getFacetField("rating");

        Map<Integer, Long> distribution = new HashMap<>();
        if (ratingFacet != null && ratingFacet.getValues() != null) {
            for (FacetField.Count count : ratingFacet.getValues()) {
                try {
                    int rating = Integer.parseInt(count.getName());
                    distribution.put(rating, count.getCount());
                } catch (NumberFormatException e) {
                    // Skip invalid ratings
                }
            }
        }

        stats.setRatingDistribution(distribution);

        return stats;
    }

    /**
     * Get source domain statistics
     */
    public SourceDomainStatsDto getSourceDomainStatistics(String libraryId, int limit) throws IOException, SolrServerException {
        SourceDomainStatsDto stats = new SourceDomainStatsDto();

        // Get top domains using faceting
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.addFilterQuery("sourceDomain:[* TO *]"); // Only stories with source
        query.setRows(0);
        query.setFacet(true);
        query.addFacetField("sourceDomain");
        query.setFacetLimit(limit);
        query.setFacetSort("count");

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);
        long storiesWithSource = response.getResults().getNumFound();

        FacetField domainFacet = response.getFacetField("sourceDomain");

        List<SourceDomainStatsDto.DomainStatsDto> topDomains = new ArrayList<>();
        if (domainFacet != null && domainFacet.getValues() != null) {
            for (FacetField.Count count : domainFacet.getValues()) {
                topDomains.add(new SourceDomainStatsDto.DomainStatsDto(count.getName(), count.getCount()));
            }
        }

        stats.setTopDomains(topDomains);
        stats.setStoriesWithSource(storiesWithSource);

        long totalStories = getTotalStories(libraryId);
        stats.setStoriesWithoutSource(totalStories - storiesWithSource);

        return stats;
    }

    /**
     * Get reading progress statistics
     */
    public ReadingProgressStatsDto getReadingProgressStatistics(String libraryId) throws IOException, SolrServerException {
        ReadingProgressStatsDto stats = new ReadingProgressStatsDto();

        long totalStories = getTotalStories(libraryId);
        stats.setTotalStories(totalStories);

        // Get read stories count
        SolrQuery readQuery = new SolrQuery("*:*");
        readQuery.addFilterQuery("libraryId:" + libraryId);
        readQuery.addFilterQuery("isRead:true");
        readQuery.setRows(0);

        QueryResponse readResponse = solrClient.query(properties.getCores().getStories(), readQuery);
        long readStories = readResponse.getResults().getNumFound();

        stats.setReadStories(readStories);
        stats.setUnreadStories(totalStories - readStories);

        if (totalStories > 0) {
            stats.setPercentageRead((readStories * 100.0) / totalStories);
        }

        // Get total words read
        SolrQuery readWordsQuery = new SolrQuery("*:*");
        readWordsQuery.addFilterQuery("libraryId:" + libraryId);
        readWordsQuery.addFilterQuery("isRead:true");
        readWordsQuery.setRows(0);
        readWordsQuery.setParam(StatsParams.STATS, true);
        readWordsQuery.setParam(StatsParams.STATS_FIELD, "wordCount");

        QueryResponse readWordsResponse = solrClient.query(properties.getCores().getStories(), readWordsQuery);
        var readFieldStats = readWordsResponse.getFieldStatsInfo();
        if (readFieldStats != null && readFieldStats.get("wordCount") != null) {
            var fieldStat = readFieldStats.get("wordCount");
            Object sumObj = fieldStat.getSum();
            stats.setTotalWordsRead((sumObj != null) ? ((Number) sumObj).longValue() : 0L);
        }

        // Get total words unread
        SolrQuery unreadWordsQuery = new SolrQuery("*:*");
        unreadWordsQuery.addFilterQuery("libraryId:" + libraryId);
        unreadWordsQuery.addFilterQuery("isRead:false");
        unreadWordsQuery.setRows(0);
        unreadWordsQuery.setParam(StatsParams.STATS, true);
        unreadWordsQuery.setParam(StatsParams.STATS_FIELD, "wordCount");

        QueryResponse unreadWordsResponse = solrClient.query(properties.getCores().getStories(), unreadWordsQuery);
        var unreadFieldStats = unreadWordsResponse.getFieldStatsInfo();
        if (unreadFieldStats != null && unreadFieldStats.get("wordCount") != null) {
            var fieldStat = unreadFieldStats.get("wordCount");
            Object sumObj = fieldStat.getSum();
            stats.setTotalWordsUnread((sumObj != null) ? ((Number) sumObj).longValue() : 0L);
        }

        return stats;
    }

    /**
     * Get reading activity statistics for the last week
     */
    public ReadingActivityStatsDto getReadingActivityStatistics(String libraryId) throws IOException, SolrServerException {
        ReadingActivityStatsDto stats = new ReadingActivityStatsDto();

        LocalDateTime oneWeekAgo = LocalDateTime.now().minusWeeks(1);
        String oneWeekAgoStr = oneWeekAgo.toInstant(ZoneOffset.UTC).toString();

        // Get stories read in last week
        SolrQuery query = new SolrQuery("*:*");
        query.addFilterQuery("libraryId:" + libraryId);
        query.addFilterQuery("lastReadAt:[" + oneWeekAgoStr + " TO *]");
        query.setRows(0);

        QueryResponse response = solrClient.query(properties.getCores().getStories(), query);
        long storiesReadLastWeek = response.getResults().getNumFound();
        stats.setStoriesReadLastWeek(storiesReadLastWeek);

        // Get words read in last week
        SolrQuery wordsQuery = new SolrQuery("*:*");
        wordsQuery.addFilterQuery("libraryId:" + libraryId);
        wordsQuery.addFilterQuery("lastReadAt:[" + oneWeekAgoStr + " TO *]");
        wordsQuery.setRows(0);
        wordsQuery.setParam(StatsParams.STATS, true);
        wordsQuery.setParam(StatsParams.STATS_FIELD, "wordCount");

        QueryResponse wordsResponse = solrClient.query(properties.getCores().getStories(), wordsQuery);
        var fieldStatsInfo = wordsResponse.getFieldStatsInfo();
        long wordsReadLastWeek = 0L;
        if (fieldStatsInfo != null && fieldStatsInfo.get("wordCount") != null) {
            var fieldStat = fieldStatsInfo.get("wordCount");
            Object sumObj = fieldStat.getSum();
            wordsReadLastWeek = (sumObj != null) ? ((Number) sumObj).longValue() : 0L;
        }

        stats.setWordsReadLastWeek(wordsReadLastWeek);
        stats.setReadingTimeMinutesLastWeek(wordsReadLastWeek / WORDS_PER_MINUTE);

        // Get daily activity (last 7 days)
        List<ReadingActivityStatsDto.DailyActivityDto> dailyActivity = new ArrayList<>();
        for (int i = 6; i >= 0; i--) {
            LocalDate date = LocalDate.now().minusDays(i);
            LocalDateTime dayStart = date.atStartOfDay();
            LocalDateTime dayEnd = date.atTime(23, 59, 59);

            String dayStartStr = dayStart.toInstant(ZoneOffset.UTC).toString();
            String dayEndStr = dayEnd.toInstant(ZoneOffset.UTC).toString();

            SolrQuery dayQuery = new SolrQuery("*:*");
            dayQuery.addFilterQuery("libraryId:" + libraryId);
            dayQuery.addFilterQuery("lastReadAt:[" + dayStartStr + " TO " + dayEndStr + "]");
            dayQuery.setRows(0);
            dayQuery.setParam(StatsParams.STATS, true);
            dayQuery.setParam(StatsParams.STATS_FIELD, "wordCount");

            QueryResponse dayResponse = solrClient.query(properties.getCores().getStories(), dayQuery);
            long storiesRead = dayResponse.getResults().getNumFound();

            long wordsRead = 0L;
            var dayFieldStats = dayResponse.getFieldStatsInfo();
            if (dayFieldStats != null && dayFieldStats.get("wordCount") != null) {
                var fieldStat = dayFieldStats.get("wordCount");
                Object sumObj = fieldStat.getSum();
                wordsRead = (sumObj != null) ? ((Number) sumObj).longValue() : 0L;
            }

            dailyActivity.add(new ReadingActivityStatsDto.DailyActivityDto(
                    date.format(DateTimeFormatter.ISO_LOCAL_DATE),
                    storiesRead,
                    wordsRead
            ));
        }

        stats.setDailyActivity(dailyActivity);

        return stats;
    }
}
