use anyhow::Result;
use std::path::Path;
use tree_sitter::Node;

use crate::analyzers::ast_analyzer::AstAnalyzer;
use crate::types::{Severity, Vulnerability, VulnerabilityType};

use super::LanguageAnalyzer;

pub struct RustAnalyzer;

impl RustAnalyzer {
    pub fn new() -> Self {
        Self
    }
}

impl LanguageAnalyzer for RustAnalyzer {
    fn check_node(
        &self,
        node: &Node,
        source: &str,
        file_path: &Path,
        analyzer: &AstAnalyzer,
    ) -> Option<Vulnerability> {
        let node_type = node.kind();
        let node_text = match node.utf8_text(source.as_bytes()) {
            Ok(text) => text,
            Err(_) => return None,
        };

        match node_type {
            "call_expression" => {
                // RSA operations
                if node_text.contains("RsaPrivateKey::new") || 
                   node_text.contains("RsaPublicKey::new") ||
                   node_text.contains("generate_rsa") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Rsa2048,
                        Severity::Critical,
                        "RSA key generation detected",
                        "Migrate to pqcrypto crate for post-quantum crypto",
                        source,
                    ));
                }

                // ECDSA operations
                if node_text.contains("SigningKey::random") || 
                   node_text.contains("VerifyingKey::from") ||
                   node_text.contains("generate_keypair") {
                    let lower = node_text.to_lowercase();
                    if lower.contains("ecdsa") || lower.contains("p256") || 
                       lower.contains("p384") || lower.contains("secp") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Ecdsa,
                            Severity::Critical,
                            "ECDSA key generation detected",
                            "Migrate to pqcrypto crate for post-quantum signatures",
                            source,
                        ));
                    }
                }

                // Weak hash functions
                if node_text.contains("Md5::new") || node_text.contains("md5::compute") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Md5,
                        Severity::High,
                        "MD5 hash function detected",
                        "Replace with SHA-256 or SHA-3",
                        source,
                    ));
                }

                if node_text.contains("Sha1::new") || node_text.contains("sha1::compute") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Sha1,
                        Severity::High,
                        "SHA-1 hash function detected",
                        "Replace with SHA-256 or SHA-3",
                        source,
                    ));
                }

                // Weak ciphers
                if node_text.contains("Des::new") || node_text.contains("TdesEde3::new") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Des,
                        Severity::Critical,
                        "DES/3DES cipher detected",
                        "Replace with AES-256-GCM",
                        source,
                    ));
                }

                // Weak random
                if node_text.contains("rand::random") || node_text.contains("thread_rng") {
                    // Check if it's used in crypto context
                    if let Some(parent) = node.parent() {
                        if let Ok(parent_text) = parent.utf8_text(source.as_bytes()) {
                            if parent_text.contains("key") || parent_text.contains("nonce") || 
                               parent_text.contains("salt") || parent_text.contains("iv") {
                                return Some(analyzer.create_vulnerability(
                                    node,
                                    file_path,
                                    VulnerabilityType::WeakRandom,
                                    Severity::Medium,
                                    "Non-cryptographic RNG usage detected",
                                    "Use rand::rngs::OsRng or getrandom for cryptographic purposes",
                                    source,
                                ));
                            }
                        }
                    }
                }

                None
            }
            "use_declaration" => {
                // RSA crate imports
                if node_text.contains("rsa::") || node_text.contains("use rsa") {
                     return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Rsa2048,
                        Severity::Medium,
                        "RSA crate import detected",
                        "Migrate to post-quantum cryptography",
                        source,
                    ));
                }

                // ECDSA/Elliptic Curve imports
                if node_text.contains("p256::") || node_text.contains("k256::") || 
                   node_text.contains("ed25519::") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Ecdsa,
                        Severity::Medium,
                        "Elliptic curve crate import detected",
                        "Migrate to post-quantum cryptography",
                        source,
                    ));
                }

                None
            }
            _ => None,
        }
    }
}
