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 JavaAnalyzer;

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

    fn check_java_import(
        &self,
        node_text: &str,
        node: &Node,
        file_path: &Path,
        source: &str,
        analyzer: &AstAnalyzer,
    ) -> Option<Vulnerability> {
        let lower = node_text.to_lowercase();
        
        // java.security quantum-unsafe imports
        if lower.contains("java.security") {
            if lower.contains("keypairgenerator") || lower.contains("keyfactory") {
                return Some(analyzer.create_vulnerability(
                    node,
                    file_path,
                    VulnerabilityType::Rsa2048,
                    Severity::Low,
                    "java.security key generation import - verify algorithm is quantum-safe",
                    "Audit usage for RSA/ECDSA/DSA",
                    source,
                ));
            }
            if lower.contains("signature") {
                return Some(analyzer.create_vulnerability(
                    node,
                    file_path,
                    VulnerabilityType::Rsa2048,
                    Severity::Low,
                    "java.security.Signature import - verify algorithm is quantum-safe",
                    "Audit for RSA/ECDSA/DSA signatures",
                    source,
                ));
            }
        }
        
        // javax.crypto
        if lower.contains("javax.crypto") {
            if lower.contains("keyagreement") {
                return Some(analyzer.create_vulnerability(
                    node,
                    file_path,
                    VulnerabilityType::DhKeyExchange,
                    Severity::Low,
                    "javax.crypto.KeyAgreement import - verify algorithm is quantum-safe",
                    "Audit for DH/ECDH usage",
                    source,
                ));
            }
        }
        
        // BouncyCastle (popular crypto library)
        if lower.contains("org.bouncycastle") {
            if lower.contains("rsa") {
                return Some(analyzer.create_vulnerability(
                    node,
                    file_path,
                    VulnerabilityType::Rsa2048,
                    Severity::Medium,
                    "BouncyCastle RSA import detected",
                    "Migrate to post-quantum cryptography",
                    source,
                ));
            }
            if lower.contains("ecdsa") || lower.contains("ec.") {
                return Some(analyzer.create_vulnerability(
                    node,
                    file_path,
                    VulnerabilityType::Ecdsa,
                    Severity::Medium,
                    "BouncyCastle EC import detected",
                    "Migrate to post-quantum cryptography",
                    source,
                ));
            }
            if lower.contains("dsa") {
                return Some(analyzer.create_vulnerability(
                    node,
                    file_path,
                    VulnerabilityType::Dsa,
                    Severity::Medium,
                    "BouncyCastle DSA import detected",
                    "Migrate to post-quantum cryptography",
                    source,
                ));
            }
        }
        
        None
    }
}

impl LanguageAnalyzer for JavaAnalyzer {
    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 {
            "method_invocation" => {
                // KeyPairGenerator
                if node_text.contains("KeyPairGenerator.getInstance") {
                    let lower = node_text.to_lowercase();
                    if lower.contains("rsa") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Rsa2048,
                            Severity::Critical,
                            "Java RSA KeyPairGenerator detected",
                            "Migrate to post-quantum key encapsulation",
                            source,
                        ));
                    }
                    if lower.contains("ec") || lower.contains("ecdsa") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Ecdsa,
                            Severity::Critical,
                            "Java EC KeyPairGenerator detected",
                            "Migrate to post-quantum cryptography",
                            source,
                        ));
                    }
                    if lower.contains("dsa") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Dsa,
                            Severity::Critical,
                            "Java DSA KeyPairGenerator detected",
                            "Migrate to post-quantum signatures",
                            source,
                        ));
                    }
                    if lower.contains("dh") || lower.contains("diffie") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::DhKeyExchange,
                            Severity::Critical,
                            "Java DH KeyPairGenerator detected",
                            "Migrate to post-quantum key exchange",
                            source,
                        ));
                    }
                }

                // Signature
                if node_text.contains("Signature.getInstance") {
                    let lower = node_text.to_lowercase();
                    if lower.contains("rsa") || lower.contains("ecdsa") || lower.contains("dsa") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Rsa2048,
                            Severity::Critical,
                            "Java quantum-unsafe Signature algorithm detected",
                            "Migrate to CRYSTALS-Dilithium",
                            source,
                        ));
                    }
                }

                // MessageDigest
                if node_text.contains("MessageDigest.getInstance") {
                    let lower = node_text.to_lowercase();
                    if lower.contains("md5") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Md5,
                            Severity::High,
                            "Java MD5 MessageDigest detected",
                            "Replace with SHA-256 or SHA-3",
                            source,
                        ));
                    }
                    if lower.contains("sha-1") || lower.contains("sha1") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Sha1,
                            Severity::High,
                            "Java SHA-1 MessageDigest detected",
                            "Replace with SHA-256 or SHA-3",
                            source,
                        ));
                    }
                }

                // Cipher
                if node_text.contains("Cipher.getInstance") {
                    let lower = node_text.to_lowercase();
                    if lower.contains("des") && !lower.contains("aes") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Des,
                            Severity::Critical,
                            "Java DES Cipher detected",
                            "Replace with AES-256-GCM",
                            source,
                        ));
                    }
                    if lower.contains("rc4") || lower.contains("arcfour") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Rc4,
                            Severity::Critical,
                            "Java RC4 Cipher detected",
                            "Replace with AES-256-GCM or ChaCha20-Poly1305",
                            source,
                        ));
                    }
                }

                // KeyAgreement (DH/ECDH)
                if node_text.contains("KeyAgreement.getInstance") {
                    let lower = node_text.to_lowercase();
                    if lower.contains("dh") || lower.contains("ecdh") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::DhKeyExchange,
                            Severity::Critical,
                            "Java DH/ECDH KeyAgreement detected",
                            "Migrate to CRYSTALS-Kyber for key exchange",
                            source,
                        ));
                    }
                }

                // Random (weak)
                if node_text.contains("new Random(") && !node_text.contains("SecureRandom") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::WeakRandom,
                        Severity::Medium,
                        "Java non-cryptographic Random detected",
                        "Use SecureRandom for cryptographic operations",
                        source,
                    ));
                }

                None
            }
            // CRITICAL FIX #3: Java import detection
            "import_declaration" => {
                self.check_java_import(node_text, node, file_path, source, analyzer)
            }
            "string_literal" => {
                analyzer.check_string_literal(node_text, node, file_path, source, node)
            }
            "decimal_integer_literal" => {
                analyzer.check_key_size_literal(node_text, node, file_path, source)
            }
            _ => None,
        }
    }
}
