//! Objective-C specific quantum vulnerability detection

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

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

pub struct ObjectiveCAnalyzer {
    patterns: Vec<ObjCPattern>,
}

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

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

    fn compile_patterns() -> Vec<ObjCPattern> {
        let pattern_defs: Vec<(&str, VulnerabilityType, Severity, &'static str, &'static str, Option<&'static str>)> = vec![
            // RSA patterns (Security.framework)
            (r"(?i)SecKeyCreateRandomKey|SecKeyGeneratePair", VulnerabilityType::Rsa2048, Severity::Critical, "Objective-C SecKey generation", "Review for quantum-vulnerable algorithms", Some("CWE-327")),
            (r"(?i)kSecAttrKeyTypeRSA", VulnerabilityType::Rsa2048, Severity::Critical, "Objective-C RSA key type", "Migrate to PQC", Some("CWE-327")),
            (r"(?i)SecKeyEncrypt|SecKeyDecrypt|SecKeyRawSign|SecKeyRawVerify", VulnerabilityType::Rsa2048, Severity::Critical, "Objective-C SecKey crypto operation", "Review algorithm", Some("CWE-327")),
            (r"(?i)kSecPaddingPKCS1|kSecPaddingOAEP", VulnerabilityType::Rsa2048, Severity::Critical, "Objective-C RSA padding", "Migrate to PQC", Some("CWE-327")),
            
            // EC patterns
            (r"(?i)kSecAttrKeyTypeEC|kSecAttrKeyTypeECSECPrimeRandom", VulnerabilityType::Ecdsa, Severity::Critical, "Objective-C EC key type", "Migrate to PQC", Some("CWE-327")),
            (r"(?i)kSecKeyAlgorithmECDSA|kSecKeyAlgorithmECIES", VulnerabilityType::Ecdsa, Severity::Critical, "Objective-C ECDSA/ECIES", "Use Dilithium", Some("CWE-327")),
            (r"(?i)kSecKeyAlgorithmECDH", VulnerabilityType::Ecdh, Severity::Critical, "Objective-C ECDH", "Use Kyber", Some("CWE-327")),
            
            // Weak hashes (CommonCrypto)
            (r"(?i)CC_MD5\s*\(|CC_MD5_Init|CC_MD5_Update|CC_MD5_Final", VulnerabilityType::Md5, Severity::High, "Objective-C CC_MD5", "Use SHA256", Some("CWE-328")),
            (r"(?i)CC_SHA1\s*\(|CC_SHA1_Init|CC_SHA1_Update|CC_SHA1_Final", VulnerabilityType::Sha1, Severity::High, "Objective-C CC_SHA1", "Use SHA256", Some("CWE-328")),
            (r"(?i)kCCHmacAlgMD5", VulnerabilityType::Md5, Severity::High, "Objective-C HMAC-MD5", "Use HMAC-SHA256", Some("CWE-328")),
            (r"(?i)kCCHmacAlgSHA1", VulnerabilityType::Sha1, Severity::High, "Objective-C HMAC-SHA1", "Use HMAC-SHA256", Some("CWE-328")),
            
            // Weak ciphers (CommonCrypto)
            (r"(?i)kCCAlgorithmDES|CCCryptorCreate.*kCCAlgorithmDES", VulnerabilityType::Des, Severity::Critical, "Objective-C DES", "Use AES", Some("CWE-327")),
            (r"(?i)kCCAlgorithm3DES|CCCryptorCreate.*kCCAlgorithm3DES", VulnerabilityType::TripleDes, Severity::High, "Objective-C 3DES", "Use AES", Some("CWE-327")),
            (r"(?i)kCCAlgorithmRC4|CCCryptorCreate.*RC4", VulnerabilityType::Rc4, Severity::Critical, "Objective-C RC4", "Use AES", Some("CWE-327")),
            (r"(?i)kCCAlgorithmBlowfish", VulnerabilityType::Blowfish, Severity::Medium, "Objective-C Blowfish", "Use AES", Some("CWE-327")),
            (r"(?i)kCCAlgorithmCAST", VulnerabilityType::Des, Severity::Medium, "Objective-C CAST", "Use AES", Some("CWE-327")),
            
            // Weak random
            (r"(?i)arc4random\s*\(|arc4random_uniform\s*\(", VulnerabilityType::WeakRandom, Severity::Medium, "Objective-C arc4random", "Use SecRandomCopyBytes", Some("CWE-338")),
            (r"(?i)\brand\s*\(\s*\)|\bsrand\s*\(", VulnerabilityType::WeakRandom, Severity::High, "Objective-C rand()", "Use SecRandomCopyBytes", Some("CWE-338")),
            (r"(?i)random\s*\(\s*\)|srandom\s*\(", VulnerabilityType::WeakRandom, Severity::High, "Objective-C random()", "Use SecRandomCopyBytes", Some("CWE-338")),
            
            // Insecure TLS
            (r"(?i)kSSLProtocol2|kSSLProtocol3|kTLSProtocol1\b|kTLSProtocol11", VulnerabilityType::InsecureTls, Severity::High, "Objective-C insecure TLS", "Use TLS 1.2+", Some("CWE-326")),
            (r"(?i)SSLSetProtocolVersionMin.*kSSL|SSLSetProtocolVersionMax.*kSSL", VulnerabilityType::InsecureTls, Severity::High, "Objective-C SSL protocol version", "Use TLS 1.2+", Some("CWE-326")),
            (r"(?i)setAllowsAnyHTTPSCertificate.*YES|validatesDomainName.*NO", VulnerabilityType::InsecureTls, Severity::High, "Objective-C TLS validation disabled", "Enable validation", Some("CWE-295")),
            
            // OpenSSL patterns (if used)
            (r"(?i)RSA_generate_key|RSA_new|RSA_sign|RSA_verify", VulnerabilityType::Rsa2048, Severity::Critical, "Objective-C OpenSSL RSA", "Migrate to PQC", Some("CWE-327")),
            (r"(?i)EC_KEY_generate_key|EC_KEY_new|ECDSA_sign|ECDSA_verify", VulnerabilityType::Ecdsa, Severity::Critical, "Objective-C OpenSSL EC", "Migrate to PQC", Some("CWE-327")),
            (r"(?i)DSA_generate_key|DSA_sign|DSA_verify", VulnerabilityType::Dsa, Severity::Critical, "Objective-C OpenSSL DSA", "Use Dilithium", Some("CWE-327")),
            (r"(?i)DH_generate_key|DH_compute_key", VulnerabilityType::DhKeyExchange, Severity::Critical, "Objective-C OpenSSL DH", "Use Kyber", Some("CWE-327")),
            (r"(?i)EVP_md5|EVP_sha1", VulnerabilityType::Md5, Severity::High, "Objective-C OpenSSL weak hash", "Use SHA256", Some("CWE-328")),
            (r"(?i)EVP_des_|EVP_rc4|EVP_bf_", VulnerabilityType::Des, Severity::Critical, "Objective-C OpenSSL weak cipher", "Use AES", Some("CWE-327")),
        ];

        pattern_defs.into_iter().filter_map(|(pattern, vuln_type, severity, desc, rec, cwe)| {
            Regex::new(pattern).ok().map(|regex| ObjCPattern { 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];
        if let Some(line_start) = before.rfind('\n') {
            if before[line_start..].contains("//") { return true; }
        }
        let last_open = before.rfind("/*");
        let last_close = before.rfind("*/");
        matches!((last_open, last_close), (Some(o), Some(c)) if o > c) || matches!((last_open, last_close), (Some(_), None))
    }

    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"))
    }
}
