package com.jishisongfu.duobibi.util

import com.jishisongfu.duobibi.data.db.Cluster
import com.jishisongfu.duobibi.data.db.PriceRecord

/**
 * 一个商品簇的统计数据。
 */
data class ClusterStats(
    val clusterId: Long,
    val title: String,
    val recordCount: Int,
    val minPrice: Double,
    val maxPrice: Double,
    val priceSpread: Double,
    val sources: List<String>,
)

/**
 * 全局统计快照。
 */
data class OverallStats(
    val totalRecords: Int,
    val totalProducts: Int,
    val totalPlatforms: Int,
    val totalSaved: Double,        // 各簇 max-min 之和
    val avgSavePerProduct: Double, // totalSaved / totalProducts (有商品时)
    val recordsByPlatform: Map<String, Int>,
    val topSpread: List<ClusterStats>,
    val recordsToday: Int,
)

object StatsCalculator {

    fun computeOverall(
        clusters: List<Cluster>,
        records: List<PriceRecord>,
        nowMillis: Long = System.currentTimeMillis(),
    ): OverallStats {
        val recordsByCluster = records.groupBy { it.clusterId }
        val clusterStats = clusters.mapNotNull { c ->
            val items = recordsByCluster[c.id].orEmpty()
            if (items.isEmpty()) return@mapNotNull null
            val minP = items.minOf { it.price }
            val maxP = items.maxOf { it.price }
            ClusterStats(
                clusterId = c.id,
                title = c.title,
                recordCount = items.size,
                minPrice = minP,
                maxPrice = maxP,
                priceSpread = maxP - minP,
                sources = items.map { it.sourceApp }.distinct(),
            )
        }

        val totalSaved = clusterStats.sumOf { it.priceSpread }
        val totalProducts = clusterStats.size
        val recordsByPlatform = records.groupingBy { it.sourceApp }.eachCount()
        val topSpread = clusterStats
            .filter { it.priceSpread > 0 }
            .sortedByDescending { it.priceSpread }
            .take(5)

        val startOfToday = startOfDay(nowMillis)
        val recordsToday = records.count { it.createdAt >= startOfToday }

        return OverallStats(
            totalRecords = records.size,
            totalProducts = totalProducts,
            totalPlatforms = recordsByPlatform.size,
            totalSaved = totalSaved,
            avgSavePerProduct = if (totalProducts > 0) totalSaved / totalProducts else 0.0,
            recordsByPlatform = recordsByPlatform,
            topSpread = topSpread,
            recordsToday = recordsToday,
        )
    }

    /**
     * 按 createdAt 时间窗口过滤记录。
     * @param windowDays null 表示全部,>0 表示只取最近 N 天
     */
    fun filterByWindow(records: List<PriceRecord>, windowDays: Int?, nowMillis: Long = System.currentTimeMillis()): List<PriceRecord> {
        if (windowDays == null) return records
        val cutoff = nowMillis - windowDays * 24L * 60L * 60L * 1000L
        return records.filter { it.createdAt >= cutoff }
    }

    private fun startOfDay(ms: Long): Long {
        val cal = java.util.Calendar.getInstance()
        cal.timeInMillis = ms
        cal.set(java.util.Calendar.HOUR_OF_DAY, 0)
        cal.set(java.util.Calendar.MINUTE, 0)
        cal.set(java.util.Calendar.SECOND, 0)
        cal.set(java.util.Calendar.MILLISECOND, 0)
        return cal.timeInMillis
    }
}
