package com.swoosh.microblog.data.model

import androidx.compose.runtime.Immutable

/**
 * Statistics calculated for a single post.
 */
@Immutable
data class PostStats(
    val wordCount: Int,
    val charCount: Int,
    val readingTimeMinutes: Int,
    val hasImage: Boolean,
    val hasLink: Boolean
) {
    companion object {
        private const val WORDS_PER_MINUTE = 200

        /**
         * Calculate post statistics from text content and metadata.
         */
        fun fromContent(
            text: String,
            hasImage: Boolean = false,
            hasLink: Boolean = false
        ): PostStats {
            val charCount = text.length
            val wordCount = countWords(text)
            val readingTime = estimateReadingTime(wordCount)
            return PostStats(
                wordCount = wordCount,
                charCount = charCount,
                readingTimeMinutes = readingTime,
                hasImage = hasImage,
                hasLink = hasLink
            )
        }

        /**
         * Calculate post statistics from a FeedPost.
         */
        fun fromFeedPost(post: FeedPost): PostStats {
            return fromContent(
                text = post.textContent,
                hasImage = post.imageUrl != null,
                hasLink = post.linkUrl != null
            )
        }

        /**
         * Count words in text by splitting on whitespace.
         * Handles multiple spaces, newlines, tabs, and empty strings.
         */
        fun countWords(text: String): Int {
            val trimmed = text.trim()
            if (trimmed.isEmpty()) return 0
            return trimmed.split(Regex("\\s+")).size
        }

        /**
         * Estimate reading time in minutes based on word count.
         * Uses 200 words per minute as average reading speed.
         * Returns at least 1 minute for non-empty content.
         */
        fun estimateReadingTime(wordCount: Int): Int {
            if (wordCount <= 0) return 0
            val minutes = wordCount / WORDS_PER_MINUTE
            return maxOf(1, minutes)
        }

        /**
         * Format reading time for display.
         */
        fun formatReadingTime(minutes: Int): String {
            return when {
                minutes <= 0 -> ""
                minutes == 1 -> "1 min read"
                else -> "$minutes min read"
            }
        }

        /**
         * Format a live stats string for the composer.
         */
        fun formatComposerStats(text: String): String {
            val charCount = text.length
            val wordCount = countWords(text)
            val readingTime = estimateReadingTime(wordCount)
            return if (charCount == 0) {
                "0 chars"
            } else {
                val readingLabel = formatReadingTime(readingTime)
                "$charCount chars · $wordCount words · ~$readingLabel"
            }
        }
    }
}
