//! Elixir-specific quantum vulnerability detection

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

use crate::types::{Location, Severity, Vulnerability, VulnerabilityType};

pub struct ElixirAnalyzer {
    patterns: Vec<ElixirPattern>,
}

struct ElixirPattern {
    regex: Regex,
    vuln_type: VulnerabilityType,
    severity: Severity,
    description: &'static str,
    recommendation: &'static str,
    cwe_id: Option<&'static str>,
}

impl ElixirAnalyzer {
    pub fn new() -> Self {
        Self { patterns: Self::compile_patterns() }
    }

    fn compile_patterns() -> Vec<ElixirPattern> {
        let pattern_defs: Vec<(&str, VulnerabilityType, Severity, &'static str, &'static str, Option<&'static str>)> = vec![
            // RSA patterns (:crypto, :public_key)
            (r"(?i):crypto\.generate_key\s*\(\s*:rsa|:public_key\.generate_key\s*\(\s*\{:rsa", VulnerabilityType::Rsa2048, Severity::Critical, "Elixir RSA key generation", "Migrate to PQC", Some("CWE-327")),
            (r"(?i):public_key\.encrypt_private|:public_key\.decrypt_public|:public_key\.encrypt_public|:public_key\.decrypt_private", VulnerabilityType::Rsa2048, Severity::Critical, "Elixir RSA encryption", "Use PQC", Some("CWE-327")),
            (r"(?i):public_key\.sign\s*\(.*:rsa|:public_key\.verify\s*\(.*:rsa", VulnerabilityType::Rsa2048, Severity::Critical, "Elixir RSA signing", "Use Dilithium", Some("CWE-327")),
            (r"(?i)RSAPrivateKey|RSAPublicKey|:rsa_private_key|:rsa_public_key", VulnerabilityType::Rsa2048, Severity::Critical, "Elixir RSA key type", "Migrate to PQC", Some("CWE-327")),
            
            // ECDSA/ECDH patterns
            (r"(?i):crypto\.generate_key\s*\(\s*:ecdh|:public_key\.generate_key\s*\(\s*\{:ec", VulnerabilityType::Ecdsa, Severity::Critical, "Elixir EC key generation", "Migrate to PQC", Some("CWE-327")),
            (r"(?i):public_key\.sign\s*\(.*:ecdsa|:public_key\.verify\s*\(.*:ecdsa", VulnerabilityType::Ecdsa, Severity::Critical, "Elixir ECDSA signing", "Use Dilithium", Some("CWE-327")),
            (r"(?i):crypto\.compute_key\s*\(\s*:ecdh", VulnerabilityType::Ecdh, Severity::Critical, "Elixir ECDH key exchange", "Use Kyber", Some("CWE-327")),
            (r#"(?i):secp256k1|:secp384r1|:secp521r1|:prime256v1"#, VulnerabilityType::Ecdsa, Severity::Critical, "Elixir EC curve", "Quantum-vulnerable", Some("CWE-327")),
            (r"(?i)ECPrivateKey|ECPublicKey|:ec_private_key|:ec_public_key", VulnerabilityType::Ecdsa, Severity::Critical, "Elixir EC key type", "Migrate to PQC", Some("CWE-327")),
            
            // DSA patterns
            (r"(?i):crypto\.generate_key\s*\(\s*:dss|:public_key\.generate_key\s*\(\s*\{:dss", VulnerabilityType::Dsa, Severity::Critical, "Elixir DSA key generation", "Use Dilithium", Some("CWE-327")),
            (r"(?i):public_key\.sign\s*\(.*:dss|:public_key\.verify\s*\(.*:dss", VulnerabilityType::Dsa, Severity::Critical, "Elixir DSA signing", "Use PQC", Some("CWE-327")),
            (r"(?i)DSAPrivateKey|DSAPublicKey|:dsa_private_key", VulnerabilityType::Dsa, Severity::Critical, "Elixir DSA key type", "Use Dilithium", Some("CWE-327")),
            
            // DH patterns
            (r"(?i):crypto\.generate_key\s*\(\s*:dh|:crypto\.compute_key\s*\(\s*:dh", VulnerabilityType::DhKeyExchange, Severity::Critical, "Elixir Diffie-Hellman", "Use Kyber", Some("CWE-327")),
            (r"(?i)DHPrivateKey|DHPublicKey|:dh_private_key|:dh_params", VulnerabilityType::DhKeyExchange, Severity::Critical, "Elixir DH key type", "Use Kyber", Some("CWE-327")),
            
            // Weak hashes
            (r"(?i):crypto\.hash\s*\(\s*:md5|:md5\s*\)", VulnerabilityType::Md5, Severity::High, "Elixir MD5 hash", "Use SHA256", Some("CWE-328")),
            (r"(?i):crypto\.hash\s*\(\s*:sha\s*,|:sha\s*\)|:sha\b", VulnerabilityType::Sha1, Severity::High, "Elixir SHA-1 hash", "Use SHA256", Some("CWE-328")),
            (r"(?i):crypto\.mac\s*\(\s*:hmac,\s*:md5|:crypto\.hmac\s*\(\s*:md5", VulnerabilityType::Md5, Severity::High, "Elixir HMAC-MD5", "Use HMAC-SHA256", Some("CWE-328")),
            (r"(?i):crypto\.mac\s*\(\s*:hmac,\s*:sha\b|:crypto\.hmac\s*\(\s*:sha\b", VulnerabilityType::Sha1, Severity::High, "Elixir HMAC-SHA1", "Use HMAC-SHA256", Some("CWE-328")),
            
            // Weak ciphers
            (r"(?i):crypto\.block_encrypt\s*\(\s*:des|:crypto\.crypto_one_time\s*\(\s*:des", VulnerabilityType::Des, Severity::Critical, "Elixir DES cipher", "Use AES-GCM", Some("CWE-327")),
            (r"(?i):crypto\.block_encrypt\s*\(\s*:des3|:des_ede3|:des3_cbc", VulnerabilityType::TripleDes, Severity::High, "Elixir 3DES cipher", "Use AES-GCM", Some("CWE-327")),
            (r"(?i):crypto\.stream_encrypt\s*\(\s*:rc4|:rc4\b", VulnerabilityType::Rc4, Severity::Critical, "Elixir RC4 cipher", "Use AES-GCM", Some("CWE-327")),
            (r"(?i):blowfish|:bf_cbc|:bf_cfb", VulnerabilityType::Blowfish, Severity::Medium, "Elixir Blowfish cipher", "Use AES-GCM", Some("CWE-327")),
            
            // Weak random
            (r"(?i):rand\.|Enum\.random|:random\.|:erlang\.phash", VulnerabilityType::WeakRandom, Severity::High, "Elixir weak random", "Use :crypto.strong_rand_bytes", Some("CWE-338")),
            
            // Insecure TLS
            (r"(?i):sslv2|:sslv3|:tlsv1\b|:'tlsv1\.0'|:'tlsv1\.1'", VulnerabilityType::InsecureTls, Severity::High, "Elixir insecure TLS", "Use TLS 1.2+", Some("CWE-326")),
            (r"(?i)verify:\s*:verify_none|verify_peer:\s*false", VulnerabilityType::InsecureTls, Severity::High, "Elixir TLS verification disabled", "Enable verification", Some("CWE-295")),
            
            // ExCrypto patterns
            (r"(?i)ExCrypto\.generate_rsa_key_pair|ExCrypto\.rsa_encrypt|ExCrypto\.rsa_decrypt", VulnerabilityType::Rsa2048, Severity::Critical, "Elixir ExCrypto RSA", "Migrate to PQC", Some("CWE-327")),
        ];

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

    pub fn analyze(&self, source: &str, file_path: &Path) -> Vec<Vulnerability> {
        let mut vulns = Vec::new();
        for pattern in &self.patterns {
            for mat in pattern.regex.find_iter(source) {
                if self.is_in_comment(source, mat.start()) { continue; }
                let (line, column) = self.offset_to_position(source, mat.start());
                vulns.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.to_string(), code_snippet: self.extract_snippet(source, line),
                    recommendation: pattern.recommendation.to_string(), migration_impacts: vec![],
                    cwe_id: pattern.cwe_id.map(|s| s.to_string()), is_dependency: false, dependency_chain: None, finding_type: crate::types::FindingType::DirectUsage, library_name: None,
                });
            }
        }
        vulns
    }

    fn is_in_comment(&self, source: &str, offset: usize) -> bool {
        let before = &source[..offset];
        // Elixir single-line comment: #
        if let Some(line_start) = before.rfind('\n') {
            if before[line_start..].contains('#') { return true; }
        }
        false
    }

    fn offset_to_position(&self, source: &str, offset: usize) -> (usize, usize) {
        let (mut line, mut col) = (1, 1);
        for (i, c) in source.char_indices() {
            if i >= offset { break; }
            if c == '\n' { line += 1; col = 1; } else { col += 1; }
        }
        (line, col)
    }

    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());
        Some(lines[start..end].iter().enumerate().map(|(i, l)| format!("{:4} | {}", start + i + 1, l)).collect::<Vec<_>>().join("\n"))
    }
}
