package com.system.cloudservice.antiban

import com.system.cloudservice.util.Logger
import java.util.*
import kotlin.random.Random

class NurtureScheduler(
    private val phase: String = "new",
    private val accountAgeDays: Int = 0,
) {
    companion object {
        private val NURTURE_ACTIONS = listOf(
            NurtureAction("browse_moments", "浏览朋友圈", 3, 120..300),
            NurtureAction("browse_discover", "浏览发现页", 2, 60..180),
            NurtureAction("read_articles", "阅读文章", 2, 90..240),
            NurtureAction("check_contacts", "查看通讯录", 1, 30..60),
            NurtureAction("browse_miniprogram", "浏览小程序", 1, 60..120),
        )

        private val PHASE_LIMITS = mapOf(
            "new" to PhaseConfig(maxDailyActions = 5, minIntervalMin = 60, allowedHours = 9..21),
            "warming" to PhaseConfig(maxDailyActions = 10, minIntervalMin = 30, allowedHours = 8..22),
            "active" to PhaseConfig(maxDailyActions = 20, minIntervalMin = 15, allowedHours = 7..23),
        )
    }

    private data class NurtureAction(
        val action: String, val name: String,
        val weight: Int, val durationRange: IntRange,
    )

    private data class PhaseConfig(
        val maxDailyActions: Int, val minIntervalMin: Int, val allowedHours: IntRange,
    )

    private var dailyActionCount = 0
    private var lastActionAt = 0L
    private var lastResetDay = -1

    @Volatile private var paused = false

    /** AB-02 熔断时暂停暖机；AB-03 降速时仍允许（shouldNurture 自身频控） */
    fun pause() { paused = true; Logger.i("NurtureScheduler paused (risk circuit breaker)") }
    fun resume() { if (paused) { paused = false; Logger.i("NurtureScheduler resumed") } }
    fun isPaused(): Boolean = paused

    fun shouldNurture(): Boolean {
        if (paused) return false
        val now = Calendar.getInstance()
        val day = now.get(Calendar.DAY_OF_YEAR)
        if (day != lastResetDay) {
            dailyActionCount = 0
            lastResetDay = day
        }
        val config = PHASE_LIMITS[phase] ?: PHASE_LIMITS["new"]!!
        val hour = now.get(Calendar.HOUR_OF_DAY)
        if (hour !in config.allowedHours) return false
        if (dailyActionCount >= config.maxDailyActions) return false
        val elapsed = (System.currentTimeMillis() - lastActionAt) / 60_000
        return elapsed >= config.minIntervalMin
    }

    fun pickAction(): Map<String, Any> {
        val weighted = NURTURE_ACTIONS.flatMap { a -> List(a.weight) { a } }
        val chosen = weighted[Random.nextInt(weighted.size)]
        val duration = Random.nextInt(chosen.durationRange.first, chosen.durationRange.last + 1)
        return mapOf(
            "action" to chosen.action,
            "name" to chosen.name,
            "duration_sec" to duration,
        )
    }

    fun recordAction(action: String) {
        dailyActionCount++
        lastActionAt = System.currentTimeMillis()
        Logger.i("Nurture: $action (daily count: $dailyActionCount)")
    }

    fun getStatus(): Map<String, Any?> = mapOf(
        "phase" to phase,
        "account_age_days" to accountAgeDays,
        "daily_action_count" to dailyActionCount,
        "last_action_at" to lastActionAt,
        "paused" to paused,
    )
}
