package com.optix.android.ai

import javax.inject.Inject
import javax.inject.Singleton

/**
 * Intent recognition engine for the MockBrain offline AI.
 * 
 * Parses user input through a multi-layered matching strategy:
 * 1. Exact command matching (help, status, tools)
 * 2. Tool dispatch patterns (regex-based command parsing)
 * 3. Natural language patterns (fuzzy intent matching)
 * 4. Conversational patterns (educational responses)
 * 
 * @property exactCommands Map of exact string matches to their intent types
 * @property toolDispatch List of regex patterns that map to tool invocations
 * @property nlToolPatterns List of regex patterns for natural language tool intent
 * @property chatPatterns List of regex patterns for conversational responses
 */
@Singleton
class IntentParser @Inject constructor() {

    /**
     * Represents the result of intent parsing.
     * 
     * @property intentType The category of intent detected
     * @property match The regex match result (if applicable)
     * @property originalInput The original user input (for context)
     */
    data class ParsedIntent(
        val intentType: IntentType,
        val match: MatchResult? = null,
        val originalInput: String,
    )

    /**
     * Categories of user intent.
     */
    sealed class IntentType {
        /** Exact command match (help, tools, status) */
        data class ExactCommand(val command: String) : IntentType()
        
        /** Tool invocation with parameters */
        data class ToolCall(val patternIndex: Int) : IntentType()
        
        /** Natural language tool request */
        data class NaturalLanguageTool(val patternIndex: Int) : IntentType()
        
        /** Conversational/educational response */
        data class Conversation(val patternIndex: Int) : IntentType()
        
        /** Contextual follow-up (affirmative after tool result) */
        data object ContextualFollowUp : IntentType()
        
        /** Empty or blank input */
        data object EmptyInput : IntentType()
        
        /** No pattern matched */
        data object Unknown : IntentType()
    }

    /**
     * Parses user input and identifies the intent.
     * 
     * @param input The raw user input string
     * @return ParsedIntent containing the detected intent type and match information
     */
    fun parseIntent(input: String): ParsedIntent {
        val trimmed = input.trim()
        if (trimmed.isBlank()) {
            return ParsedIntent(IntentType.EmptyInput, originalInput = trimmed)
        }

        val lower = trimmed.lowercase()

        // 1. Check exact commands
        if (lower in exactCommands) {
            return ParsedIntent(IntentType.ExactCommand(lower), originalInput = trimmed)
        }

        // 2. Check tool dispatch patterns
        toolDispatchPatterns.forEachIndexed { index, pattern ->
            val match = pattern.find(lower)
            if (match != null) {
                return ParsedIntent(IntentType.ToolCall(index), match, trimmed)
            }
        }

        // 3. Check natural language tool patterns
        nlToolPatterns.forEachIndexed { index, pattern ->
            val match = pattern.find(lower)
            if (match != null) {
                return ParsedIntent(IntentType.NaturalLanguageTool(index), match, trimmed)
            }
        }

        // 4. Check if it's an affirmative for contextual follow-up
        val affirmativePattern = Regex("""^(yes|yeah|yep|sure|ok|okay|do it|go ahead|scan|check|test|run it|port scan|portscan)""")
        if (affirmativePattern.containsMatchIn(lower)) {
            return ParsedIntent(IntentType.ContextualFollowUp, originalInput = trimmed)
        }

        // 5. Check conversational patterns
        chatPatterns.forEachIndexed { index, pattern ->
            if (pattern.containsMatchIn(lower)) {
                return ParsedIntent(IntentType.Conversation(index), originalInput = trimmed)
            }
        }

        // 6. No match found
        return ParsedIntent(IntentType.Unknown, originalInput = trimmed)
    }

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

    // ──────────────────────────────────────────────────────────────────
    // Pattern Definitions
    // ──────────────────────────────────────────────────────────────────

    /** Set of exact command strings */
    private val exactCommands = setOf(
        "help", "tools", "aliases", "status", "clear",
        "hey", "hi", "hello", "yo", "sup", "what's up",
        "good morning", "good night"
    )

    /**
     * Tool dispatch regex patterns.
     * Order matters — more specific patterns should come first.
     */
    private val toolDispatchPatterns = listOf(
        // ── Network Scanning ──────────────────────────────────────────
        Regex("""^scan\s+([\d./]+)"""),
        Regex("""^port ?scan\s+([\w.:]+)"""),
        Regex("""^ps\s+([\w.:]+)"""),
        Regex("""^lan ?scan\s*([\d./]*)"""),
        Regex("""^netbios\s+([\d./]+)"""),
        Regex("""^wifi ?scan"""),
        Regex("""^traceroute\s+([\w.-]+)"""),
        Regex("""^nmap\s+([\w./:-]+)"""),
        Regex("""^arp ?scan"""),
        Regex("""^ssh ?audit\s+([\w.-]+)"""),
        Regex("""^masscan\s+([\w./:-]+)"""),
        Regex("""^rping\s+([\w.-]+)"""),
        Regex("""^sniff"""),
        Regex("""^topology"""),
        Regex("""^legion\s+([\w.-]+)"""),

        // ── DNS & Web ─────────────────────────────────────────────────
        Regex("""^dns\s+([\w.-]+)"""),
        Regex("""^subdomain\s+([\w.-]+)"""),
        Regex("""^http\s+(https?://[\w./:?=&-]+)"""),
        Regex("""^fuzz\s+(https?://[\w./:?=&-]+)"""),
        Regex("""^sqli\s+(https?://[\w./?=&-]+)"""),
        Regex("""^xss\s+(https?://[\w./?=&-]+)"""),
        Regex("""^cors\s+(https?://[\w./:?=&-]+)"""),
        Regex("""^headers?\s+(https?://[\w./:?=&-]+)"""),
        Regex("""^jwt\s+(\S+)"""),
        Regex("""^nikto\s+([\w.-]+)"""),
        Regex("""^sqlmap\s+(https?://[\w./?=&-]+)"""),

        // ── OSINT ─────────────────────────────────────────────────────
        Regex("""^shodan\s+(.+)"""),
        Regex("""^shodan\s+ip\s+([\w.]+)"""),
        Regex("""^harvest\s+([\w.-]+)"""),
        Regex("""^hibp\s+(\S+@\S+)"""),
        Regex("""^hunter\s+([\w.-]+)"""),

        // ── Exploit / Attack ──────────────────────────────────────────
        Regex("""^brute\s+(ssh|ftp|http)\s+([\w./:]+)"""),
        Regex("""^hydra\s+([\w.]+)\s+(\w+)"""),
        Regex("""^payload\s+(\w+)\s+([\d.]+)\s+(\d+)"""),
        Regex("""^reverse ?shell\s+(\w+)\s+([\d.]+)\s+(\d+)"""),

        // ── LPE & Lateral Movement ─────────────────────────────────────
        Regex("""^(linpeas|enumerate\s+lpe)"""),
        Regex("""^winpeas\s+([\w.]+)"""),
        Regex("""^(bloodhound|attack\s+paths?)"""),
        Regex("""^(cme\s+([\w.]+)|crackmapexec)"""),

        // ── Cloud Security ────────────────────────────────────────────
        Regex("""^aws\s+(?:inspect|inspector|scan|asset)"""),
        Regex("""^gcp\s+(?:asset|scan)"""),
        Regex("""^azure\s+(?:ad|scan)"""),

        // ── Utility ───────────────────────────────────────────────────
        Regex("""^crack\s+([a-fA-F0-9]{32,128})"""),
        Regex("""^password ?gen"""),
        Regex("""^encode\s+(\w+)\s+(.+)"""),
        Regex("""^decode\s+(\w+)\s+(.+)"""),
        Regex("""^subnet\s+([\d./]+)"""),
        Regex("""^hash\s+(.+)"""),
        Regex("""^cipher\s+(\w+)\s+(.+)"""),
        Regex("""^rot13\s+(.+)"""),
        Regex("""^regex\s+(.+?)\s+(?:against|on|in)\s+(.+)"""),
    )

    /**
     * Natural language tool patterns for fuzzy intent matching.
     */
    private val nlToolPatterns = listOf(
        Regex("""(scan|check|sweep|probe|who.s|what.s|show|list).*(my\s+)?(network|lan|wifi|subnet|local|devices|connected)"""),
        Regex("""(scan|check)\s+(the\s+)?ports?\s+(on\s+)?([\w.:]+)"""),
        Regex("""what.s? (ports?|services?)\s+(are\s+)?(open|running)\s+(on\s+)?([\w.:]+)"""),
        Regex("""(trace|traceroute|trace route)\s+(to\s+)?([\w.-]+)"""),
        Regex("""(nearby|available|around)\s+wifi"""),
        Regex("""(generate|create|make|give me)\s+(a\s+)?(strong\s+|secure\s+|random\s+)?password"""),
        Regex("""(generate|create|make)\s+(a\s+)?(hash|md5|sha)"""),
    )

    /**
     * Conversational patterns for educational and chat responses.
     */
    private val chatPatterns = listOf(
        // Security education
        Regex("""what is a? ?port scan"""),
        Regex("""what is an? ?ip ?address"""),
        Regex("""what is a? ?dns"""),
        Regex("""what is (ssl|tls|https)"""),
        Regex("""what is a? ?subnet"""),
        Regex("""what is a? ?firewall"""),
        Regex("""what is ssh"""),
        Regex("""what is a? ?cve"""),
        Regex("""what is sql.?injection"""),
        Regex("""what is (xss|cross.?site)"""),
        Regex("""what is arp"""),
        Regex("""what is a? ?brute.?force"""),
        Regex("""what is a? ?hash"""),
        Regex("""what is a? ?reverse ?shell"""),
        Regex("""what is (netbios|smb)"""),
        Regex("""what is a? ?traceroute"""),
        Regex("""what is (wpa|wpa2|wpa3)"""),
        Regex("""what is a? ?payload"""),
        Regex("""what is nmap"""),
        Regex("""what is (jwt|json web token)"""),
        Regex("""what is cors"""),
        Regex("""what is metasploit"""),
        Regex("""what is a? ?vpn"""),
        Regex("""what is phishing"""),
        Regex("""what is a? ?zero.?day"""),
        Regex("""what is ransomware"""),
        Regex("""what is a? ?man.?in.?the.?middle"""),
        Regex("""what is (a )?dos|what is ddos"""),
        Regex("""what is social engineering"""),
        Regex("""what is a? ?honeypot"""),
        
        // Networking concepts
        Regex("""what is (a )?router"""),
        Regex("""what is (a )?gateway"""),
        Regex("""what is (a )?mac address"""),
        Regex("""what is (a )?dhcp"""),
        Regex("""what is (a )?nat"""),
        Regex("""what is (a )?tcp"""),
        Regex("""what is (a )?udp"""),
        Regex("""what is (a )?icmp"""),
        Regex("""what is (a )?packet"""),
        Regex("""what is (a )?proxy"""),
        Regex("""what is (a )?port"""),
        Regex("""what is (a )?cidr"""),
        Regex("""what is (a )?vlan"""),
        Regex("""what is (a )?ttl"""),
        Regex("""what is (a )?banner grab"""),
        Regex("""what is (a )?ping"""),
        Regex("""what is (a )?open port"""),
        Regex("""what is (a )?closed port"""),
        Regex("""what is (a )?filtered port"""),
        Regex("""what is (a )?service"""),
        Regex("""what is (a )?network scan"""),
        Regex("""what is (a )?packet sniffer"""),
        Regex("""what is (a )?deauth"""),
        Regex("""what is (a )?evil twin"""),
        Regex("""what is (a )?masscan"""),
        Regex("""what is (a )?legion"""),
        Regex("""what is (a )?hydra"""),
        Regex("""what is (a )?nikto"""),
        Regex("""what is (a )?sqlmap"""),
        Regex("""what is (a )?directory fuzz"""),
        Regex("""what is (a )?subdomain"""),
        Regex("""what is (a )?dns recon"""),
        Regex("""what is (a )?ssh audit"""),
        Regex("""what is (a )?arp spoof"""),
        Regex("""what is (a )?network topology"""),
        Regex("""what is (a )?rping"""),
        Regex("""what is (a )?wifi scan"""),
        
        // Learn commands
        Regex("""^learn ports?"""),
        Regex("""^learn (web|http)"""),
        Regex("""^learn scanning"""),
    )
}
