//! Solidity-specific quantum vulnerability detection

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

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

pub struct SolidityAnalyzer {
    patterns: Vec<SolidityPattern>,
}

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

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

    fn compile_patterns() -> Vec<SolidityPattern> {
        let pattern_defs: Vec<(&str, VulnerabilityType, Severity, &'static str, &'static str, Option<&'static str>)> = vec![
            // ECDSA patterns (primary concern for blockchain)
            (r"(?i)ecrecover\s*\(", VulnerabilityType::Ecdsa, Severity::Critical, "Solidity ecrecover detected", "ECDSA signatures are quantum-vulnerable", Some("CWE-327")),
            (r"(?i)ECDSA\.recover|ECDSA\.tryRecover", VulnerabilityType::Ecdsa, Severity::Critical, "Solidity OpenZeppelin ECDSA", "EC signatures are quantum-vulnerable", Some("CWE-327")),
            (r"(?i)SignatureChecker\.isValidSignatureNow", VulnerabilityType::Ecdsa, Severity::Critical, "Solidity signature verification", "EC-based verification is quantum-vulnerable", Some("CWE-327")),
            (r"(?i)\.sign\s*\(|\.verify\s*\(.*signature", VulnerabilityType::Ecdsa, Severity::Critical, "Solidity EC signature operation", "Plan for PQC migration", Some("CWE-327")),
            
            // secp256k1 (Ethereum's curve)
            (r"(?i)secp256k1|Secp256k1", VulnerabilityType::Ecdsa, Severity::Critical, "Solidity secp256k1 curve reference", "secp256k1 is quantum-vulnerable", Some("CWE-327")),
            
            // Weak hashes
            (r"(?i)keccak256\s*\(|sha3\s*\(", VulnerabilityType::Sha1, Severity::Medium, "Solidity keccak256/sha3 (quantum-resistant but monitor)", "Keccak is believed quantum-resistant", Some("CWE-328")),
            (r"(?i)sha256\s*\(", VulnerabilityType::Sha1, Severity::Low, "Solidity sha256 detected", "SHA256 is believed quantum-resistant", Some("CWE-328")),
            (r"(?i)ripemd160\s*\(", VulnerabilityType::Sha1, Severity::Medium, "Solidity ripemd160 detected", "Consider stronger hash functions", Some("CWE-328")),
            
            // Weak random (blockchain-specific)
            (r"(?i)block\.timestamp|block\.difficulty|block\.number|blockhash\s*\(", VulnerabilityType::WeakRandom, Severity::High, "Solidity block-based randomness", "Use Chainlink VRF or similar", Some("CWE-338")),
            (r"(?i)keccak256\s*\(.*block\.|abi\.encodePacked\s*\(.*block\.", VulnerabilityType::WeakRandom, Severity::High, "Solidity predictable randomness", "Use verifiable random functions", Some("CWE-338")),
            
            // Private key handling
            (r"(?i)privateKey|private_key|secretKey|secret_key", VulnerabilityType::HardcodedKey, Severity::Critical, "Solidity private key reference", "Never store private keys in contracts", Some("CWE-798")),
            
            // Signature schemes
            (r"(?i)EIP712|_TYPEHASH|DOMAIN_SEPARATOR", VulnerabilityType::Ecdsa, Severity::Medium, "Solidity EIP-712 typing", "EIP-712 uses ECDSA (quantum-vulnerable)", Some("CWE-327")),
            
            // Merkle tree (often used with EC signatures)
            (r"(?i)MerkleProof\.verify|merkleRoot|merkleProof", VulnerabilityType::Sha1, Severity::Low, "Solidity Merkle proof", "Review if used with EC signatures", Some("CWE-327")),
        ];

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