//! Swift-specific quantum vulnerability detection

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

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

pub struct SwiftAnalyzer {
    patterns: Vec<SwiftPattern>,
}

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

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

    fn compile_patterns() -> Vec<SwiftPattern> {
        let pattern_defs: Vec<(&str, VulnerabilityType, Severity, &'static str, &'static str, Option<&'static str>)> = vec![
            // RSA patterns
            (r"(?i)SecKeyCreateRandomKey\s*\(", VulnerabilityType::Rsa2048, Severity::Critical, "Swift SecKeyCreateRandomKey detected", "Migrate to post-quantum cryptography", Some("CWE-327")),
            (r"(?i)kSecAttrKeyTypeRSA", VulnerabilityType::Rsa2048, Severity::Critical, "Swift RSA key type detected", "Replace with PQC algorithms", Some("CWE-327")),
            (r"(?i)SecKeyAlgorithm\.rsa|\.rsaEncryption|\.rsaSignature", VulnerabilityType::Rsa2048, Severity::Critical, "Swift RSA algorithm detected", "Use post-quantum alternatives", Some("CWE-327")),
            (r"(?i)SecKeyGeneratePair\s*\(", VulnerabilityType::Rsa2048, Severity::Critical, "Swift SecKeyGeneratePair detected", "Review and migrate to PQC", Some("CWE-327")),
            
            // EC/ECDSA patterns (CryptoKit)
            (r"(?i)P256\s*\.|P256\.Signing|P256\.KeyAgreement", VulnerabilityType::Ecdsa, Severity::Critical, "Swift P-256 curve detected", "Migrate to PQC", Some("CWE-327")),
            (r"(?i)P384\s*\.|P384\.Signing|P384\.KeyAgreement", VulnerabilityType::Ecdsa, Severity::Critical, "Swift P-384 curve detected", "Migrate to PQC", Some("CWE-327")),
            (r"(?i)P521\s*\.|P521\.Signing|P521\.KeyAgreement", VulnerabilityType::Ecdsa, Severity::Critical, "Swift P-521 curve detected", "Migrate to PQC", Some("CWE-327")),
            (r"(?i)kSecAttrKeyTypeEC", VulnerabilityType::Ecdsa, Severity::Critical, "Swift EC key type detected", "EC is quantum-vulnerable", Some("CWE-327")),
            (r"(?i)SecKeyAlgorithm\.ecdsa|\.ecdsaSignature", VulnerabilityType::Ecdsa, Severity::Critical, "Swift ECDSA detected", "Use Dilithium", Some("CWE-327")),
            (r"(?i)\.ecdhKeyExchange|SecKeyCopyKeyExchangeResult", VulnerabilityType::Ecdh, Severity::Critical, "Swift ECDH detected", "Use Kyber KEM", Some("CWE-327")),
            
            // Edwards curves
            (r"(?i)Curve25519\s*\.|X25519|Ed25519", VulnerabilityType::Ecdh, Severity::Critical, "Swift Edwards curve detected", "Quantum-vulnerable", Some("CWE-327")),
            
            // Weak hashes (CommonCrypto)
            (r"(?i)CC_MD5\s*\(|CC_MD5_Init", VulnerabilityType::Md5, Severity::High, "Swift CC_MD5 detected", "Use SHA256", Some("CWE-328")),
            (r"(?i)CC_SHA1\s*\(|CC_SHA1_Init", VulnerabilityType::Sha1, Severity::High, "Swift CC_SHA1 detected", "Use SHA256", Some("CWE-328")),
            (r"(?i)Insecure\.MD5", VulnerabilityType::Md5, Severity::High, "Swift Insecure.MD5 detected", "Use SHA256", Some("CWE-328")),
            (r"(?i)Insecure\.SHA1", VulnerabilityType::Sha1, Severity::High, "Swift Insecure.SHA1 detected", "Use SHA256", Some("CWE-328")),
            (r"(?i)kCCHmacAlgMD5", VulnerabilityType::Md5, Severity::High, "Swift HMAC-MD5 detected", "Use HMAC-SHA256", Some("CWE-328")),
            (r"(?i)kCCHmacAlgSHA1", VulnerabilityType::Sha1, Severity::High, "Swift HMAC-SHA1 detected", "Use HMAC-SHA256", Some("CWE-328")),
            
            // Weak ciphers
            (r"(?i)kCCAlgorithmDES", VulnerabilityType::Des, Severity::Critical, "Swift DES detected", "Use AES.GCM", Some("CWE-327")),
            (r"(?i)kCCAlgorithm3DES", VulnerabilityType::TripleDes, Severity::High, "Swift 3DES detected", "Use AES.GCM", Some("CWE-327")),
            (r"(?i)kCCAlgorithmRC4", VulnerabilityType::Rc4, Severity::Critical, "Swift RC4 detected", "Use AES.GCM", Some("CWE-327")),
            (r"(?i)kCCAlgorithmBlowfish", VulnerabilityType::Blowfish, Severity::Medium, "Swift Blowfish detected", "Use AES.GCM", Some("CWE-327")),
            
            // Weak random
            (r"(?i)arc4random\s*\(", VulnerabilityType::WeakRandom, Severity::Medium, "Swift arc4random detected", "Use SecRandomCopyBytes", Some("CWE-338")),
            (r"(?i)srand48\s*\(|drand48\s*\(", VulnerabilityType::WeakRandom, Severity::High, "Swift drand48 detected", "Use SecRandomCopyBytes", Some("CWE-338")),
            
            // Insecure TLS
            (r"(?i)kSSLProtocol2|kSSLProtocol3|kTLSProtocol1\b", VulnerabilityType::InsecureTls, Severity::High, "Swift insecure TLS detected", "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| SwiftPattern { 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"))
    }
}
