package com.optix.android.tools.network

import com.optix.android.domain.model.ParamType
import com.optix.android.domain.model.ToolCategory
import com.optix.android.domain.model.ToolEvent
import com.optix.android.domain.model.ToolMetadata
import com.optix.android.domain.model.ToolParam
import com.optix.android.tools.registry.BaseTool
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext

class Rping3Tool : BaseTool() {
    override val metadata = ToolMetadata(
        name = "rping3_termux",
        displayName = "Hping3 / RPing3 (Termux)",
        description = "Advanced packet forging and TCP ping sweep. (Requires Termux/root)",
        category = ToolCategory.NETWORK_SCANNING,
        requiresRoot = true,
        requiredPackages = listOf("hping3"),
        parameters = listOf(
            ToolParam("target", ParamType.STRING, "Target IP or hostname"),
            ToolParam("port", ParamType.INT, "Target port", required = false, defaultValue = "80"),
            ToolParam("count", ParamType.INT, "Packet count", required = false, defaultValue = "4"),
            ToolParam("flags", ParamType.STRING, "TCP Flags (e.g. -S for SYN)", required = false, defaultValue = "-S")
        ),
    )

    override suspend fun execute(params: Map<String, Any>, emit: suspend (ToolEvent) -> Unit) {
        val target = paramRequired(params, "target")
        val port = paramInt(params, "port", 80)
        val count = paramInt(params, "count", 4)
        val flags = param(params, "flags") ?: "-S"

        emit(ToolEvent.Log("Requesting hping3 execution via Termux on $target backdoor..."))

        withContext(Dispatchers.IO) {
            try {
                val args = mutableListOf(*flags.split("\\s+".toRegex()).toTypedArray(), "-p", port.toString(), "-c", count.toString(), target)
                shellExecutor?.executeTermuxAsRoot("hping3", args, "root-repo && pkg install hping3", emit)
            } catch (e: Exception) {
                emit(ToolEvent.Error("Termux execution failed. Ensure hping3 is installed via Termux.", e))
            }
        }
        emit(ToolEvent.ChainSuggestion("port_scanner", mapOf("target" to target)))
        emit(ToolEvent.Done)
    }
}
