package com.system.cloudservice.antiban

import android.accessibilityservice.GestureDescription
import android.graphics.Path
import com.system.cloudservice.service.AgentAccessibilityService
import com.system.cloudservice.util.Logger
import kotlin.math.cos
import kotlin.math.sin
import kotlin.random.Random

class TouchHardener {

    fun humanizedClick(x: Int, y: Int): Boolean {
        val a11y = AgentAccessibilityService.getInstance() ?: return false
        val (hx, hy) = addJitter(x.toFloat(), y.toFloat())
        val duration = Random.nextLong(80, 150)
        val path = Path().apply { moveTo(hx, hy) }
        val gesture = GestureDescription.Builder()
            .addStroke(GestureDescription.StrokeDescription(path, Random.nextLong(0, 30), duration))
            .build()
        a11y.dispatchGesture(gesture, null, null)
        return true
    }

    fun humanizedSwipe(x1: Int, y1: Int, x2: Int, y2: Int, baseDurationMs: Long = 300): Boolean {
        val a11y = AgentAccessibilityService.getInstance() ?: return false
        val path = buildBezierPath(
            addJitter(x1.toFloat(), y1.toFloat()),
            addJitter(x2.toFloat(), y2.toFloat()),
        )
        val duration = baseDurationMs + Random.nextLong(-50, 80)
        val gesture = GestureDescription.Builder()
            .addStroke(GestureDescription.StrokeDescription(path, Random.nextLong(0, 20), duration.coerceAtLeast(100)))
            .build()
        a11y.dispatchGesture(gesture, null, null)
        return true
    }

    private fun buildBezierPath(start: Pair<Float, Float>, end: Pair<Float, Float>): Path {
        val (sx, sy) = start
        val (ex, ey) = end
        val midX = (sx + ex) / 2 + Random.nextFloat() * 40 - 20
        val midY = (sy + ey) / 2 + Random.nextFloat() * 40 - 20
        return Path().apply {
            moveTo(sx, sy)
            quadTo(midX, midY, ex, ey)
        }
    }

    private fun addJitter(x: Float, y: Float): Pair<Float, Float> {
        val radius = Random.nextFloat() * 8
        val angle = Random.nextFloat() * 2 * Math.PI.toFloat()
        return Pair(
            x + radius * cos(angle),
            y + radius * sin(angle),
        )
    }
}
