//! Clojure-specific quantum vulnerability detection

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

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

pub struct ClojureAnalyzer {
    patterns: Vec<ClojurePattern>,
}

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

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

    fn compile_patterns() -> Vec<ClojurePattern> {
        let pattern_defs: Vec<(&str, VulnerabilityType, Severity, &'static str, &'static str, Option<&'static str>)> = vec![
            // RSA patterns (Java interop)
            (r#"(?i)KeyPairGenerator/getInstance\s+["']RSA["']|\.getInstance\s+["']RSA["']"#, VulnerabilityType::Rsa2048, Severity::Critical, "Clojure RSA KeyPairGenerator", "Migrate to PQC", Some("CWE-327")),
            (r#"(?i)Cipher/getInstance.*RSA"#, VulnerabilityType::Rsa2048, Severity::Critical, "Clojure RSA Cipher", "Use PQC", Some("CWE-327")),
            (r"(?i)RSAPublicKeySpec|RSAPrivateKeySpec|RSAKeyGenParameterSpec", VulnerabilityType::Rsa2048, Severity::Critical, "Clojure RSA key spec", "Migrate to PQC", Some("CWE-327")),
            
            // buddy-sign library
            (r#"(?i)buddy\.sign\.jws|buddy\.sign\.jwt|:alg\s+:rs256|:alg\s+:es256"#, VulnerabilityType::Rsa2048, Severity::Critical, "Clojure buddy-sign JWT with RSA/EC", "Review algorithm", Some("CWE-327")),
            
            // EC patterns
            (r#"(?i)KeyPairGenerator/getInstance\s+["']EC["']|\.getInstance\s+["']EC["']"#, VulnerabilityType::Ecdsa, Severity::Critical, "Clojure EC KeyPairGenerator", "Migrate to PQC", Some("CWE-327")),
            (r#"(?i)Signature/getInstance.*ECDSA"#, VulnerabilityType::Ecdsa, Severity::Critical, "Clojure ECDSA Signature", "Use Dilithium", Some("CWE-327")),
            (r#"(?i)KeyAgreement/getInstance\s+["']ECDH["']"#, VulnerabilityType::Ecdh, Severity::Critical, "Clojure ECDH KeyAgreement", "Use Kyber", Some("CWE-327")),
            
            // DSA patterns
            (r#"(?i)KeyPairGenerator/getInstance\s+["']DSA["']"#, VulnerabilityType::Dsa, Severity::Critical, "Clojure DSA KeyPairGenerator", "Use Dilithium", Some("CWE-327")),
            
            // DH patterns
            (r#"(?i)KeyPairGenerator/getInstance\s+["']DH["']"#, VulnerabilityType::DhKeyExchange, Severity::Critical, "Clojure DH KeyPairGenerator", "Use Kyber", Some("CWE-327")),
            (r#"(?i)KeyAgreement/getInstance\s+["']DH["']"#, VulnerabilityType::DhKeyExchange, Severity::Critical, "Clojure DH KeyAgreement", "Use Kyber", Some("CWE-327")),
            
            // Weak hashes
            (r#"(?i)MessageDigest/getInstance\s+["']MD5["']|\.md5\s|digest/md5"#, VulnerabilityType::Md5, Severity::High, "Clojure MD5 detected", "Use SHA256", Some("CWE-328")),
            (r#"(?i)MessageDigest/getInstance\s+["']SHA-?1["']|\.sha1\s|digest/sha1"#, VulnerabilityType::Sha1, Severity::High, "Clojure SHA-1 detected", "Use SHA256", Some("CWE-328")),
            (r#"(?i)Mac/getInstance\s+["']HmacMD5["']"#, VulnerabilityType::Md5, Severity::High, "Clojure HMAC-MD5", "Use HMAC-SHA256", Some("CWE-328")),
            (r#"(?i)Mac/getInstance\s+["']HmacSHA1["']"#, VulnerabilityType::Sha1, Severity::High, "Clojure HMAC-SHA1", "Use HMAC-SHA256", Some("CWE-328")),
            
            // Weak ciphers
            (r#"(?i)Cipher/getInstance\s+["']DES/"#, VulnerabilityType::Des, Severity::Critical, "Clojure DES Cipher", "Use AES-GCM", Some("CWE-327")),
            (r#"(?i)Cipher/getInstance\s+["']DESede/"#, VulnerabilityType::TripleDes, Severity::High, "Clojure 3DES Cipher", "Use AES-GCM", Some("CWE-327")),
            (r#"(?i)Cipher/getInstance\s+["']RC4["']"#, VulnerabilityType::Rc4, Severity::Critical, "Clojure RC4 Cipher", "Use AES-GCM", Some("CWE-327")),
            
            // Weak random
            (r"(?i)java\.util\.Random\.|Random\.\s|rand-int|rand\s", VulnerabilityType::WeakRandom, Severity::High, "Clojure weak random", "Use SecureRandom", Some("CWE-338")),
            
            // Insecure TLS
            (r#"(?i)SSLContext/getInstance\s+["'](SSLv|TLSv1\b|TLSv1\.0|TLSv1\.1)"#, VulnerabilityType::InsecureTls, Severity::High, "Clojure insecure TLS", "Use TLS 1.2+", Some("CWE-326")),
        ];

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