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

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

    fn check_js_import(
        &self,
        node_text: &str,
        node: &Node,
        file_path: &Path,
        source: &str,
        analyzer: &AstAnalyzer,
    ) -> Option<Vulnerability> {
        let lower = node_text.to_lowercase();
        
        // Check for quantum-unsafe crypto library imports
        if lower.contains("node-forge") || lower.contains("forge") {
            return Some(analyzer.create_vulnerability(
                node,
                file_path,
                VulnerabilityType::Rsa2048,
                Severity::Medium,
                "node-forge library import detected - contains quantum-unsafe algorithms",
                "Consider post-quantum cryptography libraries",
                source,
            ));
        }
        
        if lower.contains("jsrsasign") {
            return Some(analyzer.create_vulnerability(
                node,
                file_path,
                VulnerabilityType::Rsa2048,
                Severity::Medium,
                "jsrsasign library import detected - RSA/ECDSA library",
                "Migrate to post-quantum cryptography",
                source,
            ));
        }
        
        if lower.contains("elliptic") {
            return Some(analyzer.create_vulnerability(
                node,
                file_path,
                VulnerabilityType::Ecdsa,
                Severity::Medium,
                "elliptic library import detected - EC cryptography",
                "Migrate to post-quantum cryptography",
                source,
            ));
        }
        
        if lower.contains("crypto-js") && (lower.contains("rsa") || lower.contains("ecdsa")) {
            return Some(analyzer.create_vulnerability(
                node,
                file_path,
                VulnerabilityType::Rsa2048,
                Severity::Medium,
                "crypto-js quantum-unsafe algorithm import detected",
                "Use post-quantum alternatives",
                source,
            ));
        }
        
        if lower.contains("jose") || lower.contains("jsonwebtoken") {
            // JWT libraries often use RSA/ECDSA
            return Some(analyzer.create_vulnerability(
                node,
                file_path,
                VulnerabilityType::Rsa2048,
                Severity::Medium,
                "JWT library import detected - typically uses RSA/ECDSA",
                "Verify JWT signing algorithm is quantum-safe",
                source,
            ));
        }
        
        None
    }

    fn check_js_require(
        &self,
        node_text: &str,
        node: &Node,
        file_path: &Path,
        source: &str,
        analyzer: &AstAnalyzer,
    ) -> Option<Vulnerability> {
        // Similar logic to import detection
        self.check_js_import(node_text, node, file_path, source, analyzer)
    }
}

impl LanguageAnalyzer for JavaScriptAnalyzer {
    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" => {
                let callee = analyzer.get_callee_name(node, source)?;

                // Check for crypto function calls
                if callee.contains("createSign") || callee.contains("createVerify") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Rsa2048,
                        Severity::Critical,
                        "RSA/ECDSA signing operation detected",
                        "Migrate to CRYSTALS-Dilithium for digital signatures",
                        source,
                    ));
                }

                // CRITICAL FIX #4: Improved generateKeyPair detection
                if callee.contains("generateKeyPair") || callee.contains("generateKeyPairSync") {
                    let args_text = analyzer.get_call_args_text(node, source);
                    let lower_args = args_text.to_lowercase();
                    
                    // Check for quantum-unsafe algorithms
                    if lower_args.contains("rsa") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Rsa2048,
                            Severity::Critical,
                            "RSA key generation detected",
                            "Migrate to CRYSTALS-Kyber for key encapsulation",
                            source,
                        ));
                    }
                    if lower_args.contains("ec") || lower_args.contains("ecdsa") || lower_args.contains("ecdh") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Ecdsa,
                            Severity::Critical,
                            "Elliptic curve key generation detected",
                            "Migrate to CRYSTALS-Kyber/Dilithium for PQC",
                            source,
                        ));
                    }
                    // CRITICAL FIX #4: Add DSA and DH detection
                    if lower_args.contains("dsa") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Dsa,
                            Severity::Critical,
                            "DSA key generation detected",
                            "Migrate to CRYSTALS-Dilithium for digital signatures",
                            source,
                        ));
                    }
                    if lower_args.contains("dh") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::DhKeyExchange,
                            Severity::Critical,
                            "Diffie-Hellman key generation detected",
                            "Migrate to CRYSTALS-Kyber for key exchange",
                            source,
                        ));
                    }
                    
                    // If no quantum-safe algorithm detected, flag it as suspicious
                    if !lower_args.contains("kyber") && !lower_args.contains("dilithium") && 
                       !lower_args.contains("sphincs") && !lower_args.contains("ml-kem") && 
                       !lower_args.contains("ml-dsa") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::RsaOther,
                            Severity::High,
                            "Key generation with unrecognized algorithm - verify quantum-safety",
                            "Ensure using post-quantum cryptography (Kyber, Dilithium, SPHINCS+)",
                            source,
                        ));
                    }
                }

                // CRITICAL FIX #8: Add Web Crypto API detection
                if callee.contains("subtle.generateKey") || callee.contains("crypto.subtle.generateKey") {
                    let args_text = analyzer.get_call_args_text(node, source);
                    let lower_args = args_text.to_lowercase();
                    
                    if lower_args.contains("rsa") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Rsa2048,
                            Severity::Critical,
                            "Web Crypto API RSA key generation detected",
                            "Migrate to post-quantum cryptography",
                            source,
                        ));
                    }
                    if lower_args.contains("ecdsa") || lower_args.contains("ecdh") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Ecdsa,
                            Severity::Critical,
                            "Web Crypto API EC key generation detected",
                            "Migrate to post-quantum cryptography",
                            source,
                        ));
                    }
                }

                if callee.contains("subtle.sign") || callee.contains("crypto.subtle.sign") {
                    let args_text = analyzer.get_call_args_text(node, source);
                    let lower_args = args_text.to_lowercase();
                    
                    if lower_args.contains("rsa") || lower_args.contains("ecdsa") {
                        return Some(analyzer.create_vulnerability(
                            node,
                            file_path,
                            VulnerabilityType::Ecdsa,
                            Severity::Critical,
                            "Web Crypto API quantum-unsafe signing detected",
                            "Migrate to CRYSTALS-Dilithium",
                            source,
                        ));
                    }
                }

                if callee.contains("createECDH") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Ecdh,
                        Severity::Critical,
                        "ECDH key exchange detected",
                        "Migrate to CRYSTALS-Kyber for key exchange",
                        source,
                    ));
                }

                if callee.contains("createDiffieHellman") || callee.contains("getDiffieHellman") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::DhKeyExchange,
                        Severity::Critical,
                        "Diffie-Hellman key exchange detected",
                        "Migrate to CRYSTALS-Kyber for key exchange",
                        source,
                    ));
                }

                if callee.contains("createHash") {
                    let args_text = analyzer.get_call_args_text(node, source);
                    if args_text.contains("sha1") || args_text.contains("SHA1") {
                        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,
                        ));
                    }
                    if args_text.contains("md5") || args_text.contains("MD5") {
                        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 callee == "Math.random" {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::WeakRandom,
                        Severity::High,
                        "Weak random number generator (Math.random) detected",
                        "Use crypto.randomBytes() for cryptographic operations",
                        source,
                    ));
                }

                // CRITICAL FIX #8: Add third-party library detection
                // node-forge
                if callee.contains("forge.pki.rsa") || callee.contains("forge.rsa") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Rsa2048,
                        Severity::Critical,
                        "node-forge RSA usage detected",
                        "Migrate to post-quantum cryptography",
                        source,
                    ));
                }

                // jsrsasign
                if callee.contains("KJUR.crypto") || callee.contains("KEYUTIL.generateKeypair") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Rsa2048,
                        Severity::Critical,
                        "jsrsasign quantum-unsafe crypto detected",
                        "Migrate to post-quantum cryptography",
                        source,
                    ));
                }

                // elliptic library
                if callee.contains("elliptic.ec") || callee.contains("EC.genKeyPair") {
                    return Some(analyzer.create_vulnerability(
                        node,
                        file_path,
                        VulnerabilityType::Ecdsa,
                        Severity::Critical,
                        "elliptic library EC usage detected",
                        "Migrate to post-quantum cryptography",
                        source,
                    ));
                }

                None
            }
            // CRITICAL FIX #3: Add import detection for JavaScript/TypeScript
            "import_statement" | "import_specifier" => {
                self.check_js_import(node_text, node, file_path, source, analyzer)
            }
            "call_expression" if node_text.contains("require(") => {
                self.check_js_require(node_text, node, file_path, source, analyzer)
            }
            "string" | "template_string" => {
                analyzer.check_string_literal(node_text, node, file_path, source, node)
            }
            // CRITICAL FIX #9: Detect key size literals
            "number" => {
                analyzer.check_key_size_literal(node_text, node, file_path, source)
            }
            _ => None,
        }
    }
}
