package com.swoosh.microblog.data.model

import androidx.compose.runtime.Immutable

/**
 * Aggregate statistics across all posts.
 */
@Immutable
data class OverallStats(
    val totalPosts: Int = 0,
    val publishedCount: Int = 0,
    val draftCount: Int = 0,
    val scheduledCount: Int = 0,
    val totalWords: Int = 0,
    val totalCharacters: Int = 0,
    val averageWordCount: Int = 0,
    val averageCharCount: Int = 0,
    val longestPostWords: Int = 0,
    val shortestPostWords: Int = 0
) {
    companion object {
        /**
         * Calculate overall stats from lists of local and remote posts.
         */
        fun calculate(
            localPosts: List<LocalPost>,
            remotePosts: List<FeedPost>
        ): OverallStats {
            // Combine all text content
            val allTexts = mutableListOf<String>()
            var publishedCount = 0
            var draftCount = 0
            var scheduledCount = 0

            for (post in localPosts) {
                allTexts.add(post.content)
                when (post.status) {
                    PostStatus.PUBLISHED -> publishedCount++
                    PostStatus.DRAFT -> draftCount++
                    PostStatus.SCHEDULED -> scheduledCount++
                    PostStatus.SENT -> publishedCount++ // sent counts as published
                }
            }

            for (post in remotePosts) {
                allTexts.add(post.textContent)
                when (post.status.lowercase()) {
                    "published" -> publishedCount++
                    "draft" -> draftCount++
                    "scheduled" -> scheduledCount++
                    "sent" -> publishedCount++
                }
            }

            val wordCounts = allTexts.map { PostStats.countWords(it) }
            val charCounts = allTexts.map { it.length }

            val totalPosts = allTexts.size
            val totalWords = wordCounts.sum()
            val totalChars = charCounts.sum()

            return OverallStats(
                totalPosts = totalPosts,
                publishedCount = publishedCount,
                draftCount = draftCount,
                scheduledCount = scheduledCount,
                totalWords = totalWords,
                totalCharacters = totalChars,
                averageWordCount = if (totalPosts > 0) totalWords / totalPosts else 0,
                averageCharCount = if (totalPosts > 0) totalChars / totalPosts else 0,
                longestPostWords = wordCounts.maxOrNull() ?: 0,
                shortestPostWords = wordCounts.minOrNull() ?: 0
            )
        }
    }
}
