use anyhow::Result;
use regex::Regex;
use std::path::Path;
use uuid::Uuid;

use crate::rules::{Rule, RulePattern};
use crate::types::{Language, Location, Severity, Vulnerability, VulnerabilityType};

/// Pattern-based analyzer using regex matching
pub struct PatternMatcher {
    compiled_patterns: Vec<CompiledPattern>,
}

struct CompiledPattern {
    regex: Regex,
    vuln_type: VulnerabilityType,
    severity: Severity,
    description: String,
    recommendation: String,
    cwe_id: Option<String>,
}

impl PatternMatcher {
    pub fn new() -> Self {
        Self {
            compiled_patterns: Self::compile_default_patterns(),
        }
    }

    /// Check if the matched crypto term is in an informational/documentation context
    /// rather than actual cryptographic usage. Returns true if this appears to be
    /// just documentation and should NOT be flagged as a vulnerability.
    fn is_informational_string(&self, source: &str, match_start: usize, match_end: usize) -> bool {
        // Get the line containing the match
        let line_start = source[..match_start].rfind('\n').map(|p| p + 1).unwrap_or(0);
        let line_end = source[match_end..].find('\n').map(|p| match_end + p).unwrap_or(source.len());
        let line = &source[line_start..line_end];
        let line_lower = line.to_lowercase();
        
        // First, check if this match is INSIDE a string literal with informational content
        // Find the string boundaries around this match
        let match_offset_in_line = match_start - line_start;
        
        // Look for string delimiters before and after the match position
        // Note: match_offset_in_line is the position of the FIRST character of the match
        // So we want to count quotes UP TO (but not including) this position
        let before_match = &line[..match_offset_in_line];
        
        // Count quotes to determine if we're inside a string
        // We need to count escaped quotes differently, but for simplicity well just count all quotes
        let quote_count_before_single = before_match.matches('\'').count();
        let quote_count_before_double = before_match.matches('"').count();
        
        // If we're inside a string (odd number of quotes before us)
        let inside_single_quote = quote_count_before_single % 2 == 1;
        let inside_double_quote = quote_count_before_double % 2 == 1;
        
        if inside_single_quote || inside_double_quote {
            // We're inside a string literal. Check if the string CONTENT is informational
            // Phrases that indicate documentation/informational content (NOT actual usage)
            let documentation_indicators = [
                // Explanatory phrases that suggest documentation, not usage
                " is a ", " is an ", " is the ", " are the ",
                " was a ", " was an ", " was the ", " were the ",
                " provides ", " enables ", " allows ",
                " named after ", " stands for ", " means ",
                " public-key ", " public key ", " cryptosystem ",
                " deprecated for ", " vulnerable to ",
                // Comparative phrases that suggest documentation
                " than ", "compared to", "instead of", "rather than",
                // Description phrases  
                "known as", "referred to", "also called",
                // Warning/deprecation phrases - these clearly indicate documentation
                " is broken", " is deprecated", " is insecure", " is weak",
                " is completely broken", " is cryptographically broken",
                " is quantum-vulnerable", " is vulnerable",
                " should not be used", " must not be used", " do not use",
                " should be avoided", " must be avoided", " avoid using",
                " has been broken", " has been deprecated", " has been compromised",
                " no longer secure", " no longer safe", " not recommended",
                " being replaced", " being deprecated", " being phased out",
                // Upgrade/migration documentation
                "upgrade to", "migrate to", "migrate from", "replace with",
                "transition to", "switch to", "move to", "moving to",
                // Shorter signatures/faster - explanatory content
                " provides shorter", " provides faster", " provides better",
                "shorter signatures", "smaller keys", "faster than",
                // Error and warning messages - not actual usage
                " failed:", " error:", "warning:", "error: ",
                "encryption failed", "decryption failed", "signature failed",
                "key too short", "key too long", "key size", "invalid key",
                "unsupported algorithm", "deprecated algorithm", "weak algorithm",
                // Logging/status messages - not actual usage
                "using ", " for encryption", " for decryption", " for signing",
                " for hashing", " for key", "generated ", " computed",
                " hash computed", " key pair", "key generated", "encrypted",
            ];
            
            // Check if any documentation indicator is present in the string content
            for indicator in documentation_indicators {
                if line_lower.contains(indicator) {
                    return true;  // This is informational content
                }
            }
        }
        
        // NOTE: We deliberately do NOT filter out "deprecated_algorithms" lists or similar
        // configurations because those ARE legitimate vulnerabilities to report - the code
        // is actively defining which algorithms to use.
        
        false
    }

    fn compile_default_patterns() -> Vec<CompiledPattern> {
        let patterns = vec![
            // RSA patterns
            (
                r"(?i)\bRSA[\s\-_]*(OAEP|PSS|PKCS1|2048|4096|1024)?\b",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "RSA cryptography detected",
                "Migrate to CRYSTALS-Kyber (ML-KEM)",
                Some("CWE-327"),
            ),
            (
                r#"(?i)generateKeyPair\s*\(\s*['"]rsa['"]"#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "RSA key pair generation",
                "Use Kyber for key encapsulation",
                Some("CWE-327"),
            ),
            (
                r"(?i)crypto\.publicEncrypt|crypto\.privateDecrypt",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "RSA encryption/decryption",
                "Migrate to hybrid encryption with Kyber",
                Some("CWE-327"),
            ),
            // ECDSA/ECDH patterns
            (
                r"(?i)\b(ECDSA|ECDH|secp256k1|secp384r1|secp521r1|P-256|P-384|P-521|prime256v1)\b",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Elliptic curve cryptography detected",
                "Migrate to CRYSTALS-Dilithium or Kyber",
                Some("CWE-327"),
            ),
            (
                r"(?i)createECDH|EC_KEY_new|ecdsa\.GenerateKey",
                VulnerabilityType::Ecdh,
                Severity::Critical,
                "ECDH key exchange detected",
                "Replace with Kyber KEM",
                Some("CWE-327"),
            ),
            // DSA patterns
            (
                r"(?i)\bDSA\b(?!\.)|DSA_sign|DSA_verify",
                VulnerabilityType::Dsa,
                Severity::Critical,
                "DSA signature algorithm detected",
                "Migrate to Dilithium or SPHINCS+",
                Some("CWE-327"),
            ),
            // Diffie-Hellman patterns
            (
                r"(?i)createDiffieHellman|getDiffieHellman|DH_generate_key|DH_compute_key|modp\d+",
                VulnerabilityType::DhKeyExchange,
                Severity::Critical,
                "Diffie-Hellman key exchange detected",
                "Replace with Kyber KEM",
                Some("CWE-327"),
            ),
            // SHA-1 patterns
            (
                r#"(?i)createHash\s*\(\s*['"]sha1['"]|SHA1_Init|sha1\.New\(\)|MessageDigest\.getInstance\s*\(\s*['"]SHA-?1['"]\)"#,
                VulnerabilityType::Sha1,
                Severity::High,
                "SHA-1 hash function detected",
                "Replace with SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            // MD5 patterns
            (
                r#"(?i)createHash\s*\(\s*['"]md5['"]|MD5_Init|md5\.New\(\)|MessageDigest\.getInstance\s*\(\s*['"]MD5['"]\)"#,
                VulnerabilityType::Md5,
                Severity::High,
                "MD5 hash function detected",
                "Replace with SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            // DES patterns
            (
                r"(?i)\b(3DES|DES-?EDE|TripleDES|DESede)\b",
                VulnerabilityType::TripleDes,
                Severity::Medium,
                "3DES encryption detected",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r#"(?i)\bDES\b(?!3|ede)|des-cbc|des-ecb|DES_encrypt"#,
                VulnerabilityType::Des,
                Severity::Critical,
                "DES encryption detected",
                "Replace with AES-256-GCM immediately",
                Some("CWE-327"),
            ),
            // RC4 patterns
            (
                r"(?i)\b(RC4|ARC4|ARCFOUR)\b",
                VulnerabilityType::Rc4,
                Severity::Critical,
                "RC4 stream cipher detected",
                "Replace with AES-256-GCM or ChaCha20-Poly1305",
                Some("CWE-327"),
            ),
            // Weak random patterns
            (
                r"Math\.random\s*\(\)|random\.random\s*\(\)|\brand\s*\(\s*\)|srand\s*\(",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Weak random number generator detected",
                "Use cryptographically secure RNG",
                Some("CWE-338"),
            ),
            // Insecure TLS patterns
            (
                r"(?i)(SSLv2|SSLv3|TLSv1\.0|TLSv1\.1|ssl_version\s*=\s*2|ssl_version\s*=\s*3)",
                VulnerabilityType::InsecureTls,
                Severity::High,
                "Insecure TLS/SSL version detected",
                "Use TLS 1.3",
                Some("CWE-326"),
            ),

            // ===== PHP-specific patterns =====
            (
                r"(?i)\bopenssl_pkey_new\s*\(|openssl_sign\s*\(|openssl_verify\s*\(",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "PHP OpenSSL RSA/signing function detected",
                "Migrate to post-quantum alternatives",
                Some("CWE-327"),
            ),
            (
                r#"(?i)['"]rsa['"]|['"]RSA['"]|OPENSSL_KEYTYPE_RSA"#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "PHP RSA algorithm identifier",
                "Replace with PQC algorithms",
                Some("CWE-327"),
            ),
            (
                r#"(?i)openssl_encrypt\s*\([^,]*,\s*['"]des|openssl_decrypt\s*\([^,]*,\s*['"]des"#,
                VulnerabilityType::Des,
                Severity::Critical,
                "PHP DES encryption usage",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r#"(?i)\bmd5\s*\(|hash\s*\(\s*['"]md5['"]\s*,"#,
                VulnerabilityType::Md5,
                Severity::High,
                "PHP MD5 hash function",
                "Replace with hash('sha256', ...) or hash('sha3-256', ...)",
                Some("CWE-328"),
            ),
            (
                r#"(?i)\bsha1\s*\(|hash\s*\(\s*['"]sha1['"]\s*,"#,
                VulnerabilityType::Sha1,
                Severity::High,
                "PHP SHA1 hash function",
                "Replace with hash('sha256', ...) or hash('sha3-256', ...)",
                Some("CWE-328"),
            ),
            (
                r"(?i)\bmt_rand\s*\(|\brand\s*\(",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "PHP weak random function",
                "Use random_bytes() or random_int() for cryptographic purposes",
                Some("CWE-338"),
            ),

            // ===== Ruby-specific patterns =====
            (
                r"(?i)OpenSSL::PKey::RSA\.|OpenSSL::PKey::RSA\.new|rsa\.sign|rsa\.verify",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Ruby OpenSSL RSA usage",
                "Migrate to post-quantum cryptography",
                Some("CWE-327"),
            ),
            (
                r"(?i)OpenSSL::PKey::EC\.|OpenSSL::PKey::EC\.new|ec\.sign",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Ruby OpenSSL EC cryptography",
                "Migrate to Dilithium or other PQC signatures",
                Some("CWE-327"),
            ),
            (
                r#"(?i)OpenSSL::Cipher\.new\s*\(['"]des|OpenSSL::Cipher\.new\s*\(['"]DES"#,
                VulnerabilityType::Des,
                Severity::Critical,
                "Ruby DES cipher usage",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r"(?i)Digest::MD5\.|OpenSSL::Digest::MD5\.|\.md5",
                VulnerabilityType::Md5,
                Severity::High,
                "Ruby MD5 digest usage",
                "Use Digest::SHA256 or Digest::SHA3",
                Some("CWE-328"),
            ),
            (
                r"(?i)Digest::SHA1\.|OpenSSL::Digest::SHA1\.|\.sha1",
                VulnerabilityType::Sha1,
                Severity::High,
                "Ruby SHA1 digest usage",
                "Use Digest::SHA256 or Digest::SHA3",
                Some("CWE-328"),
            ),
            (
                r"(?i)\brand\s*\(|\bRandom\.rand\s*\(",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Ruby weak random function",
                "Use SecureRandom for cryptographic purposes",
                Some("CWE-338"),
            ),

            // ===== Kotlin-specific patterns =====
            (
                r#"(?i)KeyPairGenerator\.getInstance\s*\(\s*['"]RSA['"]\s*\)|Cipher\.getInstance\s*\([^)]*RSA[^)]*\)"#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Kotlin RSA cryptography usage",
                "Use BouncyCastle PQC provider",
                Some("CWE-327"),
            ),
            (
                r#"(?i)KeyPairGenerator\.getInstance\s*\(\s*['"]EC['"]\s*\)|Signature\.getInstance\s*\([^)]*ECDSA[^)]*\)"#,
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Kotlin EC cryptography usage",
                "Use BouncyCastle PQC provider",
                Some("CWE-327"),
            ),
            (
                r#"(?i)MessageDigest\.getInstance\s*\(\s*['"]MD5['"]\s*\)"#,
                VulnerabilityType::Md5,
                Severity::High,
                "Kotlin MD5 hash function",
                "Use SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            (
                r#"(?i)MessageDigest\.getInstance\s*\(\s*['"]SHA-?1['"]\s*\)"#,
                VulnerabilityType::Sha1,
                Severity::High,
                "Kotlin SHA-1 hash function",
                "Use SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            (
                r"(?i)Random\s*\(\s*\)\.|kotlin\.random\.Random(?!\.Secure)",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Kotlin weak random usage",
                "Use SecureRandom for cryptographic purposes",
                Some("CWE-338"),
            ),

            // ===== Swift-specific patterns =====
            (
                r"(?i)SecKeyCreateRandomKey|SecKeyAlgorithm\.rsaEncryption|kSecAttrKeyTypeRSA",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Swift RSA key generation/usage",
                "Migrate to post-quantum cryptography when available in CryptoKit",
                Some("CWE-327"),
            ),
            (
                r"(?i)P256\.|P384\.|P521\.|kSecAttrKeyTypeEC|SecKeyAlgorithm\.ecies",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Swift elliptic curve cryptography",
                "Migrate to post-quantum alternatives",
                Some("CWE-327"),
            ),
            (
                r"(?i)CC_MD5|Insecure\.MD5|CommonCrypto.*MD5",
                VulnerabilityType::Md5,
                Severity::High,
                "Swift MD5 hash function",
                "Use SHA256 or SHA512 from CryptoKit",
                Some("CWE-328"),
            ),
            (
                r"(?i)CC_SHA1|Insecure\.SHA1|CommonCrypto.*SHA1",
                VulnerabilityType::Sha1,
                Severity::High,
                "Swift SHA-1 hash function",
                "Use SHA256 or SHA512 from CryptoKit",
                Some("CWE-328"),
            ),
            (
                r"(?i)arc4random\s*\(",
                VulnerabilityType::WeakRandom,
                Severity::Medium,
                "Swift arc4random usage (deprecated)",
                "Use SystemRandomNumberGenerator from Swift 5+",
                Some("CWE-338"),
            ),
            // Additional Swift RSA signing patterns
            (
                r"(?i)\.rsaSignatureMessage|rsaEncryption|SecKeyAlgorithm\.rsa",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Swift RSA signing/encryption algorithm",
                "Migrate to post-quantum signatures",
                Some("CWE-327"),
            ),
            // Swift ECDSA patterns
            (
                r"(?i)\.ecdsaSignature|SecKeyAlgorithm\.ecdsa",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Swift ECDSA signing algorithm",
                "Migrate to Dilithium signatures",
                Some("CWE-327"),
            ),
            // Swift ECDH patterns
            (
                r"(?i)\.ecdhKeyExchange|SecKeyCopyKeyExchangeResult",
                VulnerabilityType::Ecdh,
                Severity::Critical,
                "Swift ECDH key exchange",
                "Migrate to Kyber KEM",
                Some("CWE-327"),
            ),
            // Swift DSA patterns
            (
                r#"(?i)\bDSAConfig\b|algorithm\s*=\s*['"]DSA['"]"#,
                VulnerabilityType::Dsa,
                Severity::Critical,
                "Swift DSA configuration",
                "Migrate to Dilithium or SPHINCS+",
                Some("CWE-327"),
            ),
            // Swift DES/3DES patterns
            (
                r"(?i)kCCAlgorithmDES|kCCAlgorithm3DES|CCCryptorCreate.*DES",
                VulnerabilityType::Des,
                Severity::Critical,
                "Swift CommonCrypto DES usage",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            // Swift RC4 patterns
            (
                r"(?i)kCCAlgorithmRC4|CCCryptorCreate.*RC4",
                VulnerabilityType::Rc4,
                Severity::Critical,
                "Swift CommonCrypto RC4 usage",
                "Replace with AES-256-GCM or ChaCha20",
                Some("CWE-327"),
            ),
            // Swift weak random patterns
            (
                r"(?i)\bsrand48\s*\(|\bdrand48\s*\(",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Swift srand48/drand48 (weak RNG)",
                "Use SecRandomCopyBytes or SystemRandomNumberGenerator",
                Some("CWE-338"),
            ),
            // Swift HMAC algorithm patterns
            (
                r"(?i)kCCHmacAlgSHA1|CCHmac.*SHA1",
                VulnerabilityType::Sha1,
                Severity::High,
                "Swift HMAC with SHA-1",
                "Use SHA-256 or SHA-3 HMAC",
                Some("CWE-328"),
            ),
            (
                r"(?i)kCCHmacAlgMD5|CCHmac.*MD5",
                VulnerabilityType::Md5,
                Severity::High,
                "Swift HMAC with MD5",
                "Use SHA-256 or SHA-3 HMAC",
                Some("CWE-328"),
            ),
            // Swift SecKeyGeneratePair (general pattern)
            (
                r"(?i)SecKeyGeneratePair\s*\(",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Swift key pair generation",
                "Review for quantum-vulnerable algorithms",
                Some("CWE-327"),
            ),

            // ===== Shell/Bash-specific patterns =====
            (
                r"(?i)openssl\s+rsa|openssl\s+genrsa|openssl\s+pkeyutl.*-pkeyopt\s+rsa",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Shell script RSA operations via openssl",
                "Plan migration to PQC tools",
                Some("CWE-327"),
            ),
            (
                r"(?i)openssl\s+ec\s|openssl\s+ecparam|ecdsa-",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Shell script EC operations via openssl",
                "Plan migration to PQC alternatives",
                Some("CWE-327"),
            ),
            (
                r"(?i)openssl\s+dgst\s+-md5|md5sum\s|md5\s+-",
                VulnerabilityType::Md5,
                Severity::High,
                "Shell script MD5 hash usage",
                "Use sha256sum or sha3sum",
                Some("CWE-328"),
            ),
            (
                r"(?i)openssl\s+dgst\s+-sha1|sha1sum\s",
                VulnerabilityType::Sha1,
                Severity::High,
                "Shell script SHA-1 hash usage",
                "Use sha256sum or sha3sum",
                Some("CWE-328"),
            ),
            (
                r"(?i)openssl\s+des3?|openssl\s+enc\s+-des",
                VulnerabilityType::Des,
                Severity::Critical,
                "Shell script DES encryption",
                "Use openssl enc -aes-256-gcm",
                Some("CWE-327"),
            ),
            (
                r"\$RANDOM|\$\{RANDOM\}",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Shell $RANDOM variable (weak randomness)",
                "Use /dev/urandom or openssl rand",
                Some("CWE-338"),
            ),

            // ===== Lua-specific patterns =====
            (
                r#"(?i)require\s*[(\[]*\s*['"]rsa['"]|require\s*[(\[]*\s*['"]crypto['"]"#,
                VulnerabilityType::Rsa2048,
                Severity::Medium,
                "Lua crypto library import",
                "Review for quantum-vulnerable cryptography",
                Some("CWE-327"),
            ),
            (
                r"(?i)digest\s*\.\s*md5|md5\s*\(|:md5\s*\(",
                VulnerabilityType::Md5,
                Severity::High,
                "Lua MD5 hash function",
                "Use SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            (
                r"(?i)digest\s*\.\s*sha1|sha1\s*\(|:sha1\s*\(",
                VulnerabilityType::Sha1,
                Severity::High,
                "Lua SHA-1 hash function",
                "Use SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            (
                r"(?i)math\s*\.\s*random\s*\(|random\s*\(",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Lua math.random (weak RNG)",
                "Use a cryptographically secure RNG library",
                Some("CWE-338"),
            ),
            (
                r"(?i)des\s*\.|des3\s*\.|cipher\s*\.\s*des",
                VulnerabilityType::Des,
                Severity::Critical,
                "Lua DES cipher usage",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r"(?i)rsa\s*\.|rsa\s*\(|:rsa\s*\(",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Lua RSA cryptography usage",
                "Migrate to post-quantum alternatives",
                Some("CWE-327"),
            ),
            // Lua crypto.pkey.generate patterns
            (
                r#"(?i)crypto\.pkey\.generate\s*\(\s*['"]RSA['"]"#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Lua RSA key generation",
                "Migrate to post-quantum key exchange",
                Some("CWE-327"),
            ),
            (
                r#"(?i)crypto\.pkey\.generate\s*\(\s*['"]EC['"]"#,
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Lua EC key generation",
                "Migrate to post-quantum signatures",
                Some("CWE-327"),
            ),
            (
                r#"(?i)crypto\.pkey\.generate\s*\(\s*['"]DSA['"]"#,
                VulnerabilityType::Dsa,
                Severity::Critical,
                "Lua DSA key generation",
                "Migrate to Dilithium or SPHINCS+",
                Some("CWE-327"),
            ),
            // Lua crypto.encrypt/decrypt patterns
            (
                r#"(?i)crypto\.(encrypt|decrypt)\s*\(\s*['"](RSA|RSA-OAEP)['"]"#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Lua RSA encryption/decryption",
                "Migrate to hybrid encryption with Kyber",
                Some("CWE-327"),
            ),
            (
                r#"(?i)crypto\.(encrypt|decrypt)\s*\(\s*['"]des"#,
                VulnerabilityType::Des,
                Severity::Critical,
                "Lua DES encryption",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r#"(?i)crypto\.(encrypt|decrypt)\s*\(\s*['"]rc4"#,
                VulnerabilityType::Rc4,
                Severity::Critical,
                "Lua RC4 encryption",
                "Replace with AES-256-GCM or ChaCha20",
                Some("CWE-327"),
            ),
            (
                r#"(?i)crypto\.(encrypt|decrypt)\s*\(\s*['"]arc4"#,
                VulnerabilityType::Rc4,
                Severity::Critical,
                "Lua ARC4 encryption",
                "Replace with AES-256-GCM or ChaCha20",
                Some("CWE-327"),
            ),
            // Lua crypto.sign/verify patterns
            (
                r#"(?i)crypto\.(sign|verify)\s*\(\s*['"]RSA"#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Lua RSA signing/verification",
                "Migrate to Dilithium signatures",
                Some("CWE-327"),
            ),
            (
                r#"(?i)crypto\.(sign|verify)\s*\(\s*['"]ECDSA['"]"#,
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Lua ECDSA signing/verification",
                "Migrate to Dilithium signatures",
                Some("CWE-327"),
            ),
            (
                r#"(?i)crypto\.(sign|verify)\s*\(\s*['"]DSA['"]"#,
                VulnerabilityType::Dsa,
                Severity::Critical,
                "Lua DSA signing/verification",
                "Migrate to Dilithium or SPHINCS+",
                Some("CWE-327"),
            ),
            // Lua crypto.derive patterns for ECDH
            (
                r#"(?i)crypto\.derive\s*\(\s*['"]ECDH['"]"#,
                VulnerabilityType::Ecdh,
                Severity::Critical,
                "Lua ECDH key derivation",
                "Migrate to Kyber KEM",
                Some("CWE-327"),
            ),
            // Lua Diffie-Hellman patterns
            (
                r"(?i)crypto\.dh\.",
                VulnerabilityType::DhKeyExchange,
                Severity::Critical,
                "Lua Diffie-Hellman operations",
                "Migrate to Kyber KEM",
                Some("CWE-327"),
            ),
            // Lua crypto.digest/hmac patterns for SHA-1/MD5
            (
                r#"(?i)crypto\.(digest|hmac)\s*\(\s*['"]sha1['"]"#,
                VulnerabilityType::Sha1,
                Severity::High,
                "Lua SHA-1 digest/HMAC",
                "Replace with SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            (
                r#"(?i)crypto\.(digest|hmac)\s*\(\s*['"]md5['"]"#,
                VulnerabilityType::Md5,
                Severity::High,
                "Lua MD5 digest/HMAC",
                "Replace with SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            // Lua digest.new patterns
            (
                r#"(?i)crypto\.digest\.new\s*\(\s*['"]sha1['"]"#,
                VulnerabilityType::Sha1,
                Severity::High,
                "Lua SHA-1 digest context",
                "Replace with SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            (
                r#"(?i)crypto\.digest\.new\s*\(\s*['"]md5['"]"#,
                VulnerabilityType::Md5,
                Severity::High,
                "Lua MD5 digest context",
                "Replace with SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            // Lua randomseed pattern
            (
                r"(?i)math\.randomseed\s*\(",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Lua math.randomseed (predictable seed)",
                "Use cryptographically secure RNG",
                Some("CWE-338"),
            ),

            // ===== Rust-specific patterns =====
            (
                r"(?i)use\s+rsa::|rsa::|RsaPrivateKey|RsaPublicKey",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Rust RSA crate usage",
                "Use pqcrypto crate for Kyber/Dilithium",
                Some("CWE-327"),
            ),
            (
                r"(?i)use\s+ecdsa::|ecdsa::|use\s+p256|use\s+p384|SigningKey|VerifyingKey",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Rust ECDSA crate usage",
                "Use pqcrypto crate for PQC signatures",
                Some("CWE-327"),
            ),
            (
                r"(?i)use\s+des::|Des::|TripleDes::",
                VulnerabilityType::Des,
                Severity::Critical,
                "Rust DES crate usage",
                "Replace with aes_gcm crate",
                Some("CWE-327"),
            ),
            (
                r"(?i)use\s+md5::|Md5::|md5::Md5",
                VulnerabilityType::Md5,
                Severity::High,
                "Rust MD5 crate usage",
                "Use sha2::Sha256 or sha3 crate",
                Some("CWE-328"),
            ),
            (
                r"(?i)use\s+sha1::|Sha1::|sha1::Sha1",
                VulnerabilityType::Sha1,
                Severity::High,
                "Rust SHA-1 crate usage",
                "Use sha2::Sha256 or sha3 crate",
                Some("CWE-328"),
            ),
            (
                r"(?i)thread_rng\(\)\.gen|rand::random\(",
                VulnerabilityType::WeakRandom,
                Severity::Medium,
                "Rust non-cryptographic RNG",
                "Use OsRng or getrandom for crypto operations",
                Some("CWE-338"),
            ),
            // Rust DSA patterns
            (
                r"(?i)\bdsa_sign\s*\(|\bdsa_verify\s*\(|\bgenerate_dsa_key\s*\(",
                VulnerabilityType::Dsa,
                Severity::Critical,
                "Rust DSA function",
                "Migrate to Dilithium or SPHINCS+",
                Some("CWE-327"),
            ),
            (
                r"(?i)\bDSAKeyPair\b|\bDSA_sign\b|\bDSA_verify\b",
                VulnerabilityType::Dsa,
                Severity::Critical,
                "Rust DSA type/function",
                "Migrate to Dilithium or SPHINCS+",
                Some("CWE-327"),
            ),
            // Rust Diffie-Hellman patterns
            (
                r"(?i)\bdh_generate_key\s*\(|\bdh_compute_key\s*\(",
                VulnerabilityType::DhKeyExchange,
                Severity::Critical,
                "Rust DH key operation",
                "Migrate to Kyber KEM",
                Some("CWE-327"),
            ),
            (
                r"(?i)\bDHParameters\b|\bget_modp\d+",
                VulnerabilityType::DhKeyExchange,
                Severity::Critical,
                "Rust DH parameters/modp group",
                "Migrate to Kyber KEM",
                Some("CWE-327"),
            ),
            // Rust RC4 patterns
            (
                r"(?i)use\s+rc4::|Rc4::|rc4::Rc4",
                VulnerabilityType::Rc4,
                Severity::Critical,
                "Rust RC4 crate usage",
                "Replace with ChaCha20-Poly1305 or AES-GCM",
                Some("CWE-327"),
            ),
            // Rust 3DES patterns
            (
                r"(?i)\b3DES\b|des-ede3|des_ede3",
                VulnerabilityType::TripleDes,
                Severity::Medium,
                "Rust 3DES usage",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            // Rust srand/seed patterns
            (
                r"(?i)\bsrand\s*\(|\bstatic\s+mut\s+SEED\b",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Rust predictable seed/srand pattern",
                "Use OsRng or getrandom for crypto operations",
                Some("CWE-338"),
            ),
            // Rust SHA-1 hasher pattern
            (
                r"(?i)\bSHA1Hasher\b|\bSha1Hasher\b",
                VulnerabilityType::Sha1,
                Severity::High,
                "Rust SHA-1 hasher struct",
                "Use sha2::Sha256 or sha3 crate",
                Some("CWE-328"),
            ),
            // Rust MD5 hasher pattern
            (
                r"(?i)\bMD5Hasher\b|\bMd5Hasher\b",
                VulnerabilityType::Md5,
                Severity::High,
                "Rust MD5 hasher struct",
                "Use sha2::Sha256 or sha3 crate",
                Some("CWE-328"),
            ),
            // Rust TLS version enum patterns
            (
                r"(?i)\bTlsVersion\b|\bSSLv\d\b|\bTLSv1_\d\b",
                VulnerabilityType::InsecureTls,
                Severity::High,
                "Rust TLS version configuration",
                "Use TLS 1.3 with PQC-ready cipher suites",
                Some("CWE-326"),
            ),

            // ===== Perl-specific patterns =====
            (
                r"(?i)use\s+Crypt::RSA|Crypt::RSA->new|rsa->sign",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Perl Crypt::RSA module usage",
                "Migrate to post-quantum cryptography",
                Some("CWE-327"),
            ),
            (
                r"(?i)use\s+Digest::MD5|Digest::MD5->new|md5_hex\s*\(|md5_base64\s*\(",
                VulnerabilityType::Md5,
                Severity::High,
                "Perl Digest::MD5 usage",
                "Use Digest::SHA qw(sha256_hex)",
                Some("CWE-328"),
            ),
            (
                r"(?i)use\s+Digest::SHA1|Digest::SHA1->new|sha1_hex\s*\(|sha1_base64\s*\(",
                VulnerabilityType::Sha1,
                Severity::High,
                "Perl Digest::SHA1 usage",
                "Use Digest::SHA qw(sha256_hex)",
                Some("CWE-328"),
            ),
            (
                r"(?i)use\s+Crypt::DES|Crypt::DES->new",
                VulnerabilityType::Des,
                Severity::Critical,
                "Perl Crypt::DES usage",
                "Replace with Crypt::Rijndael (AES)",
                Some("CWE-327"),
            ),
            (
                r"(?i)\brand\s*\(|\$\s*rand\s*\(|int\s*\(\s*rand",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Perl rand() function (weak RNG)",
                "Use Crypt::Random or /dev/urandom",
                Some("CWE-338"),
            ),
            (
                r"(?i)use\s+Crypt::OpenSSL::RSA|OpenSSL::RSA->new",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Perl OpenSSL RSA bindings",
                "Plan migration to PQC",
                Some("CWE-327"),
            ),

            // ===== Go-specific patterns =====
            (
                r"(?i)crypto/rsa|crypto/ecdsa|crypto/ecdh|rsa\.GenerateKey|ecdsa\.GenerateKey",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Go RSA/ECDSA crypto package usage",
                "Use post-quantum cryptography libraries",
                Some("CWE-327"),
            ),
            (
                r#"(?i)rsa\.(Encrypt|Decrypt|Sign|Verify)|ecdsa\.(Sign|Verify)|ecdh\.(GenerateKey|ComputeSecret)"#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Go RSA/ECDSA/ECDH operations",
                "Migrate to PQC alternatives",
                Some("CWE-327"),
            ),
            (
                r"(?i)crypto/md5|crypto/sha1|md5\.New\(\)|sha1\.New\(\)",
                VulnerabilityType::Md5,
                Severity::High,
                "Go MD5/SHA-1 hash usage",
                "Use crypto/sha256 or crypto/sha512",
                Some("CWE-328"),
            ),
            (
                r"(?i)math/rand\.(Int|Float|Seed)|rand\.(Int|Float|Seed)",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Go math/rand usage (weak RNG)",
                "Use crypto/rand for cryptographic purposes",
                Some("CWE-338"),
            ),
            (
                r"(?i)des\.NewCipher|des\.NewTripleDESCipher",
                VulnerabilityType::Des,
                Severity::Critical,
                "Go DES cipher usage",
                "Replace with crypto/aes",
                Some("CWE-327"),
            ),
            (
                r"(?i)tls\.Config.*MinVersion.*VersionTLS10|tls\.Config.*MinVersion.*VersionTLS11",
                VulnerabilityType::InsecureTls,
                Severity::High,
                "Go insecure TLS version",
                "Use TLS 1.2 or higher",
                Some("CWE-326"),
            ),

            // ===== Java-specific patterns =====
            (
                r#"(?i)KeyPairGenerator\.getInstance\s*\(\s*['"]RSA['"]|Cipher\.getInstance\s*\([^)]*RSA[^)]*\)"#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Java RSA cryptography",
                "Use BouncyCastle PQC provider",
                Some("CWE-327"),
            ),
            (
                r#"(?i)KeyPairGenerator\.getInstance\s*\(\s*['"]EC['"]|Signature\.getInstance\s*\([^)]*ECDSA[^)]*\)"#,
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Java EC cryptography",
                "Use BouncyCastle PQC provider",
                Some("CWE-327"),
            ),
            (
                r#"(?i)KeyAgreement\.getInstance\s*\(\s*['"]ECDH['"]"#,
                VulnerabilityType::Ecdh,
                Severity::Critical,
                "Java ECDH key agreement",
                "Migrate to Kyber KEM",
                Some("CWE-327"),
            ),
            (
                r#"(?i)MessageDigest\.getInstance\s*\(\s*['"]MD5['"]|MessageDigest\.getInstance\s*\(\s*['"]SHA-?1['"]"#,
                VulnerabilityType::Md5,
                Severity::High,
                "Java MD5/SHA-1 MessageDigest",
                "Use SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            (
                r#"(?i)KeyGenerator\.getInstance\s*\(\s*['"]DES['"]|Cipher\.getInstance\s*\([^)]*DES[^)]*\)"#,
                VulnerabilityType::Des,
                Severity::Critical,
                "Java DES cipher",
                "Replace with AES",
                Some("CWE-327"),
            ),
            (
                r#"(?i)KeyGenerator\.getInstance\s*\(\s*['"]DESede['"]|Cipher\.getInstance\s*\([^)]*DESede[^)]*\)"#,
                VulnerabilityType::TripleDes,
                Severity::Medium,
                "Java 3DES cipher",
                "Replace with AES-256",
                Some("CWE-327"),
            ),
            (
                r"(?i)new\s+Random\s*\(|Random\.next(Int|Long|Double|Float)",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Java Random class (weak RNG)",
                "Use SecureRandom for cryptographic purposes",
                Some("CWE-338"),
            ),
            (
                r#"(?i)SSLContext\.getInstance\s*\(\s*['"]TLSv1['"]|SSLContext\.getInstance\s*\(\s*['"]TLSv1\.1['"]"#,
                VulnerabilityType::InsecureTls,
                Severity::High,
                "Java insecure TLS version",
                "Use TLS 1.2 or higher",
                Some("CWE-326"),
            ),

            // ===== C/C++ specific patterns =====
            (
                r"(?i)RSA_generate_key|RSA_new|RSA_public_encrypt|RSA_private_decrypt",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "C/C++ OpenSSL RSA functions",
                "Migrate to post-quantum cryptography",
                Some("CWE-327"),
            ),
            (
                r"(?i)EC_KEY_new|EC_KEY_generate_key|ECDSA_sign|ECDSA_verify",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "C/C++ OpenSSL EC functions",
                "Migrate to PQC signatures",
                Some("CWE-327"),
            ),
            (
                r"(?i)EVP_PKEY_CTX_new_id\s*\(\s*EVP_PKEY_EC\s*\)|EC_GROUP_new_by_curve_name",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "C/C++ OpenSSL EC key operations",
                "Migrate to PQC",
                Some("CWE-327"),
            ),
            (
                r"(?i)DSA_generate_key|DSA_sign|DSA_verify",
                VulnerabilityType::Dsa,
                Severity::Critical,
                "C/C++ OpenSSL DSA functions",
                "Migrate to Dilithium or SPHINCS+",
                Some("CWE-327"),
            ),
            (
                r"(?i)DH_generate_key|DH_compute_key|EVP_PKEY_CTX_new_id\s*\(\s*EVP_PKEY_DH\s*\)",
                VulnerabilityType::DhKeyExchange,
                Severity::Critical,
                "C/C++ OpenSSL DH functions",
                "Migrate to Kyber KEM",
                Some("CWE-327"),
            ),
            (
                r"(?i)EVP_md5|EVP_sha1|MD5_Init|SHA1_Init",
                VulnerabilityType::Md5,
                Severity::High,
                "C/C++ OpenSSL MD5/SHA-1",
                "Use SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            (
                r"(?i)EVP_des_cbc|EVP_des_ecb|EVP_des_ede3",
                VulnerabilityType::Des,
                Severity::Critical,
                "C/C++ OpenSSL DES cipher",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r"(?i)EVP_rc4|RC4_set_key|RC4\s*\(",
                VulnerabilityType::Rc4,
                Severity::Critical,
                "C/C++ OpenSSL RC4 cipher",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r"(?i)rand\s*\(|srand\s*\(",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "C/C++ rand() function (weak RNG)",
                "Use /dev/urandom or RAND_bytes()",
                Some("CWE-338"),
            ),
            (
                r"(?i)SSL_CTX_set_min_proto_version\s*\([^,]*,\s*TLS1_VERSION|SSL_CTX_set_min_proto_version\s*\([^,]*,\s*TLS1_1_VERSION",
                VulnerabilityType::InsecureTls,
                Severity::High,
                "C/C++ insecure TLS version",
                "Use TLS 1.2 or higher",
                Some("CWE-326"),
            ),

            // ===== C# specific patterns =====
            (
                r"(?i)RSACryptoServiceProvider|RSA\.Create|new\s+RSACryptoServiceProvider",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "C# RSA cryptography",
                "Migrate to post-quantum alternatives",
                Some("CWE-327"),
            ),
            (
                r"(?i)ECDsaCng|ECDiffieHellmanCng|ECDsa\.Create|ECDiffieHellman\.Create",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "C# ECDSA/ECDH cryptography",
                "Migrate to PQC signatures/KEM",
                Some("CWE-327"),
            ),
            (
                r"(?i)DSACryptoServiceProvider|DSA\.Create",
                VulnerabilityType::Dsa,
                Severity::Critical,
                "C# DSA cryptography",
                "Migrate to Dilithium or SPHINCS+",
                Some("CWE-327"),
            ),
            (
                r"(?i)MD5CryptoServiceProvider|MD5\.Create|new\s+MD5CryptoServiceProvider",
                VulnerabilityType::Md5,
                Severity::High,
                "C# MD5 hash",
                "Use SHA256 or SHA3",
                Some("CWE-328"),
            ),
            (
                r"(?i)SHA1CryptoServiceProvider|SHA1\.Create|new\s+SHA1CryptoServiceProvider",
                VulnerabilityType::Sha1,
                Severity::High,
                "C# SHA-1 hash",
                "Use SHA256 or SHA3",
                Some("CWE-328"),
            ),
            (
                r"(?i)DESCryptoServiceProvider|DES\.Create|TripleDESCryptoServiceProvider",
                VulnerabilityType::Des,
                Severity::Critical,
                "C# DES/3DES cipher",
                "Replace with AesCryptoServiceProvider",
                Some("CWE-327"),
            ),
            (
                r"(?i)new\s+Random\s*\(|Random\.Next",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "C# Random class (weak RNG)",
                "Use RNGCryptoServiceProvider for crypto",
                Some("CWE-338"),
            ),
            (
                r"(?i)SecurityProtocolType\.Tls|SecurityProtocolType\.Tls11|SecurityProtocolType\.Ssl3",
                VulnerabilityType::InsecureTls,
                Severity::High,
                "C# insecure TLS version",
                "Use SecurityProtocolType.Tls12 or Tls13",
                Some("CWE-326"),
            ),

            // ===== Dart-specific patterns =====
            (
                r"(?i)package:crypto/crypto\.dart|package:pointycastle|RSAKeyGenerator",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Dart RSA cryptography",
                "Migrate to post-quantum alternatives",
                Some("CWE-327"),
            ),
            (
                r"(?i)ECDSAKeyGenerator|ECKeyGenerator",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Dart EC cryptography",
                "Migrate to PQC signatures",
                Some("CWE-327"),
            ),
            (
                r"(?i)MD5Digest|SHA1Digest|md5\.convert|sha1\.convert",
                VulnerabilityType::Md5,
                Severity::High,
                "Dart MD5/SHA-1 hash",
                "Use SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            (
                r"(?i)Random\(\)|math\.Random\(\)",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Dart Random (weak RNG)",
                "Use secure random for crypto",
                Some("CWE-338"),
            ),

            // ===== Python-specific additional patterns =====
            (
                r"(?i)from\s+Crypto\.PublicKey\s+import\s+RSA|RSA\.generate|rsa\.generate",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Python PyCrypto/PyCryptodome RSA",
                "Migrate to post-quantum cryptography",
                Some("CWE-327"),
            ),
            (
                r"(?i)from\s+Crypto\.PublicKey\s+import\s+ECC|ECC\.generate|ecdsa\.SigningKey",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Python EC cryptography",
                "Migrate to PQC signatures",
                Some("CWE-327"),
            ),
            (
                r"(?i)from\s+Crypto\.Cipher\s+import\s+DES|DES\.new|DES3\.new",
                VulnerabilityType::Des,
                Severity::Critical,
                "Python DES cipher",
                "Replace with AES from Crypto.Cipher",
                Some("CWE-327"),
            ),
            (
                r"(?i)from\s+Crypto\.Hash\s+import\s+MD5|from\s+Crypto\.Hash\s+import\s+SHA1|MD5\.new|SHA1\.new",
                VulnerabilityType::Md5,
                Severity::High,
                "Python MD5/SHA-1 hash",
                "Use SHA256 or SHA3 from Crypto.Hash",
                Some("CWE-328"),
            ),
            (
                r"(?i)random\.(randint|random|choice|shuffle)",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "Python random module (weak RNG)",
                "Use secrets module for cryptographic purposes",
                Some("CWE-338"),
            ),
            (
                r"(?i)ssl\.PROTOCOL_TLSv1|ssl\.PROTOCOL_TLSv1_1|ssl\.PROTOCOL_SSLv2|ssl\.PROTOCOL_SSLv3",
                VulnerabilityType::InsecureTls,
                Severity::High,
                "Python insecure TLS/SSL protocol",
                "Use ssl.PROTOCOL_TLS or ssl.PROTOCOL_TLS_CLIENT",
                Some("CWE-326"),
            ),

            // ===== JavaScript/TypeScript additional patterns =====
            (
                r"(?i)node-forge|forge\.rsa|forge\.pki\.rsa",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "JavaScript node-forge RSA",
                "Migrate to post-quantum alternatives",
                Some("CWE-327"),
            ),
            (
                r"(?i)elliptic|ec\.genKeyPair|ec\.sign",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "JavaScript elliptic curve library",
                "Migrate to PQC signatures",
                Some("CWE-327"),
            ),
            (
                r"(?i)jsrsasign|KJUR\.crypto\.ECDSA|KJUR\.crypto\.RSA",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "JavaScript jsrsasign RSA/ECDSA",
                "Migrate to PQC",
                Some("CWE-327"),
            ),
            (
                r"(?i)crypto-js.*md5|crypto-js.*sha1|CryptoJS\.MD5|CryptoJS\.SHA1",
                VulnerabilityType::Md5,
                Severity::High,
                "JavaScript crypto-js MD5/SHA-1",
                "Use SHA-256 or SHA-3",
                Some("CWE-328"),
            ),
            (
                r"(?i)Math\.random\s*\(\)|window\.crypto\.getRandomValues\s*\(\s*\[\s*\]\s*\)",
                VulnerabilityType::WeakRandom,
                Severity::High,
                "JavaScript Math.random (weak RNG)",
                "Use crypto.getRandomValues() or crypto.randomBytes()",
                Some("CWE-338"),
            ),

            // ===== Additional comprehensive patterns =====
            (
                r"(?i)\bRSA\s*-\s*(OAEP|PSS|PKCS1|PKCS#1)\b",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "RSA algorithm variant",
                "Migrate to CRYSTALS-Kyber",
                Some("CWE-327"),
            ),
            (
                r"(?i)\b(Ed25519|Ed448|X25519|X448)\b",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Edwards curve cryptography (quantum-vulnerable)",
                "Migrate to CRYSTALS-Dilithium",
                Some("CWE-327"),
            ),
            (
                r"(?i)\b(Brainpool|secp|prime)\d+r?\d*\b",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Elliptic curve parameters",
                "Migrate to PQC",
                Some("CWE-327"),
            ),
            (
                r"(?i)\b(Diffie[\s-]?Hellman|DH)\b",
                VulnerabilityType::DhKeyExchange,
                Severity::Critical,
                "Diffie-Hellman key exchange",
                "Replace with Kyber KEM",
                Some("CWE-327"),
            ),
            (
                r"(?i)\b(ElGamal|El[\s-]?Gamal)\b",
                VulnerabilityType::DhKeyExchange,
                Severity::Critical,
                "ElGamal encryption (quantum-vulnerable)",
                "Migrate to Kyber KEM",
                Some("CWE-327"),
            ),
            (
                r"(?i)\b(Blowfish|Twofish)\b",
                VulnerabilityType::Blowfish,
                Severity::Medium,
                "Blowfish/Twofish cipher (deprecated)",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r"(?i)\b(IDEA|International Data Encryption Algorithm)\b",
                VulnerabilityType::Des,
                Severity::Medium,
                "IDEA cipher (deprecated)",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r"(?i)\b(CAST|CAST5|CAST-128)\b",
                VulnerabilityType::Des,
                Severity::Medium,
                "CAST cipher (deprecated)",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r"(?i)\b(Skipjack|SEAL)\b",
                VulnerabilityType::Des,
                Severity::Medium,
                "Skipjack/SEAL cipher (deprecated)",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            (
                r"(?i)\b(TLS\s*1\.0|TLS\s*1\.1|SSL\s*2\.0|SSL\s*3\.0)\b",
                VulnerabilityType::InsecureTls,
                Severity::High,
                "Insecure TLS/SSL version",
                "Use TLS 1.2 or higher",
                Some("CWE-326"),
            ),
            (
                r"(?i)\b(RC2|RC5|RC6)\b",
                VulnerabilityType::Rc4,
                Severity::Critical,
                "RC2/RC5/RC6 cipher (broken/deprecated)",
                "Replace with AES-256-GCM",
                Some("CWE-327"),
            ),
            
            // ===== SSH Key Patterns =====
            (
                r"(?i)ssh-rsa\s+[A-Za-z0-9+/]+",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "SSH RSA public key",
                "Migrate to post-quantum SSH keys when available",
                Some("CWE-327"),
            ),
            (
                r"(?i)ecdsa-sha2-nistp\d+",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "SSH ECDSA public key",
                "Migrate to post-quantum SSH keys when available",
                Some("CWE-327"),
            ),
            (
                r"(?i)ssh-ed25519\s+[A-Za-z0-9+/]+",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "SSH Ed25519 public key (quantum-vulnerable)",
                "Migrate to post-quantum SSH keys when available",
                Some("CWE-327"),
            ),
            (
                r"(?i)-----BEGIN\s+(RSA|DSA|EC)\s+(PRIVATE|PUBLIC)\s+KEY-----",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "PEM-encoded quantum-vulnerable key",
                "Migrate to post-quantum cryptography",
                Some("CWE-327"),
            ),
            (
                r"(?i)-----BEGIN\s+OPENSSH\s+PRIVATE\s+KEY-----",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "OpenSSH private key (likely RSA/EC)",
                "Audit key algorithm and migrate to PQC",
                Some("CWE-327"),
            ),
            
            // ===== Certificate Patterns =====
            (
                r"(?i)X509Certificate|X\.509|x509\.",
                VulnerabilityType::Rsa2048,
                Severity::High,
                "X.509 certificate handling (likely RSA/ECDSA)",
                "Plan for PQC certificate migration",
                Some("CWE-327"),
            ),
            (
                r"(?i)PKCS#?12|\.p12|\.pfx",
                VulnerabilityType::Rsa2048,
                Severity::High,
                "PKCS#12 certificate container (likely RSA/ECDSA)",
                "Plan for PQC certificate migration",
                Some("CWE-327"),
            ),
            
            // ===== Additional Python Patterns =====
            (
                r"(?i)from\s+nacl\s+import|import\s+nacl",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "PyNaCl library (uses Curve25519/Ed25519)",
                "Migrate to post-quantum cryptography",
                Some("CWE-327"),
            ),
            (
                r"(?i)from\s+cryptography\.hazmat\.primitives\s+import\s+hashes",
                VulnerabilityType::Sha1,
                Severity::Medium,
                "Python cryptography hazmat hashes import",
                "Verify not using MD5/SHA-1",
                Some("CWE-328"),
            ),
            (
                r"(?i)\.sign\s*\(|\.verify\s*\(",
                VulnerabilityType::Rsa2048,
                Severity::High,
                "Digital signature operation",
                "Verify using post-quantum signature scheme",
                Some("CWE-327"),
            ),
            (
                r"(?i)load_pem_private_key|load_der_private_key",
                VulnerabilityType::Rsa2048,
                Severity::High,
                "Loading private key (likely RSA/EC)",
                "Verify key is post-quantum safe",
                Some("CWE-327"),
            ),
            (
                r"(?i)serialization\.Encoding\.PEM",
                VulnerabilityType::Rsa2048,
                Severity::Medium,
                "Key serialization (likely RSA/EC)",
                "Plan for PQC key migration",
                Some("CWE-327"),
            ),
            
            // ===== Additional Node.js Patterns =====
            (
                r"(?i)crypto\.createSign\s*\(|crypto\.createVerify\s*\(",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Node.js signature creation/verification",
                "Migrate to post-quantum signatures",
                Some("CWE-327"),
            ),
            (
                r"(?i)crypto\.createPrivateKey|crypto\.createPublicKey",
                VulnerabilityType::Rsa2048,
                Severity::High,
                "Node.js asymmetric key creation",
                "Verify using post-quantum keys",
                Some("CWE-327"),
            ),
            (
                r"(?i)tls\.createSecureContext",
                VulnerabilityType::Rsa2048,
                Severity::Medium,
                "Node.js TLS context (uses RSA/ECDSA certs)",
                "Plan for PQC TLS migration",
                Some("CWE-327"),
            ),
            (
                r"(?i)subtle\.importKey|subtle\.exportKey",
                VulnerabilityType::Rsa2048,
                Severity::High,
                "WebCrypto key import/export",
                "Verify using post-quantum algorithms",
                Some("CWE-327"),
            ),
            (
                r"(?i)subtle\.generateKey\s*\(|subtle\.sign\s*\(|subtle\.verify\s*\(",
                VulnerabilityType::Rsa2048,
                Severity::High,
                "WebCrypto operations (likely RSA/ECDSA)",
                "Migrate to post-quantum WebCrypto when available",
                Some("CWE-327"),
            ),
            
            // ===== Additional Go Patterns =====
            (
                r#"(?i)rsa\.GenerateKey\s*\(|rsa\.EncryptPKCS1v15\s*\(|rsa\.DecryptPKCS1v15\s*\("#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Go RSA operations",
                "Use circl or go-pqc for post-quantum",
                Some("CWE-327"),
            ),
            (
                r#"(?i)ecdsa\.GenerateKey\s*\(|ecdsa\.Sign\s*\(|ecdsa\.Verify\s*\("#,
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Go ECDSA operations",
                "Migrate to Dilithium signatures",
                Some("CWE-327"),
            ),
            (
                r#"(?i)elliptic\.P256\s*\(|elliptic\.P384\s*\(|elliptic\.P521\s*\("#,
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Go elliptic curve selection",
                "Migrate to post-quantum curves",
                Some("CWE-327"),
            ),
            (
                r"(?i)x509\.CreateCertificate",
                VulnerabilityType::Rsa2048,
                Severity::High,
                "Go X.509 certificate creation (likely RSA/EC)",
                "Plan for PQC certificate migration",
                Some("CWE-327"),
            ),
            (
                r"(?i)ssh\\.parsePrivateKey|ssh\\.ParsePrivateKey",
                VulnerabilityType::Rsa2048,
                Severity::High,
                "Go SSH private key parsing",
                "Verify key is post-quantum safe",
                Some("CWE-327"),
            ),
            
            // ===== Additional Java Patterns =====  
            (
                r#"(?i)KeyFactory\.getInstance\s*\(\s*['"]RSA['"]"#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Java RSA KeyFactory",
                "Use BouncyCastle PQC provider",
                Some("CWE-327"),
            ),
            (
                r#"(?i)KeyFactory\.getInstance\s*\(\s*['"]EC['"]|KeyFactory\.getInstance\s*\(\s*['"]ECDSA['"]"#,
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Java EC/ECDSA KeyFactory",
                "Use BouncyCastle PQC provider",
                Some("CWE-327"),
            ),
            (
                r#"(?i)Signature\.getInstance\s*\(\s*['"][^'"]*RSA[^'"]*['"]"#,
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                "Java RSA Signature",
                "Migrate to Dilithium",
                Some("CWE-327"),
            ),
            (
                r#"(?i)Signature\.getInstance\s*\(\s*['"][^'"]*ECDSA[^'"]*['"]"#,
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Java ECDSA Signature",
                "Migrate to Dilithium",
                Some("CWE-327"),
            ),
            (
                r#"(?i)KeyAgreement\.getInstance\s*\(\s*['"]ECDH['"]|KeyAgreement\.getInstance\s*\(\s*['"]DH['"]"#,
                VulnerabilityType::DhKeyExchange,
                Severity::Critical,
                "Java key agreement (DH/ECDH)",
                "Migrate to Kyber KEM",
                Some("CWE-327"),
            ),
            (
                r#"(?i)CertificateFactory\.getInstance\s*\(\s*['"]X\.509['"]"#,
                VulnerabilityType::Rsa2048,
                Severity::High,
                "Java X.509 certificate handling",
                "Plan for PQC certificate migration",
                Some("CWE-327"),
            ),
            
            // ===== Key Derivation Functions =====
            (
                r"(?i)PBKDF2|HKDF|scrypt|argon2|bcrypt",
                VulnerabilityType::Md5,
                Severity::Low,
                "Key derivation function (review hash algorithm)",
                "Ensure using SHA-256+ and adequate iterations",
                Some("CWE-916"),
            ),
            
            // ===== Cryptographic Library Detection =====
            (
                r#"(?i)require\s*\(\s*['"]tweetnacl['"]|import\s+tweetnacl"#,
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "TweetNaCl library (Curve25519/Ed25519)",
                "Migrate to post-quantum library",
                Some("CWE-327"),
            ),
            (
                r#"(?i)require\s*\(\s*['"]libsodium['"]|import\s+libsodium|sodium\."#,
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Libsodium library (uses Curve25519/Ed25519)",
                "Migrate to post-quantum cryptography",
                Some("CWE-327"),
            ),
            (
                r"(?i)BouncyCastle|bcprov|bcpkix",
                VulnerabilityType::Rsa2048,
                Severity::Medium,
                "BouncyCastle library (may use RSA/EC)",
                "Verify using PQC algorithms from BC-PQC",
                Some("CWE-327"),
            ),
            (
                r"(?i)OpenSSL|libcrypto|libssl",
                VulnerabilityType::Rsa2048,
                Severity::Medium,
                "OpenSSL library usage",
                "Configure for PQC when available (OpenSSL 3.2+)",
                Some("CWE-327"),
            ),
            
            // ===== .NET/C# Additional Patterns =====
            (
                r"(?i)RSACryptoServiceProvider|RSA\.Create\s*\(",
                VulnerabilityType::Rsa2048,
                Severity::Critical,
                ".NET RSA cryptography",
                "Migrate to post-quantum when available in .NET",
                Some("CWE-327"),
            ),
            (
                r"(?i)ECDsa\.Create\s*\(|ECDsaCng",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                ".NET ECDSA cryptography",
                "Migrate to post-quantum signatures",
                Some("CWE-327"),
            ),
            (
                r"(?i)DSACryptoServiceProvider|DSA\.Create\s*\(",
                VulnerabilityType::Dsa,
                Severity::Critical,
                ".NET DSA cryptography",
                "Migrate to Dilithium",
                Some("CWE-327"),
            ),
            (
                r"(?i)ECDiffieHellman|ECDiffieHellmanCng",
                VulnerabilityType::Ecdh,
                Severity::Critical,
                ".NET ECDH key exchange",
                "Migrate to Kyber KEM",
                Some("CWE-327"),
            ),
            (
                r"(?i)MD5CryptoServiceProvider|MD5\.Create\s*\(",
                VulnerabilityType::Md5,
                Severity::High,
                ".NET MD5 hash",
                "Use SHA256 or SHA512",
                Some("CWE-328"),
            ),
            (
                r"(?i)SHA1CryptoServiceProvider|SHA1\.Create\s*\(",
                VulnerabilityType::Sha1,
                Severity::High,
                ".NET SHA-1 hash",
                "Use SHA256 or SHA512",
                Some("CWE-328"),
            ),
            
            // ===== Blockchain/Crypto Wallet Patterns =====
            (
                r"(?i)secp256k1|bitcoin|ethereum|web3",
                VulnerabilityType::Ecdsa,
                Severity::Critical,
                "Blockchain cryptography (secp256k1/ECDSA)",
                "Monitor blockchain PQC developments",
                Some("CWE-327"),
            ),
            (
                r"(?i)PrivateKey\s*\(|PublicKey\s*\(|KeyPair\s*\(",
                VulnerabilityType::Rsa2048,
                Severity::High,
                "Key object instantiation",
                "Verify using post-quantum key types",
                Some("CWE-327"),
            ),
            
            // ===== Configuration/Environment Patterns =====
            (
                r#"(?i)(algorithm|cipher|algo)\s*[=:]\s*['"]?(rsa|ecdsa|dsa|dh|des|rc4|md5|sha1)['"]?"#,
                VulnerabilityType::Rsa2048,
                Severity::High,
                "Cryptographic algorithm configuration",
                "Update to post-quantum or quantum-safe algorithms",
                Some("CWE-327"),
            ),
            (
                r#"(?i)jwt\.(sign|verify)|jsonwebtoken"#,
                VulnerabilityType::Rsa2048,
                Severity::High,
                "JWT signing/verification (likely RSA/ECDSA)",
                "Consider HMAC for symmetric or plan PQC migration",
                Some("CWE-327"),
            ),
        ];

        patterns
            .into_iter()
            .filter_map(|(pattern, vuln_type, severity, desc, rec, cwe)| {
                Regex::new(pattern).ok().map(|regex| CompiledPattern {
                    regex,
                    vuln_type,
                    severity,
                    description: desc.to_string(),
                    recommendation: rec.to_string(),
                    cwe_id: cwe.map(|s| s.to_string()),
                })
            })
            .collect()
    }

    /// Analyze source code using pattern matching
    pub fn analyze(
        &self,
        source: &str,
        file_path: &Path,
        language: Language,
        rules: &[Rule],
    ) -> Result<Vec<Vulnerability>> {
        let mut vulnerabilities = Vec::new();

        // Apply compiled patterns
        for pattern in &self.compiled_patterns {
            for mat in pattern.regex.find_iter(source) {
                // First, check if this is in an informational/documentation string
                // (we want to skip these even though they're in strings)
                if self.is_informational_string(source, mat.start(), mat.end()) {
                    continue;
                }

                // Check if it's in a comment (NOT strings - algorithm identifiers in strings ARE vulnerabilities)
                if self.is_in_comment(source, mat.start(), language) {
                    continue;
                }

                let (line, column) = self.offset_to_position(source, mat.start());

                vulnerabilities.push(Vulnerability {
                    id: Uuid::new_v4(),
                    vuln_type: pattern.vuln_type.clone(),
                    severity: pattern.severity,
                    location: Location {
                        file: file_path.to_path_buf(),
                        line,
                        column,
                        end_line: None,
                        end_column: None,
                    },
                    description: pattern.description.clone(),
                    code_snippet: self.extract_snippet(source, line),
                    recommendation: pattern.recommendation.clone(),
                    migration_impacts: vec![],
                    cwe_id: pattern.cwe_id.clone(),
                    is_dependency: false,
                    dependency_chain: None,
                    finding_type: crate::types::FindingType::DirectUsage,
                    library_name: None,
                });
            }
        }

        // Apply rule-based patterns
        for rule in rules {
            for pattern in &rule.patterns {
                if let Some(regex_str) = self.pattern_to_regex(pattern) {
                    if let Ok(regex) = Regex::new(&regex_str) {
                        for mat in regex.find_iter(source) {
                            // First, check if this is in an informational/documentation string
                            if self.is_informational_string(source, mat.start(), mat.end()) {
                                continue;
                            }

                            // Check if it's in a comment
                            if self.is_in_comment(source, mat.start(), language) {
                                continue;
                            }

                            let (line, column) = self.offset_to_position(source, mat.start());

                            // Check for duplicates
                            let is_duplicate = vulnerabilities.iter().any(|v| {
                                v.location.file == file_path
                                    && v.location.line == line
                                    && std::mem::discriminant(&v.vuln_type)
                                        == std::mem::discriminant(&rule.vuln_type)
                            });

                            if !is_duplicate {
                                vulnerabilities.push(Vulnerability {
                                    id: Uuid::new_v4(),
                                    vuln_type: rule.vuln_type.clone(),
                                    severity: rule.severity,
                                    location: Location {
                                        file: file_path.to_path_buf(),
                                        line,
                                        column,
                                        end_line: None,
                                        end_column: None,
                                    },
                                    description: rule.description.clone(),
                                    code_snippet: self.extract_snippet(source, line),
                                    recommendation: rule.recommendation.clone(),
                                    migration_impacts: rule
                                        .migration_impacts
                                        .iter()
                                        .map(|t| t.to_impact(vec![]))
                                        .collect(),
                                    cwe_id: rule.cwe_id.clone(),
                                    is_dependency: false,
                                    dependency_chain: None,
                                    finding_type: crate::types::FindingType::DirectUsage,
                                    library_name: None,
                                });
                            }
                        }
                    }
                }
            }
        }

        Ok(vulnerabilities)
    }

    fn pattern_to_regex(&self, pattern: &RulePattern) -> Option<String> {
        match pattern {
            RulePattern::FunctionCall { names, module: _ } => {
                let escaped: Vec<String> = names.iter().map(|n| regex::escape(n)).collect();
                Some(format!(r"\b({})\s*\(", escaped.join("|")))
            }
            RulePattern::StringLiteral { patterns } => {
                let escaped: Vec<String> = patterns.iter().map(|p| regex::escape(p)).collect();
                Some(format!(r#"['"]({})['"]"#, escaped.join("|")))
            }
            RulePattern::Import { modules, symbols } => {
                let all: Vec<String> = modules
                    .iter()
                    .chain(symbols.iter())
                    .map(|s| regex::escape(s))
                    .collect();
                Some(format!(r"(import|from|require|use)\s+.*({}).*", all.join("|")))
            }
            RulePattern::MethodCall { object_type: _, method_names } => {
                let escaped: Vec<String> = method_names.iter().map(|n| regex::escape(n)).collect();
                Some(format!(r"\.({})[\s(]", escaped.join("|")))
            }
            RulePattern::Regex { pattern } => Some(pattern.clone()),
            _ => None,
        }
    }

    fn offset_to_position(&self, source: &str, offset: usize) -> (usize, usize) {
        let mut line = 1;
        let mut col = 1;

        for (i, c) in source.char_indices() {
            if i >= offset {
                break;
            }
            if c == '\n' {
                line += 1;
                col = 1;
            } else {
                col += 1;
            }
        }

        (line, col)
    }

    /// Determine if a match offset is inside a comment (NOT strings - algorithm identifiers in strings ARE vulnerabilities).
    fn is_in_comment(&self, source: &str, offset: usize, language: Language) -> bool {
        if source.is_empty() {
            return false;
        }

        let offset = offset.min(source.len());
        
        // Find line boundaries
        let line_start = source[..offset]
            .rfind('\n')
            .map(|i| i + 1)
            .unwrap_or(0);
        let _line_end = source[offset..]
            .find('\n')
            .map(|i| offset + i)
            .unwrap_or(source.len());

        let line_before_match = &source[line_start..offset];
        
        let (inline_markers, block_markers, symmetric_markers) = self.get_comment_markers(language);

        // Check for inline comments on this line BEFORE the match
        // Iterate through ALL occurrences of markers, not just the first one
        for marker in inline_markers {
            for (idx, _) in line_before_match.match_indices(marker) {
                // If we find a comment marker that is NOT inside a string, then everything after is a comment
                if !self.is_inside_string_on_line(line_before_match, idx) {
                    return true;
                }
            }
        }

        // NOTE: We deliberately do NOT check for string literals here.
        // Algorithm identifiers passed as strings to crypto functions ARE vulnerabilities.
        // Only informational strings (filtered by is_informational_string) should be skipped.

        // Check for asymmetric block comments (/* ... */)
        if !block_markers.is_empty() {
             for (start_marker, end_marker) in block_markers {
                 let last_end = source[..offset].rfind(end_marker);
                 let last_start = source[..offset].rfind(start_marker);
                 
                 match (last_start, last_end) {
                     (Some(s), Some(e)) => {
                         if s > e {
                             return true; // Found a start after the last end
                         }
                     }
                     (Some(_), None) => {
                         return true; // Found a start but no end
                     }
                     _ => {}
                 }
             }
        }

        // Check for symmetric block markers (e.g. Python """ ... """)
        // We count occurrences. If odd, we are inside.
        // NOTE: This heuristic doesn't perfectly handle escaped quotes, but triple-quotes are rarely escaped.
        for marker in symmetric_markers {
            let count = source[..offset].matches(marker).count();
            if count % 2 != 0 {
                return true;
            }
        }

        false
    }

    /// Helper to determine if a specific position on a line is inside a string string
    fn is_inside_string_on_line(&self, line_content: &str, target_idx: usize) -> bool {
        let mut in_single = false;
        let mut in_double = false;
        let mut in_java_string = false; // "..."
        let mut in_lua_multiline = false; // [[ ... ]]
        
        let mut chars = line_content.char_indices().peekable();
        let mut prev_backslash = false;
        let mut last_char = ' ';

        while let Some((idx, ch)) = chars.next() {
            if idx >= target_idx {
                break;
            }

            // Check for Lua multiline start [[
            if ch == '[' {
                if let Some((_, '[')) = chars.peek() {
                    // This is [[, entering multiline string (simplified)
                    if !in_single && !in_double {
                         // We are entering a detailed scan, but for this simplified "is_inside" 
                         // we treat it as a state change.
                         // But we cannot easily consume the next char here without advancing the iterator 
                         // which affects the loop. 
                         // Just ignoring for now as simple heuristic 
                         // "Smart" way:
                    }
                }
            }
            
            match ch {
                '\\' => {
                    prev_backslash = !prev_backslash;
                }
                '"' if !prev_backslash && !in_single => {
                    in_double = !in_double;
                    prev_backslash = false;
                }
                '\'' if !prev_backslash && !in_double => {
                    in_single = !in_single;
                    prev_backslash = false;
                }
                _ => {
                    prev_backslash = false;
                }
            }
            last_char = ch;
        }

        // Check for heredoc markers (heuristic)
        // If the line *starts* with a heredoc marker usage or contains `<<`, we assume the rest of the line (or next lines) might be strings.
        // This is extremely hard to do with just line-context.
        // Current implementation is strictly line-based.
        
        in_single || in_double
    }

    fn get_comment_markers(&self, language: Language) -> (&'static [&'static str], &'static [(&'static str, &'static str)], &'static [&'static str]) {
        match language {
            Language::JavaScript | Language::TypeScript | Language::Java | Language::Rust | 
            Language::C | Language::Cpp | Language::CSharp | Language::Go | Language::Kotlin | 
            Language::Scala | Language::Swift | Language::Dart | Language::Groovy | 
            Language::ObjectiveC | Language::Php | Language::Solidity => {
                (&["//"], &[("/*", "*/")], &[])
            }
            Language::Python => {
                (&["#"], &[], &["\"\"\"", "'''"])
            }
            Language::Ruby => {
                 // Check for =begin =end?
                 // Ruby uses # for inline.
                (&["#"], &[("=begin", "=end")], &[]) 
            }
            Language::Shell | Language::Perl | Language::R => {
                (&["#"], &[], &[])
            }
            Language::Lua => {
                // Lua strings [[ ... ]] are symmetric-ish, but mainly block comments are --[[ ... ]]
                (&["--"], &[("--[[", "]]")], &["[[", "]]"])
            }
            Language::Elixir => {
                // Elixir uses # for inline comments and @doc/@moduledoc for documentation
                (&["#"], &[], &["\"\"\""])
            }
            Language::Haskell => {
                // Haskell uses -- for inline and {- -} for block
                (&["--"], &[("{-", "-}")], &[])
            }
            Language::FSharp => {
                // F# uses // for inline and (* *) for block
                (&["//"], &[("(*", "*)")], &[])
            }
            Language::Clojure => {
                // Clojure uses ; for inline comments
                (&[";", ";;"], &[], &[])
            }
            Language::Unknown => {
                // Conservative defaults - check all common comment markers
                (&["//", "#", "--", ";"], &[("/*", "*/")], &[])
            }
            _ => (&["//", "#"], &[], &[]) // Default fallback includes both // and #
        }
    }

    fn extract_snippet(&self, source: &str, line: usize) -> Option<String> {
        let lines: Vec<&str> = source.lines().collect();

        if line == 0 || line > lines.len() {
            return None;
        }

        let start = line.saturating_sub(2);
        let end = (line + 1).min(lines.len());

        let snippet: Vec<String> = lines[start..end]
            .iter()
            .enumerate()
            .map(|(i, l)| format!("{:4} | {}", start + i + 1, l))
            .collect();

        Some(snippet.join("\n"))
    }
}
