package com.system.cloudservice.antiban

import com.system.cloudservice.util.Logger
import kotlinx.coroutines.CoroutineScope

class AntiBanManager(
    scope: CoroutineScope,
) {
    val nurtureScheduler = NurtureScheduler(phase = "new")
    val riskSentinel = RiskSentinel { level, msg ->
        Logger.w("RiskAlert Lv$level: $msg")
        // AB-02 熔断联动：level>=3 暂停暖机，level<=1 恢复
        when {
            level >= 3 -> nurtureScheduler.pause()
            level <= 1 -> nurtureScheduler.resume()
        }
    }
    val deviceGuard = DeviceGuard()
    val touchHardener = TouchHardener()
    val sensorSimulator = SensorSimulator(scope)

    private var guardReport: DeviceGuard.CheckResult? = null

    fun init() {
        Logger.i("AntiBanManager initializing...")
        guardReport = deviceGuard.runFullCheck()
        if (guardReport!!.warnings.isNotEmpty()) {
            Logger.w("DeviceGuard found ${guardReport!!.warnings.size} warnings: ${guardReport!!.warnings}")
        }
        sensorSimulator.start(3f)
        Logger.i("AntiBanManager ready")
    }

    fun canOperate(action: String? = null): Boolean {
        return riskSentinel.canOperate(action)
    }

    /** AB-06：level<3 才允许批量任务入队/执行（与 NurtureScheduler.pause 协同） */
    fun canBatch(): Boolean = riskSentinel.currentLevel() < 3

    fun riskStatus(): Map<String, Any?> = riskSentinel.getStatus()

    fun statusSummary(): Map<String, Any?> = mapOf(
        "risk_sentinel" to riskSentinel.getStatus(),
        "nurture" to nurtureScheduler.getStatus(),
        "device_guard" to (guardReport?.info ?: emptyMap()),
        "sensor_simulator" to true,
        "touch_hardener" to true,
    )

    fun stop() {
        sensorSimulator.stop()
    }
}
