//! Perl-specific quantum vulnerability detection

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

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

pub struct PerlAnalyzer {
    patterns: Vec<PerlPattern>,
}

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

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

    fn compile_patterns() -> Vec<PerlPattern> {
        let pattern_defs: Vec<(&str, VulnerabilityType, Severity, &'static str, &'static str, Option<&'static str>)> = vec![
            // RSA patterns
            (r"(?i)Crypt::OpenSSL::RSA|Crypt::RSA|new_private_key|new_public_key", VulnerabilityType::Rsa2048, Severity::Critical, "Perl RSA module detected", "Migrate to PQC", Some("CWE-327")),
            (r"(?i)->generate_key\s*\(|rsa_generate|generate_rsa", VulnerabilityType::Rsa2048, Severity::Critical, "Perl RSA key generation", "Use PQC", Some("CWE-327")),
            (r"(?i)->encrypt\s*\(.*rsa|->decrypt\s*\(.*rsa|rsa_encrypt|rsa_decrypt", VulnerabilityType::Rsa2048, Severity::Critical, "Perl RSA encrypt/decrypt", "Migrate to PQC", Some("CWE-327")),
            (r"(?i)->sign\s*\(.*rsa|->verify\s*\(.*rsa|rsa_sign|rsa_verify", VulnerabilityType::Rsa2048, Severity::Critical, "Perl RSA sign/verify", "Use Dilithium", Some("CWE-327")),
            
            // ECDSA/ECDH patterns
            (r"(?i)Crypt::OpenSSL::EC|Crypt::EC|Crypt::ECDSA", VulnerabilityType::Ecdsa, Severity::Critical, "Perl EC module detected", "Migrate to PQC", Some("CWE-327")),
            (r"(?i)ec_generate|generate_ec|ecdsa_sign|ecdsa_verify", VulnerabilityType::Ecdsa, Severity::Critical, "Perl ECDSA operations", "Use Dilithium", Some("CWE-327")),
            (r"(?i)ecdh_compute|derive_shared|ec_dh", VulnerabilityType::Ecdh, Severity::Critical, "Perl ECDH detected", "Use Kyber", Some("CWE-327")),
            (r#"(?i)secp256k1|secp384r1|secp521r1|prime256v1"#, VulnerabilityType::Ecdsa, Severity::Critical, "Perl EC curve detected", "Quantum-vulnerable", Some("CWE-327")),
            
            // DSA patterns
            (r"(?i)Crypt::DSA|Crypt::OpenSSL::DSA|dsa_generate|dsa_sign|dsa_verify", VulnerabilityType::Dsa, Severity::Critical, "Perl DSA detected", "Use Dilithium", Some("CWE-327")),
            
            // DH patterns
            (r"(?i)Crypt::DH|Crypt::OpenSSL::DH|dh_generate|dh_compute", VulnerabilityType::DhKeyExchange, Severity::Critical, "Perl Diffie-Hellman detected", "Use Kyber", Some("CWE-327")),
            
            // Weak hashes
            (r"(?i)Digest::MD5|md5_hex|md5_base64|md5\s*\(", VulnerabilityType::Md5, Severity::High, "Perl MD5 detected", "Use SHA256", Some("CWE-328")),
            (r"(?i)Digest::SHA1|sha1_hex|sha1_base64|sha1\s*\(", VulnerabilityType::Sha1, Severity::High, "Perl SHA-1 detected", "Use SHA256", Some("CWE-328")),
            (r"(?i)Digest::HMAC_MD5|hmac_md5", VulnerabilityType::Md5, Severity::High, "Perl HMAC-MD5", "Use HMAC-SHA256", Some("CWE-328")),
            (r"(?i)Digest::HMAC_SHA1|hmac_sha1", VulnerabilityType::Sha1, Severity::High, "Perl HMAC-SHA1", "Use HMAC-SHA256", Some("CWE-328")),
            
            // Weak ciphers
            (r"(?i)Crypt::DES|Crypt::DES_EDE3|des_encrypt|des_decrypt", VulnerabilityType::Des, Severity::Critical, "Perl DES detected", "Use AES", Some("CWE-327")),
            (r"(?i)Crypt::RC4|rc4_encrypt|rc4_decrypt", VulnerabilityType::Rc4, Severity::Critical, "Perl RC4 detected", "Use AES", Some("CWE-327")),
            (r"(?i)Crypt::Blowfish|blowfish_encrypt", VulnerabilityType::Blowfish, Severity::Medium, "Perl Blowfish detected", "Use AES", Some("CWE-327")),
            
            // Weak random
            (r"(?i)\brand\s*\(|\bsrand\s*\(|int\s*\(\s*rand", VulnerabilityType::WeakRandom, Severity::High, "Perl rand() detected", "Use Crypt::Random", Some("CWE-338")),
            (r"(?i)Math::Random|random_uniform", VulnerabilityType::WeakRandom, Severity::High, "Perl Math::Random", "Use Crypt::Random", Some("CWE-338")),
            
            // Insecure TLS
            (r"(?i)SSLv2|SSLv3|TLSv1_0|TLSv1_1|SSL_version.*[23]", VulnerabilityType::InsecureTls, Severity::High, "Perl insecure TLS", "Use TLS 1.2+", Some("CWE-326")),
            (r"(?i)verify_mode\s*=>\s*0|SSL_verify_mode\s*=>\s*0", VulnerabilityType::InsecureTls, Severity::High, "Perl TLS verification disabled", "Enable verification", Some("CWE-295")),
            
            // Import patterns
            (r"(?i)use\s+Crypt::OpenSSL::RSA", VulnerabilityType::Rsa2048, Severity::Medium, "Perl RSA import", "Plan PQC migration", Some("CWE-327")),
            (r"(?i)use\s+Crypt::DSA", VulnerabilityType::Dsa, Severity::Medium, "Perl DSA import", "Plan PQC migration", Some("CWE-327")),
            (r"(?i)use\s+Digest::MD5", VulnerabilityType::Md5, Severity::Medium, "Perl MD5 import", "Use SHA256", Some("CWE-328")),
            (r"(?i)use\s+Digest::SHA1", VulnerabilityType::Sha1, Severity::Medium, "Perl SHA1 import", "Use SHA256", Some("CWE-328")),
        ];

        pattern_defs.into_iter().filter_map(|(pattern, vuln_type, severity, desc, rec, cwe)| {
            Regex::new(pattern).ok().map(|regex| PerlPattern { 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];
        // Perl 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"))
    }
}
