package com.system.cloudservice.antiban

import com.system.cloudservice.util.Logger
import com.system.cloudservice.util.ShellExecutor
import kotlinx.coroutines.*
import kotlin.math.sin
import kotlin.random.Random

class SensorSimulator(
    private val scope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()),
) {
    private var job: Job? = null
    private var running = false

    fun start(intervalSec: Float = 3f) {
        if (!ShellExecutor.hasRoot()) {
            Logger.w("SensorSimulator: requires root, skipped")
            return
        }
        running = true
        job = scope.launch {
            Logger.i("SensorSimulator started (interval=${intervalSec}s)")
            var tick = 0
            while (isActive && running) {
                delay((intervalSec * 1000).toLong())
                tick++
                try {
                    simulateAccelerometer(tick)
                    if (tick % 5 == 0) simulateGyroscope(tick)
                } catch (e: Exception) {
                    Logger.d("SensorSimulator tick error: ${e.message}")
                }
            }
        }
    }

    fun stop() {
        running = false
        job?.cancel()
        Logger.i("SensorSimulator stopped")
    }

    private fun simulateAccelerometer(tick: Int) {
        val x = Random.nextFloat() * 0.3f - 0.15f
        val y = Random.nextFloat() * 0.3f - 0.15f
        val z = 9.81f + Random.nextFloat() * 0.2f - 0.1f + 0.05f * sin(tick * 0.1f).toFloat()
        ShellExecutor.execute("su -c 'echo $x $y $z > /dev/input/accel_inject 2>/dev/null'", 2)
    }

    private fun simulateGyroscope(tick: Int) {
        val rx = Random.nextFloat() * 0.01f - 0.005f
        val ry = Random.nextFloat() * 0.01f - 0.005f
        val rz = Random.nextFloat() * 0.01f - 0.005f
        ShellExecutor.execute("su -c 'echo $rx $ry $rz > /dev/input/gyro_inject 2>/dev/null'", 2)
    }
}
