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.withContext

class LegionTool : BaseTool() {
    override val metadata = ToolMetadata(
        name = "legion_termux",
        displayName = "Legion",
        description = "Automated network discovery and multi-protocol attack framework. Runs service enumeration (nmap, hydra, nikto, etc.) automatically against a target. Requires Termux + Python3 + Legion cloned to ~/legion.",
        category = ToolCategory.NETWORK_SCANNING,
        requiresRoot = true,
        parameters = listOf(
            ToolParam("target", ParamType.STRING, "Target IP, CIDR range, or hostname"),
            ToolParam("profile", ParamType.ENUM, "Scan aggressiveness", required = false, defaultValue = "EASY", enumValues = listOf("EASY", "HARD", "INSANE")),
            ToolParam("threads", ParamType.INT, "Concurrent threads", required = false, defaultValue = "5")
        ),
        chainSuggestions = listOf("nmap", "port_scanner", "ssh_audit"),
    )

    override suspend fun execute(params: Map<String, Any>, emit: suspend (ToolEvent) -> Unit) {
        val target = paramRequired(params, "target")
        val profile = param(params, "profile") ?: "EASY"
        val threads = paramInt(params, "threads", 5)

        emit(ToolEvent.Log("[Legion] Starting $profile scan against $target with $threads threads..."))
        emit(ToolEvent.Log("[Legion] Chain tip: Use nmap first to identify open ports, then feed results into Legion for deep enumeration."))

        withContext(Dispatchers.IO) {
            try {
                val args = listOf("/data/data/com.termux/files/home/legion/legion.py", "--target", target, "--profile", profile, "--threads", threads.toString())
                shellExecutor?.executeTermuxAsRoot("python3", args, "python3", emit)
            } catch (e: Exception) {
                emit(ToolEvent.Error("Legion failed. Ensure Python3 is installed in Termux and Legion is cloned to ~/legion.", e))
            }
        }
        emit(ToolEvent.ChainSuggestion("nmap_termux", mapOf("target" to target)))
        emit(ToolEvent.Done)
    }
}
