//! Security profiles and rules framework
//!
//! Adaptive security guidelines based on project type, characteristics, and use cases.
//! Includes SBOM, dependency scanning, secret detection, compliance frameworks, etc.

use crate::error::Result;
use crate::types::ProjectType;
use serde::{Deserialize, Serialize};

/// Security profile for a project
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SecurityProfile {
    /// REST/GraphQL API endpoint (public or internal)
    WebApi,
    /// Command-line tool
    CliTool,
    /// Data processing (ETL, batch jobs)
    DataProcessing,
    /// IoT/Embedded device
    IoT,
    /// Machine Learning model
    MachineLearning,
    /// Open source library
    OpenSourceLib,
    /// Enterprise application
    Enterprise,
    /// Desktop/GUI application
    Desktop,
    /// Mobile application
    Mobile,
    /// Microservice
    Microservice,
    /// Custom profile
    Custom(String),
}

impl std::fmt::Display for SecurityProfile {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::WebApi => write!(f, "web-api"),
            Self::CliTool => write!(f, "cli-tool"),
            Self::DataProcessing => write!(f, "data-processing"),
            Self::IoT => write!(f, "iot"),
            Self::MachineLearning => write!(f, "ml"),
            Self::OpenSourceLib => write!(f, "oss-lib"),
            Self::Enterprise => write!(f, "enterprise"),
            Self::Desktop => write!(f, "desktop"),
            Self::Mobile => write!(f, "mobile"),
            Self::Microservice => write!(f, "microservice"),
            Self::Custom(s) => write!(f, "custom-{}", s),
        }
    }
}

/// Security characteristic/flag
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum SecurityCharacteristic {
    /// Handles user authentication
    Authentication,
    /// Handles sensitive data (PII, PHI, financial)
    SensitiveData,
    /// Exposed to network/internet
    NetworkExposed,
    /// Handles payments
    Payments,
    /// Uses cryptography
    Cryptography,
    /// Handles secrets/keys
    SecretsManagement,
    /// AI/ML model (potential bias/safety)
    AiModel,
    /// Has database access
    DatabaseAccess,
    /// File system access
    FileSystemAccess,
    /// Admin/root privileges required
    PrivilegedAccess,
    /// Real-time/safety-critical
    SafetyCritical,
    /// HIPAA compliance required
    Hipaa,
    /// GDPR compliance required
    Gdpr,
    /// PCI-DSS compliance required
    PciDss,
    /// SOC2 compliance required
    Soc2,
}

/// Security rule category
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum RuleCategory {
    /// Dependency management and CVE scanning
    Dependencies,
    /// Secret/credential detection
    SecretsDetection,
    /// Code quality and vulnerability scanning
    CodeQuality,
    /// Authentication and authorization
    AuthZ,
    /// Data protection and encryption
    DataProtection,
    /// Access control and RBAC
    AccessControl,
    /// Compliance requirements
    Compliance,
    /// Deployment security
    Deployment,
    /// Network security
    Network,
    /// Container/image security
    Container,
    /// API security
    ApiSecurity,
    /// Logging and monitoring
    Logging,
    /// Incident response
    IncidentResponse,
    /// Software Bill of Materials
    Sbom,
}

/// Security rule
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityRule {
    /// Rule ID (e.g., "deps-001")
    pub id: String,
    /// Rule name
    pub name: String,
    /// Rule category
    pub category: RuleCategory,
    /// Description
    pub description: String,
    /// Severity: critical, high, medium, low
    pub severity: String,
    /// Whether rule is mandatory
    pub mandatory: bool,
    /// Implementation guidance
    pub guidance: String,
    /// Tools to use
    pub tools: Vec<String>,
    /// Relevant compliance frameworks
    pub compliance_frameworks: Vec<String>,
}

/// Security profile configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityProfileConfig {
    /// Security profile type
    pub profile: SecurityProfile,
    /// Project characteristics
    pub characteristics: Vec<SecurityCharacteristic>,
    /// Enabled rules
    pub rules: Vec<SecurityRule>,
    /// Custom rules
    pub custom_rules: Vec<SecurityRule>,
    /// Compliance frameworks to follow
    pub compliance_frameworks: Vec<String>,
    /// SBOM generation enabled
    pub sbom_enabled: bool,
    /// SBOM format (spdx, cyclonedx)
    pub sbom_format: String,
    /// Dependency scanning enabled
    pub dependency_scanning: bool,
    /// Secret detection enabled
    pub secret_detection: bool,
    /// Code quality checks enabled
    pub code_quality: bool,
    /// Maximum allowed CVE severity
    pub max_allowed_cve_severity: String,
}

/// Security assessment result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityAssessment {
    /// Profile assessed
    pub profile: SecurityProfile,
    /// Overall risk level
    pub risk_level: String,
    /// Rules passed
    pub rules_passed: usize,
    /// Rules failed
    pub rules_failed: usize,
    /// Critical issues
    pub critical_issues: Vec<String>,
    /// Recommendations
    pub recommendations: Vec<String>,
}

/// Security rules engine
#[derive(Debug)]
pub struct SecurityEngine;

impl SecurityEngine {
    /// Get security profile for project type
    pub fn get_profile_for_type(project_type: &ProjectType) -> SecurityProfile {
        match project_type {
            ProjectType::RustWeb => SecurityProfile::WebApi,
            ProjectType::RustCli => SecurityProfile::CliTool,
            ProjectType::RustEmbedded => SecurityProfile::IoT,
            ProjectType::MultiLang => SecurityProfile::Enterprise,
            ProjectType::NuShellScript => SecurityProfile::CliTool,
            ProjectType::Custom(s) => {
                if s.contains("api") {
                    SecurityProfile::WebApi
                } else if s.contains("cli") {
                    SecurityProfile::CliTool
                } else if s.contains("ml") {
                    SecurityProfile::MachineLearning
                } else if s.contains("data") {
                    SecurityProfile::DataProcessing
                } else {
                    SecurityProfile::Custom(s.clone())
                }
            }
        }
    }

    /// Get default rules for profile
    pub fn get_default_rules(profile: &SecurityProfile) -> Vec<SecurityRule> {
        match profile {
            SecurityProfile::WebApi => Self::rules_for_web_api(),
            SecurityProfile::CliTool => Self::rules_for_cli(),
            SecurityProfile::DataProcessing => Self::rules_for_data_processing(),
            SecurityProfile::IoT => Self::rules_for_iot(),
            SecurityProfile::MachineLearning => Self::rules_for_ml(),
            SecurityProfile::OpenSourceLib => Self::rules_for_oss(),
            SecurityProfile::Enterprise => Self::rules_for_enterprise(),
            SecurityProfile::Desktop => Self::rules_for_desktop(),
            SecurityProfile::Mobile => Self::rules_for_mobile(),
            SecurityProfile::Microservice => Self::rules_for_microservice(),
            SecurityProfile::Custom(_) => Self::rules_for_custom(),
        }
    }

    /// Create security profile config
    pub fn create_profile_config(
        profile: SecurityProfile,
        characteristics: Vec<SecurityCharacteristic>,
    ) -> Result<SecurityProfileConfig> {
        let mut rules = Self::get_default_rules(&profile);

        // Add additional rules based on characteristics
        for characteristic in &characteristics {
            let char_rules = Self::get_rules_for_characteristic(characteristic);
            rules.extend(char_rules);
        }

        // Determine compliance frameworks based on characteristics
        let compliance_frameworks = Self::get_compliance_frameworks(&characteristics);

        Ok(SecurityProfileConfig {
            profile,
            characteristics,
            rules,
            custom_rules: Vec::new(),
            compliance_frameworks,
            sbom_enabled: true,
            sbom_format: "spdx".to_string(),
            dependency_scanning: true,
            secret_detection: true,
            code_quality: true,
            max_allowed_cve_severity: "high".to_string(),
        })
    }

    /// Assess project security posture
    pub fn assess_security(
        config: &SecurityProfileConfig,
        passed_rules: usize,
        failed_rules: usize,
        issues: Vec<String>,
    ) -> SecurityAssessment {
        let total_rules = config.rules.len();
        let critical_issues: Vec<String> = issues
            .iter()
            .filter(|issue| issue.to_lowercase().contains("critical"))
            .cloned()
            .collect();

        let risk_level = if critical_issues.is_empty() && failed_rules == 0 {
            "low".to_string()
        } else if failed_rules < total_rules / 3 {
            "medium".to_string()
        } else if failed_rules < total_rules * 2 / 3 {
            "high".to_string()
        } else {
            "critical".to_string()
        };

        let recommendations = Self::generate_recommendations(&config.profile, &critical_issues);

        SecurityAssessment {
            profile: config.profile.clone(),
            risk_level,
            rules_passed: passed_rules,
            rules_failed: failed_rules,
            critical_issues,
            recommendations,
        }
    }

    // Helper methods

    fn rules_for_web_api() -> Vec<SecurityRule> {
        vec![
            SecurityRule {
                id: "api-001".to_string(),
                name: "Dependency Scanning".to_string(),
                category: RuleCategory::Dependencies,
                description: "Scan dependencies for known CVEs".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Use cargo audit, npm audit, or safety to scan for vulnerabilities"
                    .to_string(),
                tools: vec!["cargo-audit".to_string(), "npm-audit".to_string()],
                compliance_frameworks: vec!["OWASP".to_string()],
            },
            SecurityRule {
                id: "api-002".to_string(),
                name: "Secret Detection".to_string(),
                category: RuleCategory::SecretsDetection,
                description: "Detect hardcoded secrets in codebase".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Use git-secrets, truffleHog, or GitGuardian".to_string(),
                tools: vec!["git-secrets".to_string(), "truffleHog".to_string()],
                compliance_frameworks: vec!["OWASP".to_string()],
            },
            SecurityRule {
                id: "api-003".to_string(),
                name: "Input Validation".to_string(),
                category: RuleCategory::CodeQuality,
                description: "Validate and sanitize all user inputs".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Use validation libraries, prevent injection attacks".to_string(),
                tools: vec!["serde".to_string(), "validator".to_string()],
                compliance_frameworks: vec!["OWASP Top 10".to_string()],
            },
            SecurityRule {
                id: "api-004".to_string(),
                name: "Authentication & Authorization".to_string(),
                category: RuleCategory::AuthZ,
                description: "Implement proper auth mechanisms".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Use OAuth2, JWT, or similar frameworks".to_string(),
                tools: vec!["jsonwebtoken".to_string(), "oauth2".to_string()],
                compliance_frameworks: vec!["OWASP".to_string()],
            },
            SecurityRule {
                id: "api-005".to_string(),
                name: "HTTPS/TLS".to_string(),
                category: RuleCategory::Network,
                description: "Enforce HTTPS/TLS for all communications".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Use TLS 1.2+, configure proper certificates".to_string(),
                tools: vec!["rustls".to_string(), "OpenSSL".to_string()],
                compliance_frameworks: vec!["OWASP".to_string()],
            },
            SecurityRule {
                id: "api-006".to_string(),
                name: "SBOM Generation".to_string(),
                category: RuleCategory::Sbom,
                description: "Generate Software Bill of Materials".to_string(),
                severity: "high".to_string(),
                mandatory: true,
                guidance: "Generate SPDX or CycloneDX SBOM files".to_string(),
                tools: vec!["cargo-sbom".to_string(), "syft".to_string()],
                compliance_frameworks: vec!["NTIA".to_string()],
            },
        ]
    }

    fn rules_for_cli() -> Vec<SecurityRule> {
        vec![
            SecurityRule {
                id: "cli-001".to_string(),
                name: "Dependency Scanning".to_string(),
                category: RuleCategory::Dependencies,
                description: "Scan dependencies for known CVEs".to_string(),
                severity: "high".to_string(),
                mandatory: true,
                guidance: "Run cargo audit or npm audit".to_string(),
                tools: vec!["cargo-audit".to_string()],
                compliance_frameworks: vec!["OWASP".to_string()],
            },
            SecurityRule {
                id: "cli-002".to_string(),
                name: "Secret Detection".to_string(),
                category: RuleCategory::SecretsDetection,
                description: "Detect hardcoded credentials".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Check for API keys, tokens in code".to_string(),
                tools: vec!["git-secrets".to_string()],
                compliance_frameworks: vec![],
            },
            SecurityRule {
                id: "cli-003".to_string(),
                name: "Input Validation".to_string(),
                category: RuleCategory::CodeQuality,
                description: "Validate command-line arguments".to_string(),
                severity: "high".to_string(),
                mandatory: true,
                guidance: "Use clap or similar for argument parsing".to_string(),
                tools: vec!["clap".to_string()],
                compliance_frameworks: vec![],
            },
            SecurityRule {
                id: "cli-004".to_string(),
                name: "SBOM Generation".to_string(),
                category: RuleCategory::Sbom,
                description: "Generate SBOM for dependencies".to_string(),
                severity: "medium".to_string(),
                mandatory: false,
                guidance: "Document all dependencies and versions".to_string(),
                tools: vec!["cargo-sbom".to_string()],
                compliance_frameworks: vec![],
            },
        ]
    }

    fn rules_for_data_processing() -> Vec<SecurityRule> {
        vec![
            SecurityRule {
                id: "data-001".to_string(),
                name: "Data Encryption at Rest".to_string(),
                category: RuleCategory::DataProtection,
                description: "Encrypt sensitive data at rest".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Use AES-256 or similar encryption".to_string(),
                tools: vec!["aes-gcm".to_string(), "cryptography".to_string()],
                compliance_frameworks: vec!["GDPR".to_string(), "HIPAA".to_string()],
            },
            SecurityRule {
                id: "data-002".to_string(),
                name: "Data Encryption in Transit".to_string(),
                category: RuleCategory::Network,
                description: "Encrypt data in transit".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Use TLS 1.2+ for all network transfers".to_string(),
                tools: vec!["rustls".to_string()],
                compliance_frameworks: vec!["GDPR".to_string()],
            },
            SecurityRule {
                id: "data-003".to_string(),
                name: "Access Logging".to_string(),
                category: RuleCategory::Logging,
                description: "Log all data access and modifications".to_string(),
                severity: "high".to_string(),
                mandatory: true,
                guidance: "Implement comprehensive audit logs".to_string(),
                tools: vec!["tracing".to_string(), "slog".to_string()],
                compliance_frameworks: vec!["GDPR".to_string(), "HIPAA".to_string()],
            },
            SecurityRule {
                id: "data-004".to_string(),
                name: "PII Handling".to_string(),
                category: RuleCategory::DataProtection,
                description: "Protect Personally Identifiable Information".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Minimize PII collection, anonymize where possible".to_string(),
                tools: vec![],
                compliance_frameworks: vec!["GDPR".to_string(), "CCPA".to_string()],
            },
        ]
    }

    fn rules_for_iot() -> Vec<SecurityRule> {
        vec![
            SecurityRule {
                id: "iot-001".to_string(),
                name: "Firmware Updates".to_string(),
                category: RuleCategory::Deployment,
                description: "Secure firmware update mechanism".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Implement signed firmware, rollback protection".to_string(),
                tools: vec![],
                compliance_frameworks: vec![],
            },
            SecurityRule {
                id: "iot-002".to_string(),
                name: "Secure Boot".to_string(),
                category: RuleCategory::Deployment,
                description: "Implement secure boot process".to_string(),
                severity: "high".to_string(),
                mandatory: true,
                guidance: "Verify bootloader signatures".to_string(),
                tools: vec![],
                compliance_frameworks: vec![],
            },
            SecurityRule {
                id: "iot-003".to_string(),
                name: "Network Security".to_string(),
                category: RuleCategory::Network,
                description: "Secure IoT network communication".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Use TLS, mutual authentication".to_string(),
                tools: vec!["rustls".to_string()],
                compliance_frameworks: vec![],
            },
        ]
    }

    fn rules_for_ml() -> Vec<SecurityRule> {
        vec![
            SecurityRule {
                id: "ml-001".to_string(),
                name: "Model Provenance".to_string(),
                category: RuleCategory::Compliance,
                description: "Track model origin and modifications".to_string(),
                severity: "high".to_string(),
                mandatory: true,
                guidance: "Document model training data, versions".to_string(),
                tools: vec!["dvc".to_string()],
                compliance_frameworks: vec![],
            },
            SecurityRule {
                id: "ml-002".to_string(),
                name: "Adversarial Testing".to_string(),
                category: RuleCategory::CodeQuality,
                description: "Test for adversarial robustness".to_string(),
                severity: "high".to_string(),
                mandatory: false,
                guidance: "Perform adversarial input testing".to_string(),
                tools: vec![],
                compliance_frameworks: vec![],
            },
            SecurityRule {
                id: "ml-003".to_string(),
                name: "Bias Detection".to_string(),
                category: RuleCategory::CodeQuality,
                description: "Detect and mitigate model bias".to_string(),
                severity: "high".to_string(),
                mandatory: true,
                guidance: "Test for demographic parity, fairness".to_string(),
                tools: vec![],
                compliance_frameworks: vec![],
            },
        ]
    }

    fn rules_for_oss() -> Vec<SecurityRule> {
        vec![
            SecurityRule {
                id: "oss-001".to_string(),
                name: "License Compliance".to_string(),
                category: RuleCategory::Compliance,
                description: "Ensure license compliance".to_string(),
                severity: "high".to_string(),
                mandatory: true,
                guidance: "Check transitive dependencies for compatible licenses".to_string(),
                tools: vec!["cargo-license".to_string(), "license-finder".to_string()],
                compliance_frameworks: vec!["SPDX".to_string()],
            },
            SecurityRule {
                id: "oss-002".to_string(),
                name: "Security Disclosure Policy".to_string(),
                category: RuleCategory::IncidentResponse,
                description: "Have security disclosure policy".to_string(),
                severity: "high".to_string(),
                mandatory: true,
                guidance: "Create SECURITY.md with responsible disclosure".to_string(),
                tools: vec![],
                compliance_frameworks: vec![],
            },
            SecurityRule {
                id: "oss-003".to_string(),
                name: "Code Review".to_string(),
                category: RuleCategory::CodeQuality,
                description: "Mandatory code review for contributions".to_string(),
                severity: "high".to_string(),
                mandatory: true,
                guidance: "All PRs require review before merge".to_string(),
                tools: vec!["github".to_string()],
                compliance_frameworks: vec![],
            },
        ]
    }

    fn rules_for_enterprise() -> Vec<SecurityRule> {
        // Combine multiple security requirements
        let mut rules = vec![];
        rules.extend(Self::rules_for_web_api());
        rules.extend(Self::rules_for_data_processing());
        rules
    }

    fn rules_for_desktop() -> Vec<SecurityRule> {
        vec![SecurityRule {
            id: "desk-001".to_string(),
            name: "Code Signing".to_string(),
            category: RuleCategory::Deployment,
            description: "Sign executables and binaries".to_string(),
            severity: "high".to_string(),
            mandatory: true,
            guidance: "Code sign all releases".to_string(),
            tools: vec![],
            compliance_frameworks: vec![],
        }]
    }

    fn rules_for_mobile() -> Vec<SecurityRule> {
        vec![SecurityRule {
            id: "mob-001".to_string(),
            name: "Secure Storage".to_string(),
            category: RuleCategory::DataProtection,
            description: "Use secure storage for sensitive data".to_string(),
            severity: "critical".to_string(),
            mandatory: true,
            guidance: "Use OS-level secure storage (Keychain, Keystore)".to_string(),
            tools: vec![],
            compliance_frameworks: vec!["OWASP Mobile".to_string()],
        }]
    }

    fn rules_for_microservice() -> Vec<SecurityRule> {
        vec![SecurityRule {
            id: "micro-001".to_string(),
            name: "Service Mesh Security".to_string(),
            category: RuleCategory::Network,
            description: "Implement mTLS in service mesh".to_string(),
            severity: "high".to_string(),
            mandatory: true,
            guidance: "Use Istio or similar with mTLS".to_string(),
            tools: vec!["istio".to_string()],
            compliance_frameworks: vec![],
        }]
    }

    fn rules_for_custom() -> Vec<SecurityRule> {
        vec![SecurityRule {
            id: "custom-001".to_string(),
            name: "Dependency Management".to_string(),
            category: RuleCategory::Dependencies,
            description: "Manage and track dependencies".to_string(),
            severity: "high".to_string(),
            mandatory: true,
            guidance: "Regular dependency updates and audits".to_string(),
            tools: vec![],
            compliance_frameworks: vec![],
        }]
    }

    fn get_rules_for_characteristic(characteristic: &SecurityCharacteristic) -> Vec<SecurityRule> {
        match characteristic {
            SecurityCharacteristic::Authentication => vec![SecurityRule {
                id: "char-auth-001".to_string(),
                name: "Strong Authentication".to_string(),
                category: RuleCategory::AuthZ,
                description: "Implement strong auth mechanisms".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Use MFA, strong password policies".to_string(),
                tools: vec![],
                compliance_frameworks: vec!["OWASP".to_string()],
            }],
            SecurityCharacteristic::SensitiveData => vec![SecurityRule {
                id: "char-data-001".to_string(),
                name: "Data Protection".to_string(),
                category: RuleCategory::DataProtection,
                description: "Protect sensitive data".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Encrypt, minimize collection, audit access".to_string(),
                tools: vec![],
                compliance_frameworks: vec!["GDPR".to_string(), "HIPAA".to_string()],
            }],
            SecurityCharacteristic::Payments => vec![SecurityRule {
                id: "char-pay-001".to_string(),
                name: "PCI-DSS Compliance".to_string(),
                category: RuleCategory::Compliance,
                description: "Follow PCI-DSS standards".to_string(),
                severity: "critical".to_string(),
                mandatory: true,
                guidance: "Don't store card details, use tokenization".to_string(),
                tools: vec![],
                compliance_frameworks: vec!["PCI-DSS".to_string()],
            }],
            _ => vec![],
        }
    }

    fn get_compliance_frameworks(characteristics: &[SecurityCharacteristic]) -> Vec<String> {
        let mut frameworks = vec!["OWASP".to_string()];

        for char in characteristics {
            match char {
                SecurityCharacteristic::SensitiveData => {
                    frameworks.extend(vec!["GDPR".to_string(), "CCPA".to_string()]);
                }
                SecurityCharacteristic::Hipaa => {
                    frameworks.push("HIPAA".to_string());
                }
                SecurityCharacteristic::Payments => {
                    frameworks.push("PCI-DSS".to_string());
                }
                _ => {}
            }
        }

        frameworks
    }

    fn generate_recommendations(profile: &SecurityProfile, issues: &[String]) -> Vec<String> {
        let mut recommendations = vec![];

        match profile {
            SecurityProfile::WebApi => {
                recommendations.push("Conduct regular security audits".to_string());
                recommendations.push("Implement WAF (Web Application Firewall)".to_string());
                recommendations.push("Use rate limiting and DDoS protection".to_string());
            }
            SecurityProfile::DataProcessing => {
                recommendations.push("Implement data retention policies".to_string());
                recommendations.push("Regular privacy impact assessments".to_string());
            }
            SecurityProfile::IoT => {
                recommendations.push("Regular firmware security updates".to_string());
                recommendations.push("Monitor device telemetry for anomalies".to_string());
            }
            _ => {}
        }

        if !issues.is_empty() {
            recommendations.push(format!("Address {} critical issue(s)", issues.len()));
        }

        recommendations
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_web_api_profile() {
        let rules = SecurityEngine::get_default_rules(&SecurityProfile::WebApi);
        assert!(!rules.is_empty());
        assert!(rules.iter().any(|r| r.category == RuleCategory::AuthZ));
        assert!(rules
            .iter()
            .any(|r| r.category == RuleCategory::Dependencies));
    }

    #[test]
    fn test_cli_profile() {
        let rules = SecurityEngine::get_default_rules(&SecurityProfile::CliTool);
        assert!(!rules.is_empty());
        assert!(rules.iter().any(|r| r.id == "cli-001"));
    }

    #[test]
    fn test_profile_for_project_type() {
        let profile = SecurityEngine::get_profile_for_type(&ProjectType::RustWeb);
        assert_eq!(profile, SecurityProfile::WebApi);

        let profile = SecurityEngine::get_profile_for_type(&ProjectType::RustCli);
        assert_eq!(profile, SecurityProfile::CliTool);
    }

    #[test]
    fn test_create_profile_config() {
        let characteristics = vec![
            SecurityCharacteristic::Authentication,
            SecurityCharacteristic::SensitiveData,
        ];

        let config =
            SecurityEngine::create_profile_config(SecurityProfile::WebApi, characteristics)
                .unwrap();

        assert_eq!(config.profile, SecurityProfile::WebApi);
        assert!(!config.rules.is_empty());
        assert!(config.compliance_frameworks.contains(&"GDPR".to_string()));
    }

    #[test]
    fn test_security_assessment() {
        let characteristics = vec![];
        let config =
            SecurityEngine::create_profile_config(SecurityProfile::CliTool, characteristics)
                .unwrap();

        let assessment = SecurityEngine::assess_security(&config, 3, 0, vec![]);

        assert_eq!(assessment.profile, SecurityProfile::CliTool);
        assert_eq!(assessment.risk_level, "low");
    }

    #[test]
    fn test_data_processing_profile() {
        let rules = SecurityEngine::get_default_rules(&SecurityProfile::DataProcessing);
        assert!(rules
            .iter()
            .any(|r| r.category == RuleCategory::DataProtection));
        assert!(rules.iter().any(|r| r.category == RuleCategory::Logging));
    }

    #[test]
    fn test_sbom_rule_included() {
        let rules = SecurityEngine::get_default_rules(&SecurityProfile::WebApi);
        assert!(rules.iter().any(|r| r.category == RuleCategory::Sbom));
    }

    #[test]
    fn test_characteristic_rules() {
        let rules = SecurityEngine::get_rules_for_characteristic(&SecurityCharacteristic::Payments);
        assert!(!rules.is_empty());
        assert!(rules[0]
            .compliance_frameworks
            .contains(&"PCI-DSS".to_string()));
    }
}
