package com.optix.android.ai

import com.optix.android.tools.registry.ToolRegistry
import com.optix.android.util.NetworkUtils
import dagger.Lazy
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Response from MockBrain — either plain text or a tool invocation.
 * When [toolCall] is non-null, OfflineProvider emits a ProviderEvent.ToolCall
 * so AiBridge actually runs the tool. [text] becomes the preamble message.
 *
 * When [chain] is non-null, OfflineProvider emits a ProviderEvent.ToolChain so the
 * UI can forward a multi-step sequence to the NETWORK tab. [chain] is raw text
 * containing a JSON or structured chain definition.
 */
data class MockBrainResponse(
    val text: String,
    val toolCall: Pair<String, Map<String, Any>>? = null,
    val chain: String? = null,
)

/**
 * Offline fallback AI — casual chatbot + real tool-calling engine.
 * Parses user intent via regex, selects the right tool from the 68-tool registry,
 * and returns structured responses that OfflineProvider converts to ProviderEvents.
 */
@Singleton
class MockBrain @Inject constructor(
    private val networkUtils: NetworkUtils,
    private val toolRegistry: Lazy<ToolRegistry>,
) {

    private fun localSubnet(): String =
        networkUtils.getLocalNetworkState().subnet ?: "192.168.1"

    /**
     * Validates that all tool names referenced in [toolDispatch] exist in the registry.
     * Logs a warning for any mismatches so they're caught at startup rather than silently
     * failing at runtime when a user triggers a tool call.
     */
    fun validateToolNames() {
        val registeredNames = toolRegistry.get().listNames().toSet()
        val referencedNames = toolDispatch.mapNotNull { (_, handler) ->
            // Extract tool name from a dummy match to check the mapping
            null // We validate via the companion constant list below
        }
        DISPATCH_TOOL_NAMES.forEach { name ->
            if (name !in registeredNames) {
                Timber.w("MockBrain: tool '$name' referenced in dispatch but not found in ToolRegistry")
            }
        }
    }

    // Last tool context — used to generate contextual follow-up suggestions
    private var lastToolName: String? = null
    private var lastToolResult: String? = null

    fun recordToolResult(toolName: String, result: String) {
        lastToolName = toolName
        lastToolResult = result
    }

    fun respond(input: String): MockBrainResponse {
        val trimmed = input.trim()
        if (trimmed.isBlank()) return MockBrainResponse(randomGreeting())

        val lower = trimmed.lowercase()

        // 1. Exact commands
        exactCommands[lower]?.let { return it() }

        // 2. Tool-calling dispatch (returns toolCall + preamble)
        for ((pattern, handler) in toolDispatch) {
            val match = pattern.find(lower)
            if (match != null) {
                val response = handler(match, trimmed)
                // Clear last context when starting a new tool
                lastToolName = response.toolCall?.first
                return response
            }
        }

        // 3. Natural language → tool inference
        for ((pattern, handler) in nlToolPatterns) {
            val match = pattern.find(lower)
            if (match != null) {
                val response = handler(match, trimmed)
                lastToolName = response.toolCall?.first
                return response
            }
        }

        // 4. Contextual follow-up — "yes", "sure", affirmative after a tool result
        val isAffirmative = Regex("""^(yes|yeah|yep|sure|ok|okay|do it|go ahead|scan|check|test|run it|port scan|portscan)""").containsMatchIn(lower)
        if (isAffirmative) {
            val followUp = contextualFollowUp(lower)
            if (followUp != null) return followUp
        }

        // 5. Conversational patterns (text-only)
        for ((pattern, response) in chatPatterns) {
            if (pattern.containsMatchIn(lower)) return MockBrainResponse(response(trimmed))
        }

        return MockBrainResponse(genericResponse(trimmed))
    }

    private fun contextualFollowUp(lower: String): MockBrainResponse? {
        val subnet = localSubnet()
        return when (lastToolName) {
            "lan_scanner" -> {
                // After LAN scan — offer port scan
                val target = Regex("""([\d.]+)""").find(lower)?.value
                if (target != null) {
                    MockBrainResponse("port scanning $target — checking ports 1–9999 for open services.",
                        "port_scanner" to mapOf("target" to target, "start_port" to "1", "end_port" to "9999"))
                } else {
                    MockBrainResponse("sure! which IP do you want to port scan? type: port scan <ip>")
                }
            }
            "port_scanner", "nmap_termux" -> {
                // After port scan — suggest vuln testing based on what was found
                val result = lastToolResult ?: ""
                val openPorts = Regex("""(\d+)/tcp\s+open""").findAll(result).map { it.groupValues[1].toInt() }.toList()
                    .ifEmpty { Regex("""port (\d+)""").findAll(result).map { it.groupValues[1].toInt() }.toList() }
                suggestVulnTools(openPorts, lower)
            }
            "ssh_audit" -> MockBrainResponse("want me to try brute-forcing SSH credentials? type: hydra <ip> ssh\n\n⚠ only on systems you own.")
            "http_inspector", "security_headers" -> MockBrainResponse("want me to check for web vulnerabilities? options:\n• 'sqli <url>' — SQL injection\n• 'xss <url>' — Cross-site scripting\n• 'nuclei <url>' — automated vulnerability scanner\n• 'fuzz <url>' — Hidden directories")
            "wifi_scanner" -> MockBrainResponse("want me to scan devices on your network? type: lan scan")
            "shodan_search" -> MockBrainResponse("shodan search complete. next steps:\n• 'subdomain <domain>' — enumerate subdomains\n• 'http <ip>' — inspect web services on discovered IPs")
            "theharvester" -> MockBrainResponse("harvester complete. next steps:\n• 'hibp <email>' — check discovered emails against breach databases")
            else -> null
        }
    }

    private fun suggestVulnTools(openPorts: List<Int>, lower: String): MockBrainResponse {
        val suggestions = mutableListOf<String>()
        val target = Regex("""([\d.]+)""").find(lower)?.value ?: lastToolResult?.let {
            Regex("""Scanning ([\d.]+)""").find(it)?.groupValues?.get(1)
        } ?: ""

        if (openPorts.any { it in listOf(80, 443, 8080, 8443) }) {
            suggestions += "• 'http http://$target' — inspect the web server"
            suggestions += "• 'nikto $target' — full web vulnerability scan"
            suggestions += "• 'fuzz http://$target' — find hidden directories"
        }
        if (openPorts.any { it == 22 }) suggestions += "• 'ssh audit $target' — check SSH config weaknesses"
        if (openPorts.any { it in listOf(445, 139) }) {
            suggestions += "• 'netbios $target' — enumerate Windows shares"
            suggestions += "• 'enum4linux $target' — full SMB enumeration"
        }
        if (openPorts.any { it in listOf(3306, 5432, 27017, 6379) }) suggestions += "• 'nmap $target' — detect DB version + known CVEs"
        if (openPorts.any { it == 21 }) suggestions += "• 'hydra $target ftp' — test FTP credentials"
        if (openPorts.any { it == 3389 }) suggestions += "• 'hydra $target rdp' — test RDP credentials"
        if (openPorts.any { it == 161 }) suggestions += "• 'snmpwalk $target' — SNMP enumeration"

        val result = lastToolResult ?: ""
        if (Regex("""linux|ubuntu|debian|centos|redhat|fedora|arch|kali|parrot""", RegexOption.IGNORE_CASE).containsMatchIn(result)) {
            suggestions += "• 'linpeas' — Linux privilege escalation enumeration"
        }
        if (Regex("""windows|microsoft|win7|win10|win11|server 20""", RegexOption.IGNORE_CASE).containsMatchIn(result)) {
            suggestions += "• 'winpeas $target' — Windows privilege escalation enumeration"
        }

        return if (suggestions.isEmpty()) {
            MockBrainResponse("scan complete. no well-known service ports found. try 'nmap $target' with -sV for deeper service detection.")
        } else {
            MockBrainResponse("found ${openPorts.size} open port(s). here's what i'd check next:\n\n${suggestions.joinToString("\n")}\n\nwhich would you like to run?")
        }
    }

    // ------------------------------------------------------------------
    // Exact commands
    // ------------------------------------------------------------------
    private val exactCommands: Map<String, () -> MockBrainResponse> = mapOf(
        "help"    to { MockBrainResponse(HELP_TEXT) },
        "tools"   to { MockBrainResponse(TOOLS_LIST) },
        "aliases" to { MockBrainResponse(ALIASES_TEXT) },
        "status"    to { MockBrainResponse("all systems go — ${toolRegistry.get().listNames().size} tools loaded and ready. hook up an API key in Settings for the full AI brain experience.") },
        "clear"   to { MockBrainResponse("conversation cleared! what's next?") },
        "hey"     to { MockBrainResponse(randomGreeting()) },
        "hi"      to { MockBrainResponse(randomGreeting()) },
        "hello"   to { MockBrainResponse(randomGreeting()) },
        "yo"      to { MockBrainResponse(randomGreeting()) },
        "sup"     to { MockBrainResponse(randomGreeting()) },
        "what's up" to { MockBrainResponse(randomGreeting()) },
        "good morning" to { MockBrainResponse("morning! ready to break some stuff? (legally, of course.)") },
        "good night"   to { MockBrainResponse("night! don't forget to patch your systems before you sleep. 😴") },
    )

    // ------------------------------------------------------------------
    // Tool-calling dispatch — actually runs tools
    // ------------------------------------------------------------------
    private val toolDispatch: List<Pair<Regex, (MatchResult, String) -> MockBrainResponse>> by lazy { listOf(
        // ── Network Scanning ──────────────────────────────────────────
        Regex("""^scan\s+([\d./]+)""")                     to { m, _ -> MockBrainResponse("running a network scan on ${m.gv(1)} — this pings hosts and checks for open ports. give it a sec...", "network_scanner" to mapOf("target" to m.gv(1))) },
        Regex("""^port ?scan\s+([\w.:]+)""")                to { m, _ -> MockBrainResponse("port scanning ${m.gv(1)} — checking ports 1–9999 for open services. each open port = a running service you can investigate.", "port_scanner" to mapOf("target" to m.gv(1))) },
        Regex("""^ps\s+([\w.:]+)""")                        to { m, _ -> MockBrainResponse("quick port scan on ${m.gv(1)}...", "port_scanner" to mapOf("target" to m.gv(1))) },
        Regex("""^lan ?scan\s*([\d./]*)""")                 to { m, _ -> val s = m.gv(1).ifEmpty { localSubnet() }; MockBrainResponse("sweeping the LAN ($s) — pinging every host in the subnet to find active devices. results show up as nodes on the globe.", "lan_scanner" to mapOf("subnet" to s)) },
        Regex("""^netbios\s+([\d./]+)""")                   to { m, _ -> MockBrainResponse("NetBIOS query on ${m.gv(1)} — this looks for Windows file sharing names and workgroup info on port 137/139.", "netbios_scanner" to mapOf("target" to m.gv(1))) },
        Regex("""^wifi ?scan""")                            to { _, _ -> MockBrainResponse("scanning nearby WiFi networks — shows SSIDs, signal strength, encryption type, and channel. useful for spotting rogue APs.", "wifi_scanner" to emptyMap()) },
        Regex("""^traceroute\s+([\w.-]+)""")                to { m, _ -> MockBrainResponse("tracing route to ${m.gv(1)} — maps every router hop between you and the target. great for diagnosing latency or finding network paths.", "traceroute" to mapOf("target" to m.gv(1))) },
        Regex("""^nmap\s+([\w./:-]+)""")                    to { m, _ -> MockBrainResponse("firing Nmap at ${m.gv(1)} — the gold standard for network scanning. detects OS, service versions, and runs scripts. needs Termux.", "nmap_termux" to mapOf("target" to m.gv(1))) },
        Regex("""^arp ?scan""")                             to { _, _ -> MockBrainResponse("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.", "arp_scan" to emptyMap()) },
        Regex("""^ssh ?audit\s+([\w.-]+)""")                to { m, _ -> MockBrainResponse("auditing SSH on ${m.gv(1)} — checks supported algorithms, key exchange methods, and known vulnerabilities in the SSH config.", "ssh_audit" to mapOf("target" to m.gv(1))) },
        Regex("""^masscan\s+([\w./:-]+)""")                 to { m, _ -> MockBrainResponse("launching Masscan on ${m.gv(1)} — fastest port scanner alive, can scan the entire internet in 6 minutes. needs Termux + root.", "masscan_termux" to mapOf("target" to m.gv(1))) },
        Regex("""^rping\s+([\w.-]+)""")                     to { m, _ -> MockBrainResponse("rping3 to ${m.gv(1)} — raw ping with detailed RTT stats.", "rping3_termux" to mapOf("target" to m.gv(1))) },
        Regex("""^sniff""")                                  to { _, _ -> MockBrainResponse("starting packet sniffer — captures raw network traffic on your interface. needs root. use responsibly.", "packet_sniffer" to emptyMap()) },
        Regex("""^topology""")                               to { _, _ -> MockBrainResponse("mapping network topology — runs traceroutes + ASN lookups to build a visual map of your network path.", "network_topology" to emptyMap()) },
        Regex("""^legion\s+([\w.-]+)""")                    to { m, _ -> MockBrainResponse("launching Legion on ${m.gv(1)} — automated multi-service scanner. runs nmap + service-specific scripts. needs Termux.", "legion_termux" to mapOf("target" to m.gv(1))) },

        // ── DNS & Web ─────────────────────────────────────────────────
        Regex("""^dns\s+([\w.-]+)""")                       to { m, _ -> MockBrainResponse("DNS recon on ${m.gv(1)} — queries A, AAAA, MX, NS, TXT, CNAME records. good first step for any web target.", "dns_recon" to mapOf("domain" to m.gv(1))) },
        Regex("""^subdomain\s+([\w.-]+)""")                 to { m, _ -> MockBrainResponse("enumerating subdomains for ${m.gv(1)} — brute-forces common subdomain names. finds hidden admin panels, dev servers, staging environments.", "subdomain_enum" to mapOf("domain" to m.gv(1))) },
        Regex("""^http\s+(https?://[\w./:?=&-]+)""")        to { m, _ -> MockBrainResponse("inspecting ${m.gv(1)} — checks response headers, server info, cookies, redirects, and security misconfigs.", "http_inspector" to mapOf("url" to m.gv(1))) },
        Regex("""^fuzz\s+(https?://[\w./:?=&-]+)""")        to { m, _ -> MockBrainResponse("directory fuzzing ${m.gv(1)} — tries common paths like /admin, /backup, /.git to find hidden endpoints.", "directory_fuzzer" to mapOf("url" to m.gv(1))) },
        Regex("""^sqli\s+(https?://[\w./?=&-]+)""")         to { m, _ -> MockBrainResponse("testing for SQL injection on ${m.gv(1)} — injects payloads into URL params to check if the DB is exposed.", "sqli_tester" to mapOf("url" to m.gv(1))) },
        Regex("""^xss\s+(https?://[\w./?=&-]+)""")          to { m, _ -> MockBrainResponse("checking for XSS on ${m.gv(1)} — injects script tags into inputs to see if they reflect back unescaped.", "xss_scanner" to mapOf("url" to m.gv(1))) },
        Regex("""^cors\s+(https?://[\w./:?=&-]+)""")        to { m, _ -> MockBrainResponse("checking CORS policy on ${m.gv(1)} — misconfigured CORS lets evil.com read your private API responses.", "cors_checker" to mapOf("url" to m.gv(1))) },
        Regex("""^headers?\s+(https?://[\w./:?=&-]+)""")    to { m, _ -> MockBrainResponse("checking security headers on ${m.gv(1)} — looks for CSP, HSTS, X-Frame-Options, etc. missing headers = easy wins for attackers.", "security_headers" to mapOf("url" to m.gv(1))) },
        Regex("""^jwt\s+(\S+)""")                           to { m, _ -> MockBrainResponse("analyzing JWT — decoding header + payload, checking algorithm (watch out for 'none' or RS256→HS256 confusion attacks).", "jwt_analyzer" to mapOf("token" to m.gv(1))) },
        Regex("""^nikto\s+([\w.-]+)""")                     to { m, _ -> MockBrainResponse("running Nikto on ${m.gv(1)} — web server scanner that checks for 6700+ known vulnerabilities, misconfigs, and outdated software. needs Termux.", "nikto_termux" to mapOf("target" to m.gv(1))) },
        Regex("""^sqlmap\s+(https?://[\w./?=&-]+)""")       to { m, _ -> MockBrainResponse("launching SQLmap on ${m.gv(1)} — automated SQL injection tool. finds and exploits DB vulnerabilities. needs Termux.", "sqlmap_termux" to mapOf("url" to m.gv(1))) },
        Regex("""^nuclei\s+(https?://[\w./:?=&-]+)""")      to { m, _ -> MockBrainResponse("running Nuclei on ${m.gv(1)} — template-based vulnerability scanner for known CVEs and misconfigs. needs Termux.", "nuclei_termux" to mapOf("url" to m.gv(1))) },

        // ── OSINT ─────────────────────────────────────────────────────
        Regex("""^shodan\s+(.+)""")                          to { m, _ -> MockBrainResponse("searching Shodan for '${m.gv(1)}' — finds internet-connected devices, open ports, services, and vulnerabilities exposed to the web.", "shodan_search" to mapOf("query" to m.gv(1))) },
        Regex("""^shodan\s+ip\s+([\w.]+)""")                to { m, _ -> MockBrainResponse("looking up IP ${m.gv(1)} on Shodan — shows open ports, banner data, geolocation, ISP, and known vulnerabilities for that host.", "shodan_host" to mapOf("ip" to m.gv(1))) },
        Regex("""^harvest\s+([\w.-]+)""")                   to { m, _ -> MockBrainResponse("running theHarvester on ${m.gv(1)} — gathers emails, subdomains, hosts, and open ports from public sources (search engines, PGP keys, SHODAN).", "theharvester" to mapOf("domain" to m.gv(1))) },
        Regex("""^hibp\s+(\S+@\S+)""")                      to { m, _ -> MockBrainResponse("checking ${m.gv(1)} against Have I Been Pwned — looks for known data breaches where this email appeared.", "hibp_check" to mapOf("email" to m.gv(1))) },
        Regex("""^hunter\s+([\w.-]+)""")                    to { m, _ -> MockBrainResponse("verifying ${m.gv(1)} with Hunter.io — finds email addresses, patterns, and deliverability status for the domain.", "hunter_verify" to mapOf("domain" to m.gv(1))) },

        // ── Exploit / Attack ──────────────────────────────────────────
        Regex("""^brute\s+(ssh|ftp|http)\s+([\w./:]+)""")   to { m, _ -> MockBrainResponse("launching ${m.gv(1)} brute force on ${m.gv(2)} — tries username/password combos from a wordlist. slow but effective against weak creds.", "brute_force" to mapOf("protocol" to m.gv(1), "target" to m.gv(2))) },
        Regex("""^hydra\s+([\w.]+)\s+(\w+)""")              to { m, _ -> MockBrainResponse("firing Hydra at ${m.gv(1)} via ${m.gv(2)} — fastest network login cracker. supports 50+ protocols. needs Termux.", "hydra_termux" to mapOf("target" to m.gv(1), "service" to m.gv(2))) },
        Regex("""^payload\s+(\w+)\s+([\d.]+)\s+(\d+)""")    to { m, _ -> MockBrainResponse("generating ${m.gv(1)} payload for ${m.gv(2)}:${m.gv(3)} — creates shellcode that connects back to your listener.", "payload_generator" to mapOf("type" to m.gv(1), "lhost" to m.gv(2), "lport" to m.gv(3))) },
        Regex("""^reverse ?shell\s+(\w+)\s+([\d.]+)\s+(\d+)""") to { m, _ -> MockBrainResponse("generating ${m.gv(1)} reverse shell — one-liner that makes the target connect back to ${m.gv(2)}:${m.gv(3)}. set up a listener first with: nc -lvnp ${m.gv(3)}", "reverse_shell_gen" to mapOf("language" to m.gv(1), "host" to m.gv(2), "port" to m.gv(3))) },

        // ── LPE & Lateral Movement ─────────────────────────────────────
        Regex("""^(linpeas|enumerate\s+lpe)""")             to { _, _ -> MockBrainResponse("running LinPEAS — Linux local enumeration script. checks for kernel exploits, sudo permissions, capabilities, cron jobs, SUID binaries, and misconfigs.", "linpeas_termux" to emptyMap()) },
        Regex("""^winpeas\s+([\w.]+)""")                    to { m, _ -> MockBrainResponse("running WinPEAS on ${m.gv(1)} — Windows local enumeration. checks for AV, AMSI, UAC, stored creds, services, registry, and privilege escalation paths.", "winpeas_termux" to mapOf("target" to m.gv(1))) },
        Regex("""^(bloodhound|attack\s+paths?)""")           to { _, _ -> MockBrainResponse("launching BloodHound — Active Directory attack path analysis. maps domain trusts, group memberships, and finds shortest paths to DA (Domain Admin).", "bloodhound_termux" to emptyMap()) },
        Regex("""^(cme\s+([\w.]+)|crackmapexec)""")         to { m, _ -> val t = m.gv(2); if (t.isNotEmpty()) MockBrainResponse("running CrackMapExec on $t — automates network enumeration and post-exploitation across SMB, WinRM, SSH, RDP, and more.", "cme_termux" to mapOf("target" to t)) else MockBrainResponse("running CrackMapExec — specify a target like 'cme 192.168.1.10' to start.", "cme_termux" to emptyMap()) },

        // ── Utility ───────────────────────────────────────────────────
        Regex("""^crack\s+([a-fA-F0-9]{32,128})""")         to { m, _ -> MockBrainResponse("cracking hash — trying rainbow tables and common wordlists. MD5/SHA1 crack fast; bcrypt/argon2 are much harder.", "hash_cracker" to mapOf("hash" to m.gv(1))) },
        Regex("""^password ?gen""")                          to { _, _ -> MockBrainResponse("generating a cryptographically strong password — 20+ chars, mixed case, numbers, symbols. save it in a password manager!", "password_generator" to emptyMap()) },
        Regex("""^encode\s+(\w+)\s+(.+)""")                 to { m, _ -> MockBrainResponse("encoding with ${m.gv(1)}...", "encoder_tool" to mapOf("mode" to m.gv(1), "input" to m.gv(2))) },
        Regex("""^decode\s+(\w+)\s+(.+)""")                 to { m, _ -> MockBrainResponse("decoding with ${m.gv(1)}...", "encoder_tool" to mapOf("mode" to m.gv(1), "input" to m.gv(2))) },
        Regex("""^subnet\s+([\d./]+)""")                    to { m, _ -> MockBrainResponse("calculating subnet for ${m.gv(1)} — shows network address, broadcast, usable host range, and total hosts.", "subnet_calculator" to mapOf("cidr" to m.gv(1))) },
        Regex("""^hash\s+(.+)""")                           to { m, _ -> MockBrainResponse("hashing '${m.gv(1)}' — generating MD5, SHA1, SHA256, SHA512 all at once.", "hash_generator" to mapOf("input" to m.gv(1))) },
        Regex("""^cipher\s+(\w+)\s+(.+)""")                 to { m, _ -> MockBrainResponse("applying ${m.gv(1)} cipher...", "cipher_tool" to mapOf("mode" to m.gv(1), "text" to m.gv(2))) },
        Regex("""^rot13\s+(.+)""")                          to { m, _ -> MockBrainResponse("ROT13: each letter shifts 13 places. classic CTF encoding — not encryption!", "cipher_tool" to mapOf("mode" to "rot13", "text" to m.gv(1))) },
        Regex("""^regex\s+(.+?)\s+(?:against|on|in)\s+(.+)""") to { m, _ -> MockBrainResponse("testing regex pattern against input...", "regex_tester" to mapOf("pattern" to m.gv(1), "text" to m.gv(2))) },
    ) }

    // ------------------------------------------------------------------
    // NL → tool inference (fuzzy natural language)
    // ------------------------------------------------------------------
    private val nlToolPatterns: List<Pair<Regex, (MatchResult, String) -> MockBrainResponse>> by lazy { listOf(
        // Network intent — single consolidated pattern for LAN/wifi scan
        Regex("""(scan|check|sweep|probe|who.s|what.s|show|list).*(my\s+)?(network|lan|wifi|subnet|local|devices|connected)""") to { _, _ -> MockBrainResponse("let me check who's on your network — sweeping ${localSubnet()} now. results will appear as nodes on the globe.\n\nonce the scan finishes, i can port scan any of the discovered hosts — just say 'yes' or give me an IP.", "lan_scanner" to mapOf("subnet" to localSubnet())) },
        Regex("""(scan|check)\s+(the\s+)?ports?\s+(on\s+)?([\w.:]+)""") to { m, _ -> MockBrainResponse("checking ports on ${m.gv(4)} — scanning 1–9999 for open services. each open port is a potential entry point.\n\nonce done, i'll suggest which vulnerabilities to test based on what's open.", "port_scanner" to mapOf("target" to m.gv(4), "start_port" to "1", "end_port" to "9999")) },
        Regex("""what.s? (ports?|services?)\s+(are\s+)?(open|running)\s+(on\s+)?([\w.:]+)""") to { m, _ -> MockBrainResponse("scanning ${m.gv(5)} for open ports — this tells you what services are running and potentially exposed.\n\nafter the scan i'll suggest next steps based on what's found.", "port_scanner" to mapOf("target" to m.gv(5), "start_port" to "1", "end_port" to "9999")) },
        Regex("""(trace|traceroute|trace route)\s+(to\s+)?([\w.-]+)""") to { m, _ -> MockBrainResponse("tracing route to ${m.gv(3)} — maps every router hop. useful for finding where latency is coming from.", "traceroute" to mapOf("target" to m.gv(3))) },
        Regex("""(nearby|available|around)\s+wifi""")       to { _, _ -> MockBrainResponse("scanning nearby WiFi — shows all SSIDs, signal strength, encryption type. good for spotting rogue access points.", "wifi_scanner" to emptyMap()) },

        // Utility intent
        Regex("""(generate|create|make|give me)\s+(a\s+)?(strong\s+|secure\s+|random\s+)?password""") to { _, _ -> MockBrainResponse("generating a strong password — 20+ chars, mixed case, numbers, symbols. save it in a password manager!", "password_generator" to emptyMap()) },
        Regex("""(generate|create|make)\s+(a\s+)?(hash|md5|sha)""") to { _, _ -> MockBrainResponse("what text should I hash? use: hash <text>") },

        // ── Multi-step attack / workflow chains ─────────────────────────
        // "full recon on <ip>" -> lan scan (if reachable) + port scan + nmap
        Regex("""(full\s+)?recon\s+(?:on|of|for|against)\s+([\w./:]+)""") to { m, _ ->
            val t = m.gv(2)
            val chain = """
                Here's a full recon workflow for **$t**:

                ```chain
                {
                  "name": "Full Recon: $t",
                  "steps": [
                    { "tool": "lan_scanner", "params": { "subnet": "${localSubnet()}" } },
                    { "tool": "port_scanner", "params": { "target": "$t", "start_port": "1", "end_port": "1024" } },
                    { "tool": "nmap_termux", "params": { "target": "$t" } }
                  ]
                }
                ```
            """.trimIndent()
            MockBrainResponse(chain, chain = chain)
        },
        // "attack chain for <ip>" -> port scan + ssh audit + (if ssh) hydra
        Regex("""(attack\s+chain|exploit\s+chain|full\s+attack|chain\s+for)\s+(?:on|of|for|against)?\s*([\w./:]+)?""") to { m, _ ->
            val t = (m.gv(2).ifEmpty { lastToolResult?.let { Regex("""Scanning ([\d.]+)""").find(it)?.groupValues?.get(1) } } ?: "")
                .let { if (it.isBlank()) "" else it }
            if (t.isBlank()) {
                MockBrainResponse("sure — give me a target IP/host and I'll build an attack chain. e.g. 'attack chain for 192.168.1.50'")
            } else {
                val chain = """
                    Multi-step attack workflow for **$t**:

                    ```chain
                    {
                      "name": "Attack Chain: $t",
                      "steps": [
                        { "tool": "port_scanner", "params": { "target": "$t", "start_port": "1", "end_port": "9999" } },
                        { "tool": "ssh_audit", "params": { "target": "$t" } },
                        { "tool": "http_inspector", "params": { "url": "http://$t" } }
                      ]
                    }
                    ```
                """.trimIndent()
                MockBrainResponse(chain, chain = chain)
            }
        },
        // "web assessment of <url>" -> http inspect + headers + dir fuzz + nuclei
        Regex("""(web\s+assessment|web\s+audit|full\s+web\s+scan)\s+(?:on|of|for|against)?\s*([\w./:?=&%-]+)?""") to { m, _ ->
            val raw = m.gv(2).ifEmpty { lastToolResult?.let { Regex("""http[s]?://[\w./:?=&%-]+""").find(it)?.value } } ?: ""
            val url = if (raw.startsWith("http")) raw else "http://$raw"
            if (raw.isBlank()) {
                MockBrainResponse("give me a URL and I'll run a full web assessment chain. e.g. 'web assessment of https://example.com'")
            } else {
                val chain = """
                    Web assessment workflow for **$url**:

                    ```chain
                    {
                      "name": "Web Assessment: $url",
                      "steps": [
                        { "tool": "http_inspector", "params": { "url": "$url" } },
                        { "tool": "security_headers", "params": { "url": "$url" } },
                        { "tool": "directory_fuzzer", "params": { "url": "$url" } }
                      ]
                    }
                    ```
                """.trimIndent()
                MockBrainResponse(chain, chain = chain)
            }
        },
    ) }

    // ------------------------------------------------------------------
    // Chat patterns — conversational text-only responses
    // ------------------------------------------------------------------
    private val chatPatterns: List<Pair<Regex, (String) -> String>> = listOf(
        // ── Security education ───────────────────────────────────────
        Regex("""what is a? ?port scan""")          to { _ -> "a port scan checks which 'doors' (ports) on a device are open. every app that talks over the network listens on a numbered port — like 80 for web, 22 for SSH. scanning tells you what's running." },
        Regex("""what is an? ?ip ?address""")        to { _ -> "an IP address is like a home address for a device on a network — a series of numbers (like 192.168.1.1) that tells other devices where to send data." },
        Regex("""what is a? ?dns""")                 to { _ -> "DNS is the internet's phone book. when you type 'google.com', DNS translates it to an IP like 142.250.80.46 that your computer connects to." },
        Regex("""what is (ssl|tls|https)""")         to { _ -> "SSL/TLS encrypts data between your browser and a website — the padlock icon. without it, anyone on the same network can read your traffic." },
        Regex("""what is a? ?subnet""")              to { _ -> "a subnet is a range of IPs in the same network. '192.168.1.0/24' = addresses .1 to .254. the /24 means the first 24 bits are fixed." },
        Regex("""what is a? ?firewall""")            to { _ -> "a firewall filters network traffic — decides what's allowed in/out. it blocks ports, IPs, or protocols. that's why some ports show as 'filtered' in scans." },
        Regex("""what is ssh""")                     to { _ -> "SSH (Secure Shell) = encrypted remote terminal login on port 22. find port 22 open? you could try logging in (on YOUR devices only)." },
        Regex("""what is a? ?cve""")                 to { _ -> "CVE = Common Vulnerabilities and Exposures. a public database of known security bugs, each with an ID like CVE-2021-44228. CVSS score 0-10 shows severity." },
        Regex("""what is sql.?injection""")          to { _ -> "SQL injection = putting database commands into website inputs to manipulate the DB. like entering ' OR '1'='1 into a login form. one of the most common web vulns." },
        Regex("""what is (xss|cross.?site)""")       to { _ -> "XSS = Cross-Site Scripting. injecting JavaScript into a webpage that runs in other users' browsers. can steal cookies, redirect to phishing pages, etc." },
        Regex("""what is arp""")                     to { _ -> "ARP maps IPs to MAC addresses. ARP spoofing tricks devices into thinking YOU are the router — classic man-in-the-middle attack." },
        Regex("""what is a? ?brute.?force""")        to { _ -> "brute force = trying every password combo until one works. tools like Hydra automate this. slow but effective against weak passwords." },
        Regex("""what is a? ?hash""")                to { _ -> "a hash is a one-way mathematical fingerprint. 'password' → MD5 → '5f4dcc3b5aa765d61d8327deb882cf99'. websites store hashed passwords so raw ones aren't exposed." },
        Regex("""what is a? ?reverse ?shell""")      to { _ -> "a reverse shell makes a target connect BACK to you instead of you connecting to it. bypasses firewalls. you get a terminal session." },
        Regex("""what is (netbios|smb)""")           to { _ -> "NetBIOS/SMB = Windows file sharing protocol on port 445. infamous for EternalBlue (MS17-010), the exploit behind WannaCry ransomware." },
        Regex("""what is a? ?traceroute""")          to { _ -> "traceroute maps the route packets take to a target. each 'hop' is a router along the way. useful for diagnosing slow connections." },
        Regex("""what is (wpa|wpa2|wpa3)""")         to { _ -> "WPA2/WPA3 = WiFi encryption standards. WPA3 is newest and most secure. WEP is completely broken. open networks = anyone reads your traffic." },
        Regex("""what is a? ?payload""")             to { _ -> "a payload is the code that does the actual damage — opens a reverse shell, runs commands, downloads malware. Metasploit generates these." },
        Regex("""what is nmap""")                    to { _ -> "Nmap = Network Mapper. industry standard for network discovery — finds hosts, scans ports, detects OS + software versions. essential tool." },
        Regex("""what is (jwt|json web token)""")    to { _ -> "JWT = JSON Web Token. used for authentication between services. if misconfigured, attackers can forge tokens or bypass security." },
        Regex("""what is cors""")                    to { _ -> "CORS = Cross-Origin Resource Sharing. browser mechanism that lets sites share resources across domains. misconfigured? evil.com can read your private data." },
        Regex("""what is metasploit""")              to { _ -> "Metasploit = world's most used pentesting framework. thousands of exploits, payloads, and post-exploitation modules. the big gun." },
        Regex("""what is a? ?vpn""")                 to { _ -> "VPN = Virtual Private Network. encrypts your internet traffic and routes it through another server. hides your IP and location. essential for privacy." },
        Regex("""what is phishing""")                to { _ -> "phishing = tricking someone into giving up credentials via fake emails, websites, or messages that look legit. #1 attack vector globally." },
        Regex("""what is a? ?zero.?day""")           to { _ -> "a zero-day is a vulnerability that's unknown to the vendor — no patch exists yet. called 'zero-day' because developers have had zero days to fix it." },
        Regex("""what is ransomware""")              to { _ -> "ransomware encrypts your files and demands payment (usually crypto) to decrypt them. WannaCry, LockBit, REvil — all ransomware gangs." },
        Regex("""what is a? ?man.?in.?the.?middle""") to { _ -> "MITM = intercepting communication between two parties. ARP spoofing on LANs, rogue WiFi access points, or SSL stripping are common methods." },
        Regex("""what is (a )?dos|what is ddos""")   to { _ -> "DoS = Denial of Service. flooding a target with traffic until it can't respond. DDoS = Distributed DoS, using many machines (botnets). illegal." },
        Regex("""what is social engineering""")      to { _ -> "social engineering = manipulating people into giving up info or access. pretexting, baiting, tailgating, phishing — all social engineering." },
        Regex("""what is a? ?honeypot""")            to { _ -> "a honeypot is a fake system designed to attract attackers. it looks like a real target but actually logs everything the attacker does. used for threat intelligence." },
        // ── Networking concepts ───────────────────────────────────────
        Regex("""what is (a )?router""")             to { _ -> "a router connects your local network to the internet. it assigns IPs via DHCP, handles NAT, and is usually the gateway at .1 on your subnet. it's the first thing to scan." },
        Regex("""what is (a )?gateway""")            to { _ -> "the gateway is the router your traffic exits through — usually 192.168.1.1 or 192.168.0.1. it's the amber node at the center of the globe." },
        Regex("""what is (a )?mac address""")        to { _ -> "a MAC address is a hardware ID burned into every network card — like AA:BB:CC:DD:EE:FF. unique per device. ARP scan reveals MAC addresses on your LAN." },
        Regex("""what is (a )?dhcp""")               to { _ -> "DHCP automatically assigns IP addresses to devices when they join a network. your router runs a DHCP server. that's why your phone gets an IP without manual config." },
        Regex("""what is (a )?nat""")                to { _ -> "NAT = Network Address Translation. your router maps your private IPs (192.168.x.x) to one public IP. that's why the internet sees one IP for your whole house." },
        Regex("""what is (a )?tcp""")                to { _ -> "TCP = Transmission Control Protocol. reliable, ordered delivery — used by HTTP, SSH, FTP. does a 3-way handshake (SYN → SYN-ACK → ACK) before sending data." },
        Regex("""what is (a )?udp""")                to { _ -> "UDP = User Datagram Protocol. fast but no guarantee of delivery — used by DNS, VoIP, gaming. no handshake, just fire and forget." },
        Regex("""what is (a )?icmp""")               to { _ -> "ICMP = Internet Control Message Protocol. used by ping and traceroute. many firewalls block it, which is why some hosts don't respond to ping but are still up." },
        Regex("""what is (a )?packet""")             to { _ -> "a packet is a chunk of data sent over a network. every packet has a header (source/dest IP, port, protocol) and a payload (the actual data). packet sniffers capture these raw." },
        Regex("""what is (a )?proxy""")              to { _ -> "a proxy sits between you and the target — forwards your requests. useful for intercepting traffic (Burp Suite), anonymity, or bypassing filters. set one in Network Settings." },
        Regex("""what is (a )?port""")               to { _ -> "a port is a numbered channel (0–65535) on a device. apps listen on specific ports — 80=HTTP, 443=HTTPS, 22=SSH. open ports = running services. closed = nothing listening. filtered = firewall blocking." },
        Regex("""what is (a )?cidr""")               to { _ -> "CIDR = Classless Inter-Domain Routing. the /24 in 192.168.1.0/24 means 24 bits are the network part, leaving 8 bits for hosts = 254 usable IPs. use 'subnet <cidr>' to calculate." },
        Regex("""what is (a )?vlan""")               to { _ -> "VLAN = Virtual LAN. logically separates a physical network into isolated segments. devices on different VLANs can't talk directly — requires a router. common in enterprise networks." },
        Regex("""what is (a )?ttl""")                to { _ -> "TTL = Time To Live. a counter in every packet that decrements at each router hop. when it hits 0, the packet is dropped. traceroute exploits this to map hops." },
        Regex("""what is (a )?banner grab""")        to { _ -> "banner grabbing = connecting to a port and reading what the service announces about itself — version, software name. nmap does this with -sV. reveals outdated software." },
        Regex("""what is (a )?ping""")               to { _ -> "ping sends ICMP echo requests to check if a host is alive and measure latency. 'ping 8.8.8.8' = Google's DNS. blocked by many firewalls — use ARP scan on LAN instead." },
        Regex("""what is (a )?open port""")          to { _ -> "an open port means a service is actively listening for connections. each open port is a potential entry point. always ask: should this port be open? is the service patched?" },
        Regex("""what is (a )?closed port""")        to { _ -> "a closed port means nothing is listening, but the host is reachable. the OS responds with RST. different from filtered — filtered means a firewall is silently dropping packets." },
        Regex("""what is (a )?filtered port""")      to { _ -> "a filtered port means a firewall is blocking the probe — no response at all. nmap marks these as filtered. could be open or closed behind the firewall." },
        Regex("""what is (a )?service""")            to { _ -> "a service is a program listening on a port — like Apache on 80, OpenSSH on 22, MySQL on 3306. nmap -sV fingerprints the exact version. outdated versions = known CVEs." },
        Regex("""what is (a )?network scan""")       to { _ -> "a network scan discovers active hosts on a subnet. Optix pings every IP in the range and maps responding ones to the globe. start with 'lan scan' to see your network." },
        Regex("""what is (a )?packet sniffer""")     to { _ -> "a packet sniffer captures raw network traffic — every packet flowing through your interface. needs root. use it to see what devices on your network are actually sending." },
        Regex("""what is (a )?deauth""")             to { _ -> "a deauth attack sends forged 802.11 deauthentication frames to kick devices off WiFi. works because 802.11 management frames aren't authenticated. needs monitor mode + root." },
        Regex("""what is (a )?evil twin""")          to { _ -> "an evil twin is a rogue WiFi AP with the same SSID as a legit network. devices auto-connect, routing all traffic through you. classic MITM setup." },
        Regex("""what is (a )?masscan""")            to { _ -> "Masscan is the fastest port scanner — can scan the entire internet in under 6 minutes. sends packets asynchronously without waiting for responses. needs Termux + root." },
        Regex("""what is (a )?legion""")             to { _ -> "Legion is an automated network pentesting framework. runs nmap, then launches service-specific scanners automatically. great for thorough recon. needs Termux." },
        Regex("""what is (a )?hydra""")              to { _ -> "Hydra is a fast network login cracker. supports SSH, FTP, HTTP, RDP, MySQL, and 50+ more protocols. tries username/password combos from wordlists. needs Termux." },
        Regex("""what is (a )?nikto""")              to { _ -> "Nikto is a web server scanner — checks for 6700+ known vulnerabilities, dangerous files, outdated software, and misconfigs. run it against any web server. needs Termux." },
        Regex("""what is (a )?sqlmap""")             to { _ -> "SQLmap automates SQL injection detection and exploitation. give it a URL with a parameter and it tests every injection technique automatically. needs Termux." },
        Regex("""what is (a )?directory fuzz""")     to { _ -> "directory fuzzing tries common paths (/admin, /backup, /.git, /config) against a web server to find hidden endpoints. Optix uses a built-in wordlist." },
        Regex("""what is (a )?subdomain""")          to { _ -> "subdomains are prefixes on a domain — like mail.google.com or dev.google.com. subdomain enumeration finds hidden ones that might expose admin panels or dev servers." },
        Regex("""what is (a )?dns recon""")          to { _ -> "DNS recon queries all record types for a domain — A (IP), MX (mail), NS (nameservers), TXT (SPF/DKIM), CNAME (aliases). reveals infrastructure and email setup." },
        Regex("""what is (a )?ssh audit""")          to { _ -> "SSH audit checks the SSH server config — supported algorithms, key exchange methods, known weak ciphers. weak configs can be exploited even without a password." },
        Regex("""what is (a )?arp spoof""")          to { _ -> "ARP spoofing sends fake ARP replies to poison the ARP cache of devices — making them send traffic to you instead of the router. classic MITM on LAN. needs root." },
        Regex("""what is (a )?network topology""")   to { _ -> "network topology maps how devices connect — runs traceroutes + ASN lookups to visualize the path from you to any target. shows ISPs, data centers, and routing." },
        Regex("""what is (a )?rping""")              to { _ -> "rping3 is a raw ping tool with detailed RTT statistics — min/max/avg latency, jitter, packet loss. more detailed than standard ping." },
        Regex("""what is (a )?wifi scan""")          to { _ -> "WiFi scan shows all nearby access points — SSID, BSSID (MAC), signal strength (dBm), channel, and encryption type (WPA2/WPA3/Open). good for spotting rogue APs." },

        // ── Learn commands ────────────────────────────────────────────
        Regex("""^learn ports?""")                   to { _ -> "ports 101:\n\n22=SSH · 80=HTTP · 443=HTTPS · 21=FTP · 25=SMTP · 53=DNS · 3389=RDP · 445=SMB · 3306=MySQL · 3306=MySQL · 5432=PostgreSQL · 6379=Redis · 27017=MongoDB · 8080=HTTP-Alt · 5900=VNC\n\nopen ports = active services. unexpected open ports = potential attack surface. run 'port scan <ip>' to check." },
        Regex("""^learn (web|http)""")               to { _ -> "web security:\n\nHTTP=unencrypted · HTTPS=encrypted\n\nCommon vulns:\n• SQL injection — 'sqli <url>'\n• XSS — 'xss <url>'\n• Directory traversal — 'fuzz <url>'\n• Security headers — 'headers <url>'\n• CORS misconfig — 'cors <url>'\n\nstart with: 'http <url>' to inspect any site" },
        Regex("""^learn scanning""")                 to { _ -> "scanning workflow:\n\n1. 'lan scan' — find all devices\n2. 'port scan <ip>' — find open services\n3. 'nmap <ip>' — detect OS + versions\n4. 'ssh audit <ip>' — check SSH config\n5. 'netbios <ip>' — Windows shares\n\nresults appear on the globe and in the console." },
        Regex("""^learn (password|credential)""")    to { _ -> "password security:\n\nweak: 123456, password, admin\nstrong: 16+ chars, mixed case + numbers + symbols, unique per site\n\ntype 'password gen' to generate a strong one now.\n\ncracking: 'crack <hash>' tries rainbow tables. MD5/SHA1 crack fast — bcrypt/argon2 are much harder." },
        Regex("""^learn (exploit|exploitation)""")   to { _ -> "exploitation basics:\n\n• brute force — try passwords: 'brute ssh <ip>'\n• Hydra — fast login cracker: 'hydra <ip> ssh'\n• Metasploit — exploit framework (Termux)\n• ARP spoof — MITM on LAN\n• Deauth — kick devices off WiFi\n\nalways get written permission first." },
        Regex("""^learn (network|networking)""")     to { _ -> "networking basics:\n\n• LAN = your local network (192.168.x.x)\n• Gateway = your router (usually .1)\n• Subnet = range of IPs (/24 = 254 hosts)\n• Port = numbered channel (0–65535)\n• TCP = reliable · UDP = fast\n\nstart: 'lan scan' → see every device on your network" },
        Regex("""^learn (wifi|wireless)""")          to { _ -> "WiFi security:\n\n• WEP — completely broken, crack in seconds\n• WPA — weak, avoid\n• WPA2 — standard, vulnerable to PMKID/handshake attacks\n• WPA3 — most secure, use if available\n• Open — no encryption, anyone reads your traffic\n\ntry: 'wifi scan' to see nearby networks" },
        Regex("""^learn (dns|domain)""")             to { _ -> "DNS basics:\n\n• A record — domain → IPv4\n• AAAA — domain → IPv6\n• MX — mail servers\n• NS — nameservers\n• TXT — SPF, DKIM, verification\n• CNAME — alias to another domain\n\ntry: 'dns google.com' to see all records" },
        Regex("""^learn osint""")                     to { _ -> "OSINT workflow:\n\n1. Start with Shodan: 'shodan <query>' — find internet-connected devices\n2. Domain intel: 'harvest <domain>' — gather emails, subdomains, hosts\n3. Email breaches: 'hibp <email>' — check if emails were in known breaches\n4. Email verification: 'hunter <domain>' — find email patterns + deliverability\n\nOSINT = Open Source Intelligence. all tools pull from public data — search engines, PGP keys, breach databases, and IoT search engines." },
        Regex("""^learn lpe""")                       to { _ -> "privilege escalation (PE):\n\nPE = exploiting misconfigs or bugs to gain higher privileges (e.g. user → root).\n\ntools:\n• 'linpeas' — automated Linux PE enumeration\n• 'winpeas <target>' — automated Windows PE enumeration\n• 'bloodhound' — AD attack path analysis\n• 'cme <target>' — automates lateral movement\n\ncommon PE vectors: sudo misconfig, SUID binaries, kernel exploits, weak service permissions, stored credentials." },
        Regex("""^learn active directory""")          to { _ -> "Active Directory (AD):\n\nAD = Microsoft's directory service for Windows networks. manages users, computers, groups, and permissions.\n\nBloodHound maps AD relationships and finds attack paths — e.g. shortest route from a standard user to Domain Admin.\n\nkey concepts:\n• Domain Controller (DC) = server running AD\n• Group Policy = rules pushed to all domain machines\n• GPO = Group Policy Object\n• Kerberos = authentication protocol\n• LDAP = directory query protocol\n\ntry: 'bloodhound' to start analyzing AD relationships." },
        Regex("""(check|inspect|scan|test).*(ssl|cert|certificate).*(for|on)?\s*([\w.-]+\.\w{2,})""") to { _ -> "to check SSL, try: 'http https://<domain>' — shows cert details, headers, and security config. then 'headers https://<domain>' checks HSTS, CSP, X-Frame-Options.\n\nfor a full grade, visit ssllabs.com." },
        Regex("""(how does|explain|what is) arp.?spoof""") to { _ -> "ARP spoofing:\n\n1. attacker sends fake ARP replies to the network\n2. devices update their ARP cache — now they think the attacker IS the router\n3. all traffic flows through the attacker (MITM)\n4. attacker can read, modify, or drop packets\n\ndefense: dynamic ARP inspection (DAI) on managed switches, static ARP entries.\n\ntry it (on your own network): 'arp spoofer' in the NETWORK tab." },
        Regex("""(help me start|where do i start|i.*new|teach me|beginner|getting started)""") to { _ -> "welcome! here's where to start:\n\n1. 'lan scan' — see every device on your network\n2. Pick an IP → 'port scan <ip>'\n3. 'nmap <ip>' — deeper service detection\n4. 'dns <domain>' — DNS recon on any domain\n5. 'learn ports' — understand port numbers\n6. 'help' — full command cheatsheet\n\nall results are tappable with explanations!" },
        Regex("""how (do i|to) (use|run) nmap""")    to { _ -> "nmap usage:\n\n'nmap <ip>' — basic scan\n'nmap <ip/range>' — scan a range\n\nnmap needs Termux installed. it detects OS, service versions, and runs scripts. the -sV flag (set in Network Settings) enables version detection." },
        Regex("""how (do i|to) (use|run) hydra""")   to { _ -> "hydra usage:\n\n'hydra <ip> ssh' — brute SSH\n'hydra <ip> ftp' — brute FTP\n'hydra <ip> http' — brute HTTP login\n\nneeds Termux. use a wordlist. only on systems you own." },
        Regex("""how (do i|to) (use|run) (masscan|mass scan)""") to { _ -> "masscan usage:\n\n'masscan <ip/range>' — ultra-fast port scan\n\nfastest scanner available. needs Termux + root. great for scanning large ranges quickly." },
        Regex("""how (do i|to) (scan|find) (open )?ports""") to { _ -> "to scan ports:\n\n• 'port scan <ip>' — built-in scanner, ports 1–9999\n• 'nmap <ip>' — deeper scan with version detection\n• 'masscan <ip>' — fastest, needs Termux\n\nor tap any node on the globe → FULL PORT SCAN" },
        Regex("""how (do i|to) (find|see|discover) devices""") to { _ -> "to find devices on your network:\n\n• 'lan scan' — pings every IP in your subnet\n• 'arp scan' — ARP-based, finds devices even if ping is blocked\n• results appear as nodes on the 3D globe\n\ntap any node to investigate further." },
        Regex("""how (do i|to) (check|test|inspect) (a )?website""") to { _ -> "to inspect a website:\n\n• 'http <url>' — headers, server info, cookies\n• 'headers <url>' — security headers check\n• 'dns <domain>' — DNS records\n• 'subdomain <domain>' — find hidden subdomains\n• 'fuzz <url>' — find hidden directories\n• 'sqli <url>' — test for SQL injection\n• 'xss <url>' — test for XSS" },
        Regex("""how (do i|to) (use|set|configure) termux""") to { _ -> "Termux setup:\n\n1. Install Termux from F-Droid (not Play Store)\n2. Run: pkg update && pkg upgrade\n3. Run: pkg install nmap hydra masscan\n4. Grant storage permission: termux-setup-storage\n\nOptix auto-installs missing tools when you run them — just tap 'Install & Run' when prompted." },
        Regex("""how (do i|to) (use|set) (a )?proxy""")      to { _ -> "to route tool traffic through a proxy:\n\n1. Go to NETWORK tab → Settings gear\n2. Set Proxy Host (e.g. 192.168.1.x) and Port (e.g. 8080)\n3. Use Burp Suite or mitmproxy as the listener\n\ngreat for intercepting web tool traffic." },
        Regex("""how (do i|to) (use|enable) tor""")           to { _ -> "to route through Tor:\n\n1. Install Tor in Termux: pkg install tor\n2. Start it: tor &\n3. Go to NETWORK Settings → enable 'Use Tor' (port 9050)\n\nall tool traffic routes through the Tor network." },
        Regex("""(what|which) (port|ports) (is|are|does) (ssh|ftp|http|https|smtp|dns|rdp|smb|mysql|rdp|vnc|redis|mongo)""") to { _ ->
            "common ports: 22=SSH · 21=FTP · 80=HTTP · 443=HTTPS · 25=SMTP · 53=DNS · 3389=RDP · 445=SMB · 3306=MySQL · 5900=VNC · 6379=Redis · 27017=MongoDB. use 'port scan <ip>' to check what's open."
        },
        Regex("""(is|are) (port|ports) (\d+) (open|safe|dangerous)""") to { _ ->
            "use 'port scan <ip>' to check if a port is open on a specific device. open = service listening, closed = nothing there, filtered = firewall blocking."
        },

        // ── App questions ─────────────────────────────────────────────
        Regex("""(who are you|what are you|what can you do)""") to { _ -> "i'm Optix Brain — your security AI assistant. offline mode right now, but I can still run all the network and web tools. type 'tools' to browse, or 'help' for commands. connect an API key in Settings for full natural language." },
        Regex("""(are you (there|online|working)|you there)""") to { _ -> "yep, right here — offline brain active. all tools are ready. connect an API in Settings for full conversational AI." },
        Regex("""(what tools|which tools|tools do you have|what can you run|what.*available)""") to { _ -> "here's what i can run:\n\nNETWORK: lan_scanner · port_scanner · nmap · masscan · arp_scan · wifi_scanner · traceroute · netbios · ssh_audit · snmpwalk · smbclient · dnsenum · fierce · legion · network_topology · packet_sniffer\n\nWEB: http_inspector · directory_fuzzer · gobuster · sqli_tester · xss_scanner · nikto · sqlmap · cors_checker · security_headers · jwt_analyzer · whatweb · wpscan · subdomain_enum · dns_recon\n\nEXPLOIT: hydra · brute_force · arp_spoofer · metasploit · msfvenom · evil_twin · deauth_attack · enum4linux\n\nUTILITY: hash_cracker · password_generator · encoder · subnet_calculator · hash_generator · cipher · regex_tester · payload_generator · reverse_shell_gen\n\njust ask me to run any of them, or type 'help' for command syntax." },
        Regex("""how (do i|to) (use|run|start)""")   to { _ -> "just type a command like 'scan 192.168.1.1' or 'dns google.com'. or tap a tool in the NETWORK tab. type 'help' for the full list." },
        Regex("""(it.*not|nothing|doesn.*work|broken|error|failed)""") to { _ -> listOf(
            "hmm, some tools need network access or Termux installed. make sure you're connected to WiFi and try again.",
            "try checking the error in the console log — it usually tells you what went wrong.",
            "some tools require root or Termux. check the tool description for requirements.",
        ).random() },
        Regex("""(do it again|try again|rerun|re-run|repeat)""") to { _ -> "sure, just send the same command again or pick a tool from the NETWORK tab and hit Run." },
        Regex("""(what else|anything else|more tools|other tools)""") to { _ -> "type 'tools' to see everything, or try: 'learn scanning', 'learn web', 'learn passwords' for guided walkthroughs." },

        // ── Casual / Generic ──────────────────────────────────────────
        Regex("""thank""")                           to { _ -> listOf("no problem!", "anytime.", "you got it.", "happy to help!", "🤙").random() },
        Regex("""(cool|nice|sweet|great|awesome|dope|sick|fire|lit)""") to { _ -> listOf("glad it worked!", "nice.", "let's keep going.", "🔥", "right? pretty slick.").random() },
        Regex("""(lol|lmao|haha|😂|😆)""")           to { _ -> listOf("😄", "glad you're having fun!", "haha let's get back to hacking (legally).", "lol, security can be fun.").random() },
        Regex("""(how are you|how.*doing|how.*going)""") to { _ -> listOf("doing great! ready to find some vulns?", "all good over here — tools loaded and waiting.", "i'm a chatbot, so i'm always good. you?").random() },
        Regex("""(what.*time|what day)""")            to { _ -> "i don't have a clock, but your phone does! i'm better at scanning networks than telling time. 😅" },
        Regex("""(weather|rain|sunny|cold|hot)""")    to { _ -> "no weather module installed... but i CAN tell you what's running on port 80 of your router. priorities! 😄" },
        Regex("""(joke|funny|make me laugh)""")       to { _ -> listOf(
            "why did the pentester bring a ladder? to get to the next level of privilege escalation. 🪜",
            "a SQL query walks into a bar, sees two tables, and says 'can I JOIN you?'",
            "why do hackers prefer dark mode? because light attracts bugs. 🐛",
            "knock knock. who's there? *. * who? DROP TABLE users;-- oops.",
            "how do trees get on the internet? they log in. 🌲",
        ).random() },
        Regex("""(bored|boring|nothing to do)""")     to { _ -> "bored? try:\n• 'lan scan' — see who's lurking on your network\n• 'dns <any-domain>' — investigate a website's DNS\n• 'learn scanning' — mini cybersecurity lesson\n• 'password gen' — generate an uncrackable password" },
        Regex("""(who made you|who built|who created|developer)""") to { _ -> "i was built as part of Optix — a mobile penetration testing platform. type 'tools' to see everything i can do!" },
        Regex("""(yes|yeah|yep|yea|ya|sure|ok|okay|k|bet|aight)""") to { _ -> listOf("cool, what's next?", "alright, hit me with the next command.", "ready when you are.", "let's go.").random() },
        Regex("""(no|nah|nope|not really)""")         to { _ -> listOf("all good. let me know when you need something.", "no worries, i'll be here.", "cool. type 'help' whenever.").random() },
        Regex("""(bye|goodbye|see ya|later|peace|cya|gtg|gotta go)""") to { _ -> listOf("later! don't forget to close those open ports. 😄", "peace! stay safe out there.", "see ya — happy hacking!", "cya! remember: only scan what you own.").random() },
        Regex("""(good|bad|wrong|right|correct|incorrect)""") to { _ -> listOf("noted! what should we try next?", "got it. anything else?", "understood.").random() },
        Regex("""(i love|i hate|i like|i dislike)""") to { _ -> listOf("haha, noted. what do you want to scan next?", "strong feelings! let's channel that into some recon.", "i appreciate the honesty. type 'tools' if you want to explore.").random() },
        Regex("""(hey siri|ok google|alexa|chatgpt|gpt)""") to { _ -> "wrong AI! i'm Ori-on Brain — specifically built for security. way cooler than a smart speaker. try 'help' 😎" },
        Regex("""(music|song|play|spotify)""")        to { _ -> "i don't do music, but i can orchestrate a beautiful symphony of network packets. try 'lan scan'! 🎵" },
        Regex("""(food|hungry|eat|pizza|coffee)""")   to { _ -> "can't help with food, but i CAN help you digest some network traffic. 'packet sniffer' anyone? ☕" },
        Regex("""(game|play|gaming)""")               to { _ -> "the only game i play is CTF (Capture The Flag). try 'cipher rot13 <text>' for some CTF practice!" },
        Regex("""(money|crypto|bitcoin|stock)""")     to { _ -> "i deal in a different kind of currency — network intelligence. try 'lan scan' to see what's on your network!" },
    )

    private fun genericResponse(input: String): String {
        val lower = input.lowercase()
        return when {
            lower.length < 3 -> "hmm, didn't catch that. type 'help' to see what i can do."
            lower.contains("?") -> listOf(
                "not sure about that one — try 'help' or describe what you want to scan.",
                "good question! try 'learn networking', 'learn scanning', or 'learn web' for explanations.",
                "i might not know that one offline — connect an API in Settings for full natural language.",
            ).random()
            else -> listOf(
                "not sure what you mean — try 'help' or describe what you're trying to do.",
                "i'm best with commands like 'scan <ip>' or 'port scan <ip>'. type 'tools' for the full list.",
                "connect an API provider in Settings and i'll understand natural language way better.",
                "hmm, try something like 'lan scan' or 'port scan 192.168.1.1'. type 'help' for more.",
                "didn't quite get that. try 'learn networking' for a primer, or 'help' for commands.",
                "not sure — but if you tell me what you're trying to find, i can point you to the right tool.",
            ).random()
        }
    }

    private fun randomGreeting(): String = listOf(
        "hey! what do you want to scan today?",
        "Optix Brain online — what are we checking?",
        "yo, ready when you are. type 'help' if you need a hand.",
        "what's up? all tools loaded and ready.",
        "online and ready. type 'tools' to see what i can do.",
        "hey! type a command, or tap a suggestion below to get started.",
        "ready to roll — what's the target?",
        "brain active. 'lan scan' to see your network, or 'help' for all commands.",
        "what are we investigating today?",
    ).random()

    /** Extension to shorten MatchResult.groupValues[n] */
    private fun MatchResult.gv(n: Int): String = groupValues.getOrElse(n) { "" }

    companion object {
        const val HELP_TEXT = """hey, here's a quick cheatsheet:

NETWORK   scan <ip> | port scan <ip> | lan scan | wifi scan | traceroute <host> | nmap <host> | arp scan | ssh audit <host> | netbios <ip> | masscan <ip> | sniff | topology | legion <host>
DNS/WEB   dns <domain> | subdomain <domain> | http <url> | fuzz <url> | sqli <url> | xss <url> | cors <url> | headers <url> | jwt <token> | nikto <host> | sqlmap <url>
EXPLOIT   brute <proto> <target> | hydra <host> <service> | payload <type> <ip> <port> | reverse shell <lang> <ip> <port>
UTILITY   crack <hash> | password gen | encode <type> <text> | decode <type> <text> | subnet <cidr> | hash <text> | cipher <mode> <text> | rot13 <text> | regex <pattern> on <text>

LEARN     learn ports | learn scanning | learn web | learn networking | learn wifi | learn dns | learn exploit | learn passwords
OTHER     tools | status | aliases | help

or just describe what you want in plain english — i'll figure it out."""

        const val TOOLS_LIST = """registered tools:

Network (14):  network_scanner · port_scanner · lan_scanner · netbios_scanner · wifi_scanner · traceroute · packet_sniffer · rping3_termux · nmap_termux · masscan_termux · arp_scan · ssh_audit · legion_termux · network_topology
DNS/Web (11):  dns_recon · subdomain_enum · http_inspector · directory_fuzzer · sqli_tester · xss_scanner · nikto_termux · sqlmap_termux · cors_checker · security_headers · jwt_analyzer
Exploit (7):   brute_force · arp_spoofer · hydra_termux · metasploit_termux · msfvenom_termux · evil_twin · deauth_attack
OSINT (5):     shodan_search · shodan_host · theharvester · hibp_check · hunter_verify
LPE/Lateral (6): linpeas · winpeas · bloodhound · cme · rubeus · nuclei
Utility (9):   payload_generator · reverse_shell_gen · hash_cracker · password_generator · encoder_tool · subnet_calculator · hash_generator · cipher_tool · regex_tester

type a tool name or use the commands in 'help'"""

        const val ALIASES_TEXT = "ps = port scan | scan = network scan | ls = lan scan | ws = wifi scan"

        /** All tool names referenced in toolDispatch — validated against ToolRegistry at startup. */
        val DISPATCH_TOOL_NAMES = setOf(
            "network_scanner", "port_scanner", "lan_scanner", "netbios_scanner", "wifi_scanner",
            "traceroute", "nmap_termux", "arp_scan", "ssh_audit", "masscan_termux",
            "rping3_termux", "packet_sniffer", "network_topology", "legion_termux",
            "dns_recon", "subdomain_enum", "http_inspector", "directory_fuzzer", "sqli_tester",
            "xss_scanner", "cors_checker", "security_headers", "jwt_analyzer",
            "nikto_termux", "sqlmap_termux", "nuclei_termux",
            "brute_force", "hydra_termux", "payload_generator", "reverse_shell_gen",
            "hash_cracker", "password_generator", "encoder_tool", "subnet_calculator",
            "hash_generator", "cipher_tool", "regex_tester",
            "shodan_search", "shodan_host", "theharvester", "hibp_check", "hunter_verify",
            "linpeas_termux", "winpeas_termux", "bloodhound_termux", "cme_termux",
        )
    }
}
