package com.tomhempel.rbarometer.scoring

import com.tomhempel.rbarometer.network.ScoringProfileDefinition
import kotlin.math.round

/**
 * Mirrors profile weighted totals and [qdb_band_for_total] on the server.
 */
object ProfileScoringEngine {

    data class ProfileResult(
        val profileID: String,
        val name: String,
        val weightedTotal: Double,
        val calculatedBand: String,
        val complete: Boolean,
    )

    fun bandForTotal(total: Double, profile: ScoringProfileDefinition): String {
        val greenMin = profile.greenMin
        val greenMax = profile.greenMax
        val yellowMin = profile.yellowMin
        val yellowMax = profile.yellowMax
        val redMin = profile.redMin

        if (total >= greenMin && total <= greenMax) return "green"
        if (total >= yellowMin && total <= yellowMax) return "yellow"
        if (total >= redMin) return "red"
        if (total < greenMin) return "green"
        if (total < yellowMin) return "yellow"
        return "red"
    }

    fun computeProfile(
        profile: ScoringProfileDefinition,
        questionnairePoints: Map<String, Int>,
        completedQuestionnaireIds: Set<String>,
    ): ProfileResult? {
        if (!profile.isActive) return null
        var weightedTotal = 0.0
        for (member in profile.questionnaires) {
            if (!completedQuestionnaireIds.contains(member.questionnaireID)) {
                return null
            }
            val sumPoints = questionnairePoints[member.questionnaireID] ?: 0
            weightedTotal += sumPoints * member.weight
        }
        val rounded = round(weightedTotal * 10000.0) / 10000.0
        return ProfileResult(
            profileID = profile.profileID,
            name = profile.name,
            weightedTotal = rounded,
            calculatedBand = bandForTotal(rounded, profile),
            complete = true,
        )
    }
}
