package com.optix.android.ai

import com.optix.android.tools.registry.ToolRegistry
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Response template engine for generating conversational responses.
 * 
 * Handles:
 * - Tool preamble messages (what the tool is doing)
 * - Contextual follow-up suggestions
 * - Educational responses
 * - Generic fallback responses
 * - Greeting messages
 * 
 * @property toolRegistry Registry for querying available tools
 */
@Singleton
class ResponseTemplates @Inject constructor(
    private val toolRegistry: ToolRegistry,
) {

    /**
     * Generates a preamble message for a tool invocation.
     * 
     * @param toolName Name of the tool being invoked
     * @param params Parameter map for the tool
     * @param patternIndex Index of the pattern that triggered the tool
     * @return User-friendly explanation of what the tool will do
     */
    fun getToolPreamble(toolName: String, params: Map<String, Any>, patternIndex: Int): String {
        return when (patternIndex) {
            // Network Scanning
            0 -> "running a network scan on ${params["target"]} — this pings hosts and checks for open ports. give it a sec..."
            1, 2 -> "port scanning ${params["target"]} — checking ports 1–9999 for open services. each open port = a running service you can investigate."
            3 -> {
                val subnet = params["subnet"]
                "sweeping the LAN ($subnet) — pinging every host in the subnet to find active devices. results show up as nodes on the globe."
            }
            4 -> "NetBIOS query on ${params["target"]} — this looks for Windows file sharing names and workgroup info on port 137/139."
            5 -> "scanning nearby WiFi networks — shows SSIDs, signal strength, encryption type, and channel. useful for spotting rogue APs."
            6 -> "tracing route to ${params["target"]} — maps every router hop between you and the target. great for diagnosing latency or finding network paths."
            7 -> "firing Nmap at ${params["target"]} — the gold standard for network scanning. detects OS, service versions, and runs scripts. needs Termux."
            8 -> "running ARP scan — sends ARP requests to every IP in your subnet. faster than ping, works even when ICMP is blocked. shows MAC addresses too."
            9 -> "auditing SSH on ${params["target"]} — checks supported algorithms, key exchange methods, and known vulnerabilities in the SSH config."
            10 -> "launching Masscan on ${params["target"]} — fastest port scanner alive, can scan the entire internet in 6 minutes. needs Termux + root."
            11 -> "rping3 to ${params["target"]} — raw ping with detailed RTT stats."
            12 -> "starting packet sniffer — captures raw network traffic on your interface. needs root. use responsibly."
            13 -> "mapping network topology — runs traceroutes + ASN lookups to build a visual map of your network path."
            14 -> "launching Legion on ${params["target"]} — automated multi-service scanner. runs nmap + service-specific scripts. needs Termux."

            // DNS & Web
            15 -> "DNS recon on ${params["domain"]} — queries A, AAAA, MX, NS, TXT, CNAME records. good first step for any web target."
            16 -> "enumerating subdomains for ${params["domain"]} — brute-forces common subdomain names. finds hidden admin panels, dev servers, staging environments."
            17 -> "inspecting ${params["url"]} — checks response headers, server info, cookies, redirects, and security misconfigs."
            18 -> "directory fuzzing ${params["url"]} — tries common paths like /admin, /backup, /.git to find hidden endpoints."
            19 -> "testing for SQL injection on ${params["url"]} — injects payloads into URL params to check if the DB is exposed."
            20 -> "checking for XSS on ${params["url"]} — injects script tags into inputs to see if they reflect back unescaped."
            21 -> "checking CORS policy on ${params["url"]} — misconfigured CORS lets evil.com read your private API responses."
            22 -> "checking security headers on ${params["url"]} — looks for CSP, HSTS, X-Frame-Options, etc. missing headers = easy wins for attackers."
            23 -> "analyzing JWT — decoding header + payload, checking algorithm (watch out for 'none' or RS256→HS256 confusion attacks)."
            24 -> "running Nikto on ${params["target"]} — web server scanner that checks for 6700+ known vulnerabilities, misconfigs, and outdated software. needs Termux."
            25 -> "launching SQLmap on ${params["url"]} — automated SQL injection tool. finds and exploits DB vulnerabilities. needs Termux."

            // OSINT
            26 -> "searching Shodan for '${params["query"]}' — finds internet-connected devices, open ports, services, and vulnerabilities exposed to the web."
            27 -> "looking up IP ${params["ip"]} on Shodan — shows open ports, banner data, geolocation, ISP, and known vulnerabilities for that host."
            28 -> "running theHarvester on ${params["domain"]} — gathers emails, subdomains, hosts, and open ports from public sources (search engines, PGP keys, SHODAN)."
            29 -> "checking ${params["email"]} against Have I Been Pwned — looks for known data breaches where this email appeared."
            30 -> "verifying ${params["domain"]} with Hunter.io — finds email addresses, patterns, and deliverability status for the domain."

            // Exploit / Attack
            31 -> "launching ${params["protocol"]} brute force on ${params["target"]} — tries username/password combos from a wordlist. slow but effective against weak creds."
            32 -> "firing Hydra at ${params["target"]} via ${params["service"]} — fastest network login cracker. supports 50+ protocols. needs Termux."
            33 -> "generating ${params["type"]} payload for ${params["lhost"]}:${params["lport"]} — creates shellcode that connects back to your listener."
            34 -> "generating ${params["language"]} reverse shell — one-liner that makes the target connect back to ${params["host"]}:${params["port"]}. set up a listener first with: nc -lvnp ${params["port"]}"

            // LPE & Lateral Movement
            35 -> "running LinPEAS — Linux local enumeration script. checks for kernel exploits, sudo permissions, capabilities, cron jobs, SUID binaries, and misconfigs."
            36 -> "running WinPEAS on ${params["target"]} — Windows local enumeration. checks for AV, AMSI, UAC, stored creds, services, registry, and privilege escalation paths."
            37 -> "launching BloodHound — Active Directory attack path analysis. maps domain trusts, group memberships, and finds shortest paths to DA (Domain Admin)."
            38 -> if (params.containsKey("target")) {
                "running CrackMapExec on ${params["target"]} — automates network enumeration and post-exploitation across SMB, WinRM, SSH, RDP, and more."
            } else {
                "running CrackMapExec — specify a target like 'cme 192.168.1.10' to start."
            }

            // Cloud Security
            39 -> "scanning AWS infrastructure — checking EC2 instances, S3 buckets, IAM policies, and security groups for misconfigurations. requires AWS CLI + credentials."
            40 -> "scanning GCP assets — enumerating Compute Engine, Cloud Storage, IAM, and firewall rules for security issues. requires gcloud CLI + credentials."
            41 -> "scanning Azure AD and resources — checking AD users, VMs, Storage Accounts, and NSG rules for vulnerabilities. requires Azure CLI + credentials."

            // Utility
            42 -> "cracking hash — trying rainbow tables and common wordlists. MD5/SHA1 crack fast; bcrypt/argon2 are much harder."
            43 -> "generating a cryptographically strong password — 20+ chars, mixed case, numbers, symbols. save it in a password manager!"
            44, 45 -> "encoding with ${params["mode"]}..."
            46 -> "calculating subnet for ${params["cidr"]} — shows network address, broadcast, usable host range, and total hosts."
            47 -> "hashing '${params["input"]}' — generating MD5, SHA1, SHA256, SHA512 all at once."
            48, 49 -> "applying ${params.getOrDefault("mode", "ROT13")} cipher..."
            50 -> "testing regex pattern against input..."

            else -> "running $toolName..."
        }
    }
}

