package com.optix.android.tools.exploit

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 HydraTool : BaseTool() {
    override val metadata = ToolMetadata(
        name = "hydra_termux",
        displayName = "Hydra (Termux)",
        description = "Fast network logon cracker. (Requires Termux — root optional)",
        category = ToolCategory.EXPLOITATION,
        requiresRoot = false,
        requiredPackages = listOf("hydra"),
        parameters = listOf(
            ToolParam("target", ParamType.STRING, "Target IP or hostname"),
            ToolParam("service", ParamType.STRING, "Protocol (ssh, ftp, smb, etc)"),
            ToolParam("username", ParamType.STRING, "Username (or file path)", required = false, defaultValue = "admin"),
            ToolParam("password", ParamType.STRING, "Password (or wordlist path)", required = false, defaultValue = "password"),
            ToolParam("threads", ParamType.INT, "Number of concurrent tasks", required = false, defaultValue = "4")
        ),
        chainSuggestions = listOf("port_scanner", "nmap_termux", "brute_force"),
    )

    override suspend fun execute(params: Map<String, Any>, emit: suspend (ToolEvent) -> Unit) {
        val target = paramRequired(params, "target")
        val service = paramRequired(params, "service")
        val username = param(params, "username") ?: "admin"
        val password = param(params, "password") ?: "password"
        val threads = paramInt(params, "threads", 4)

        emit(ToolEvent.Log("Forwarding Hydra brute-force request to Termux on $target:$service..."))

        withContext(Dispatchers.IO) {
            try {
                val uFlag = if (username.startsWith("/")) "-L" else "-l"
                val pFlag = if (password.startsWith("/")) "-P" else "-p"

                val args = listOf("-t", threads.toString(), uFlag, username, pFlag, password, target, service)
                shellExecutor?.executeTermuxAsRoot("hydra", args, "hydra", emit)
            } catch (e: Exception) {
                emit(ToolEvent.Error("Hydra execution failed: ${e.message}"))
            }
        }
        emit(ToolEvent.ChainSuggestion("brute_force", mapOf("target" to target, "protocol" to service)))
        emit(ToolEvent.Done)
    }
}
