//! HIPAA Compliance Checker
//!
//! Implements HIPAA Security and Privacy Rule compliance validation for
//! healthcare data policies.

use std::sync::Arc;

use chrono::Utc;
use regex::Regex;

use super::{
    ComplianceControl, ComplianceFramework, ComplianceFrameworkChecker, ComplianceRecommendation,
    ComplianceResult, ComplianceViolation, ControlResult, EffortLevel, ImpactLevel,
    RecommendationPriority, RiskRating, ViolationSeverity,
};
use crate::error::{auth, ControlCenterError, Result};
use crate::policies::PolicyMetadata;
use crate::storage::PolicyStorage;

/// HIPAA compliance checker implementation
pub struct HIPAAChecker {
    controls: Vec<ComplianceControl>,
}

impl HIPAAChecker {
    /// Create new HIPAA checker with predefined controls
    pub fn new() -> Self {
        let controls = Self::initialize_hipaa_controls();
        Self { controls }
    }

    /// Initialize HIPAA Security and Privacy Rule controls
    fn initialize_hipaa_controls() -> Vec<ComplianceControl> {
        vec![
            // Administrative Safeguards
            ComplianceControl {
                control_id: "164.308(a)(1)".to_string(),
                control_name: "Assigned Security Responsibility".to_string(),
                category: "Administrative Safeguards".to_string(),
                description: "Assign security responsibility to a security officer".to_string(),
                required: true,
                policy_patterns: vec![
                    r"security.*officer|HIPAA.*officer|privacy.*officer".to_string(),
                    r"role.*SecurityOfficer|role.*PrivacyOfficer".to_string(),
                ],
                evidence_requirements: vec![
                    "Security officer designation".to_string(),
                    "Security responsibilities documentation".to_string(),
                ],
                test_procedures: vec!["Verify security officer roles in policies".to_string()],
            },
            ComplianceControl {
                control_id: "164.308(a)(3)".to_string(),
                control_name: "Workforce Training".to_string(),
                category: "Administrative Safeguards".to_string(),
                description: "Implement workforce training and access management".to_string(),
                required: true,
                policy_patterns: vec![
                    r"hipaa.*training|privacy.*training|medical.*training".to_string(),
                    r"training.*completed.*true".to_string(),
                ],
                evidence_requirements: vec![
                    "HIPAA training records".to_string(),
                    "Workforce access management".to_string(),
                ],
                test_procedures: vec!["Review training requirements in access policies".to_string()],
            },
            ComplianceControl {
                control_id: "164.308(a)(4)".to_string(),
                control_name: "Information Access Management".to_string(),
                category: "Administrative Safeguards".to_string(),
                description: "Implement procedures for granting access to PHI".to_string(),
                required: true,
                policy_patterns: vec![
                    r"phi|protected.*health.*information".to_string(),
                    r"data_type.*phi|data_type.*healthcare".to_string(),
                    r"hipaa.*authorization|minimum.*necessary".to_string(),
                ],
                evidence_requirements: vec![
                    "PHI access procedures".to_string(),
                    "Information access management policies".to_string(),
                ],
                test_procedures: vec!["Verify PHI access controls in policies".to_string()],
            },
            ComplianceControl {
                control_id: "164.308(a)(5)".to_string(),
                control_name: "Assigned Security Responsibility".to_string(),
                category: "Administrative Safeguards".to_string(),
                description: "Implement security awareness and training program".to_string(),
                required: true,
                policy_patterns: vec![
                    r"security.*awareness|security.*training".to_string(),
                    r"@audit.*true.*phi|audit.*healthcare".to_string(),
                ],
                evidence_requirements: vec![
                    "Security awareness program".to_string(),
                    "Training documentation".to_string(),
                ],
                test_procedures: vec!["Review security training requirements".to_string()],
            },
            // Physical Safeguards
            ComplianceControl {
                control_id: "164.310(a)(1)".to_string(),
                control_name: "Facility Access Controls".to_string(),
                category: "Physical Safeguards".to_string(),
                description: "Implement policies for facility access containing PHI".to_string(),
                required: true,
                policy_patterns: vec![
                    r"facility.*access|physical.*access|data.*center".to_string(),
                    r"geo.*restrict|location.*restrict".to_string(),
                ],
                evidence_requirements: vec![
                    "Facility access control procedures".to_string(),
                    "Physical security measures".to_string(),
                ],
                test_procedures: vec!["Review physical access restrictions".to_string()],
            },
            ComplianceControl {
                control_id: "164.310(b)".to_string(),
                control_name: "Workstation Use".to_string(),
                category: "Physical Safeguards".to_string(),
                description: "Implement policies for workstation use and access".to_string(),
                required: true,
                policy_patterns: vec![
                    r"workstation|endpoint|device.*management".to_string(),
                    r"time.*restrict|session.*timeout".to_string(),
                ],
                evidence_requirements: vec![
                    "Workstation use policies".to_string(),
                    "Device management procedures".to_string(),
                ],
                test_procedures: vec!["Review workstation access controls".to_string()],
            },
            // Technical Safeguards
            ComplianceControl {
                control_id: "164.312(a)(1)".to_string(),
                control_name: "Access Control".to_string(),
                category: "Technical Safeguards".to_string(),
                description: "Implement technical policies to allow access only to authorized \
                              persons"
                    .to_string(),
                required: true,
                policy_patterns: vec![
                    r"permit.*phi|allow.*healthcare".to_string(),
                    r"authorization.*valid|authorized_patients".to_string(),
                    r"role.*in.*Medical|Healthcare".to_string(),
                ],
                evidence_requirements: vec![
                    "Technical access control procedures".to_string(),
                    "User access management".to_string(),
                ],
                test_procedures: vec!["Verify technical access controls for PHI".to_string()],
            },
            ComplianceControl {
                control_id: "164.312(a)(2)(i)".to_string(),
                control_name: "Unique User Identification".to_string(),
                category: "Technical Safeguards".to_string(),
                description: "Assign unique user identification for tracking access".to_string(),
                required: true,
                policy_patterns: vec![
                    r"principal\.id|unique.*identif|user.*id".to_string(),
                    r"tracking|audit.*phi".to_string(),
                ],
                evidence_requirements: vec![
                    "User identification procedures".to_string(),
                    "Access tracking mechanisms".to_string(),
                ],
                test_procedures: vec!["Verify unique user identification in policies".to_string()],
            },
            ComplianceControl {
                control_id: "164.312(b)".to_string(),
                control_name: "Audit Controls".to_string(),
                category: "Technical Safeguards".to_string(),
                description: "Implement audit controls to record access to PHI".to_string(),
                required: true,
                policy_patterns: vec![
                    r"@audit.*true|audit.*log|audit.*trail".to_string(),
                    r"phi_access.*track|log.*phi".to_string(),
                ],
                evidence_requirements: vec![
                    "Audit control procedures".to_string(),
                    "Audit log management".to_string(),
                ],
                test_procedures: vec!["Verify audit controls for PHI access".to_string()],
            },
            ComplianceControl {
                control_id: "164.312(c)(1)".to_string(),
                control_name: "Integrity".to_string(),
                category: "Technical Safeguards".to_string(),
                description: "Protect PHI from improper alteration or destruction".to_string(),
                required: true,
                policy_patterns: vec![
                    r"integrity|alteration|destruction".to_string(),
                    r"version|backup|restore".to_string(),
                ],
                evidence_requirements: vec![
                    "Data integrity procedures".to_string(),
                    "Backup and recovery plans".to_string(),
                ],
                test_procedures: vec!["Review data integrity controls".to_string()],
            },
            ComplianceControl {
                control_id: "164.312(d)".to_string(),
                control_name: "Person or Entity Authentication".to_string(),
                category: "Technical Safeguards".to_string(),
                description: "Verify the identity of persons or entities seeking access to PHI"
                    .to_string(),
                required: true,
                policy_patterns: vec![
                    r"authentication|identity.*verif|verify.*identity".to_string(),
                    r"mfa.*phi|multi.?factor.*healthcare".to_string(),
                ],
                evidence_requirements: vec![
                    "Authentication procedures".to_string(),
                    "Identity verification processes".to_string(),
                ],
                test_procedures: vec![
                    "Verify authentication requirements for PHI access".to_string()
                ],
            },
            ComplianceControl {
                control_id: "164.312(e)(1)".to_string(),
                control_name: "Transmission Security".to_string(),
                category: "Technical Safeguards".to_string(),
                description: "Guard against unauthorized access to PHI during transmission"
                    .to_string(),
                required: true,
                policy_patterns: vec![
                    r"transmission|transfer|transit".to_string(),
                    r"encrypt.*transit|tls|ssl".to_string(),
                    r"unauthorized.*access.*transmission".to_string(),
                ],
                evidence_requirements: vec![
                    "Transmission security procedures".to_string(),
                    "Encryption in transit controls".to_string(),
                ],
                test_procedures: vec!["Review transmission security controls".to_string()],
            },
            // Privacy Rule Requirements
            ComplianceControl {
                control_id: "164.502(b)".to_string(),
                control_name: "Minimum Necessary Standard".to_string(),
                category: "Privacy Rule".to_string(),
                description: "Use and disclose only minimum necessary PHI".to_string(),
                required: true,
                policy_patterns: vec![
                    r"minimum.*necessary|least.*privilege".to_string(),
                    r"minimum_necessary.*true".to_string(),
                ],
                evidence_requirements: vec![
                    "Minimum necessary procedures".to_string(),
                    "Access limitation policies".to_string(),
                ],
                test_procedures: vec![
                    "Verify minimum necessary standard implementation".to_string()
                ],
            },
            ComplianceControl {
                control_id: "164.508".to_string(),
                control_name: "Uses and Disclosures for which Authorization is Required"
                    .to_string(),
                category: "Privacy Rule".to_string(),
                description: "Obtain authorization for uses and disclosures of PHI".to_string(),
                required: true,
                policy_patterns: vec![
                    r"authorization.*required|consent.*required".to_string(),
                    r"disclosure.*authorization|use.*authorization".to_string(),
                ],
                evidence_requirements: vec![
                    "Authorization procedures".to_string(),
                    "Use and disclosure tracking".to_string(),
                ],
                test_procedures: vec!["Review authorization requirements".to_string()],
            },
        ]
    }

    /// Validate policy content against specific HIPAA control
    fn validate_policy_against_control(
        &self,
        policy_content: &str,
        control: &ComplianceControl,
    ) -> ControlResult {
        let mut evidence = Vec::new();
        let mut gaps = Vec::new();
        let mut compliant = true;

        // Check each pattern requirement
        for pattern_str in &control.policy_patterns {
            match Regex::new(&format!("(?i){}", pattern_str)) {
                // Case-insensitive matching
                Ok(pattern) => {
                    if pattern.is_match(policy_content) {
                        evidence.push(format!("HIPAA pattern '{}' found in policy", pattern_str));
                    } else {
                        gaps.push(format!("Missing required HIPAA pattern: '{}'", pattern_str));
                        compliant = false;
                    }
                }
                Err(e) => {
                    gaps.push(format!("Invalid regex pattern '{}': {}", pattern_str, e));
                    compliant = false;
                }
            }
        }

        // HIPAA-specific validations
        if policy_content.contains("phi") || policy_content.contains("healthcare") {
            evidence.push("PHI or healthcare data references found".to_string());

            // Check for required HIPAA elements when dealing with PHI
            if !policy_content.contains("audit") && !policy_content.contains("@audit") {
                gaps.push("PHI access without audit requirements".to_string());
                compliant = false;
            }

            if !policy_content.contains("authorization") {
                gaps.push("PHI access without proper authorization requirements".to_string());
                compliant = false;
            }
        }

        // Determine risk rating based on HIPAA control category and compliance
        let risk_rating = if !compliant {
            match control.category.as_str() {
                "Technical Safeguards" => RiskRating::Critical, // Technical controls are
                // critical for HIPAA
                "Privacy Rule" => RiskRating::High,
                "Administrative Safeguards" => RiskRating::Medium,
                "Physical Safeguards" => RiskRating::Medium,
                _ => RiskRating::Low,
            }
        } else {
            RiskRating::Low
        };

        ControlResult {
            control_id: control.control_id.clone(),
            control_name: control.control_name.clone(),
            category: control.category.clone(),
            compliant,
            evidence,
            gaps,
            risk_rating,
            remediation_timeline: if !compliant {
                match control.category.as_str() {
                    "Technical Safeguards" => Some("14-30 days".to_string()), // Urgent for
                    // technical
                    _ => Some("30-90 days".to_string()),
                }
            } else {
                None
            },
        }
    }

    /// Generate HIPAA-specific violations
    fn generate_violations(&self, control_results: &[ControlResult]) -> Vec<ComplianceViolation> {
        let mut violations = Vec::new();

        for result in control_results.iter().filter(|r| !r.compliant) {
            let severity = match result.risk_rating {
                RiskRating::Critical => ViolationSeverity::Critical,
                RiskRating::High => ViolationSeverity::High,
                RiskRating::Medium => ViolationSeverity::Medium,
                RiskRating::Low => ViolationSeverity::Low,
            };

            // HIPAA violations are generally more severe due to regulatory requirements
            let adjusted_severity = match severity {
                ViolationSeverity::Low => ViolationSeverity::Medium,
                other => other,
            };

            violations.push(ComplianceViolation {
                violation_id: uuid::Uuid::new_v4().to_string(),
                control_id: result.control_id.clone(),
                severity: adjusted_severity,
                description: format!(
                    "HIPAA {} violation - Control {}: {}",
                    result.category,
                    result.control_id,
                    result.gaps.join("; ")
                ),
                policy_id: None, // Would be set by caller
                resource_id: None,
                detected_at: Utc::now(),
                remediation_required: true, // All HIPAA violations require remediation
                remediation_deadline: match result.risk_rating {
                    RiskRating::Critical => Some(Utc::now() + chrono::Duration::days(14)),
                    RiskRating::High => Some(Utc::now() + chrono::Duration::days(30)),
                    _ => Some(Utc::now() + chrono::Duration::days(90)),
                },
            });
        }

        violations
    }

    /// Generate HIPAA-specific recommendations
    fn generate_recommendations(
        &self,
        control_results: &[ControlResult],
    ) -> Vec<ComplianceRecommendation> {
        let mut recommendations = Vec::new();

        for result in control_results.iter().filter(|r| !r.compliant) {
            let (priority, effort) = match result.risk_rating {
                RiskRating::Critical => (RecommendationPriority::Urgent, EffortLevel::High),
                RiskRating::High => (RecommendationPriority::High, EffortLevel::Medium),
                RiskRating::Medium => (RecommendationPriority::Medium, EffortLevel::Medium),
                RiskRating::Low => (RecommendationPriority::Low, EffortLevel::Low),
            };

            let (title, description, resources) = match result.control_id.as_str() {
                "164.308(a)(4)" => (
                    "Implement PHI Access Management Controls",
                    "Establish comprehensive procedures for granting, modifying, and terminating \
                     access to Protected Health Information (PHI). Implement minimum necessary \
                     standard and proper authorization workflows.",
                    vec![
                        "HIPAA Privacy Officer",
                        "IT Security Team",
                        "Legal Review",
                        "Policy Documentation",
                    ],
                ),
                "164.312(b)" => (
                    "Implement HIPAA Audit Controls",
                    "Deploy comprehensive audit logging for all PHI access, modification, and \
                     disclosure activities. Ensure audit logs are tamper-evident and retained per \
                     HIPAA requirements.",
                    vec![
                        "Security Team",
                        "Audit Infrastructure",
                        "Log Management System",
                        "Compliance Review",
                    ],
                ),
                "164.312(a)(1)" => (
                    "Strengthen Technical Access Controls for PHI",
                    "Implement robust technical safeguards to ensure only authorized individuals \
                     can access PHI. Include role-based access controls and regular access \
                     reviews.",
                    vec![
                        "Technical Team",
                        "HIPAA Security Officer",
                        "Access Control System",
                        "Regular Reviews",
                    ],
                ),
                "164.502(b)" => (
                    "Implement Minimum Necessary Standard",
                    "Ensure all PHI access and disclosures are limited to the minimum necessary \
                     information required for the specific purpose. Implement granular access \
                     controls and regular reviews.",
                    vec![
                        "Privacy Officer",
                        "Clinical Staff Training",
                        "Access Control Updates",
                        "Policy Review",
                    ],
                ),
                _ => (
                    "Address HIPAA Compliance Gap",
                    "Review and update policies to address identified HIPAA compliance gaps. \
                     Consult with HIPAA experts and legal counsel as needed.",
                    vec![
                        "HIPAA Officer",
                        "Legal Counsel",
                        "Technical Review",
                        "Staff Training",
                    ],
                ),
            };

            recommendations.push(ComplianceRecommendation {
                recommendation_id: uuid::Uuid::new_v4().to_string(),
                control_id: result.control_id.clone(),
                priority,
                title: title.to_string(),
                description: description.to_string(),
                implementation_effort: effort,
                expected_impact: ImpactLevel::High, // HIPAA compliance is always high impact
                resources_required: resources.iter().map(|s| s.to_string()).collect(),
            });
        }

        recommendations
    }

    /// Calculate HIPAA compliance score with regulatory weighting
    fn calculate_compliance_score(&self, control_results: &[ControlResult]) -> f64 {
        if control_results.is_empty() {
            return 0.0;
        }

        let mut weighted_score = 0.0;
        let mut total_weight = 0.0;

        for result in control_results {
            // HIPAA weighting based on control category importance
            let weight = match result.category.as_str() {
                "Technical Safeguards" => 5.0, // Most critical
                "Privacy Rule" => 4.0,         // High importance
                "Administrative Safeguards" => 3.0,
                "Physical Safeguards" => 2.0,
                _ => 1.0,
            };

            if result.compliant {
                weighted_score += weight;
            }
            total_weight += weight;
        }

        if total_weight > 0.0 {
            (weighted_score / total_weight) * 100.0
        } else {
            0.0
        }
    }
}

#[async_trait::async_trait]
impl ComplianceFrameworkChecker for HIPAAChecker {
    fn framework_name(&self) -> &str {
        "HIPAA Security and Privacy Rules"
    }

    async fn check_compliance(
        &self,
        policies: &[PolicyMetadata],
        storage: Arc<dyn PolicyStorage>,
    ) -> Result<ComplianceResult> {
        let mut all_control_results = Vec::new();

        // Check each policy against all HIPAA controls
        for policy_metadata in policies {
            if !policy_metadata.enabled {
                continue;
            }

            match storage.get_policy(&policy_metadata.id).await {
                Ok(policy_content) => {
                    // Only evaluate policies that deal with healthcare data
                    if policy_content.to_lowercase().contains("phi")
                        || policy_content.to_lowercase().contains("healthcare")
                        || policy_content.to_lowercase().contains("medical")
                        || policy_metadata.tags.iter().any(|tag| {
                            tag.to_lowercase().contains("hipaa")
                                || tag.to_lowercase().contains("healthcare")
                        })
                    {
                        let policy_results = self
                            .validate_policy(&policy_content, policy_metadata)
                            .await?;
                        all_control_results.extend(policy_results);
                    }
                }
                Err(e) => {
                    tracing::warn!("Failed to retrieve policy {}: {}", policy_metadata.id, e);
                }
            }
        }

        // If no healthcare-related policies found, create default failing results
        if all_control_results.is_empty() {
            tracing::warn!("No HIPAA-relevant policies found - creating default assessment");
            for control in &self.controls {
                all_control_results.push(ControlResult {
                    control_id: control.control_id.clone(),
                    control_name: control.control_name.clone(),
                    category: control.category.clone(),
                    compliant: false,
                    evidence: Vec::new(),
                    gaps: vec!["No HIPAA-compliant policies found".to_string()],
                    risk_rating: RiskRating::High,
                    remediation_timeline: Some("30-90 days".to_string()),
                });
            }
        }

        // Aggregate results by control ID (take best result for each control)
        let mut control_map = std::collections::HashMap::new();
        for result in all_control_results {
            let entry = control_map
                .entry(result.control_id.clone())
                .or_insert_with(|| result.clone());

            // If we find a compliant result for a control, prefer it
            if result.compliant && !entry.compliant {
                *entry = result;
            }
        }

        let control_results: Vec<ControlResult> = control_map.into_values().collect();

        // Generate violations and recommendations
        let violations = self.generate_violations(&control_results);
        let recommendations = self.generate_recommendations(&control_results);

        // Calculate compliance score
        let score = self.calculate_compliance_score(&control_results);

        // HIPAA requires stricter compliance - no critical violations allowed
        let critical_violations = violations
            .iter()
            .filter(|v| matches!(v.severity, ViolationSeverity::Critical))
            .count();
        let high_violations = violations
            .iter()
            .filter(|v| matches!(v.severity, ViolationSeverity::High))
            .count();
        let overall_compliant = critical_violations == 0 && high_violations == 0 && score >= 85.0;

        Ok(ComplianceResult {
            framework: ComplianceFramework::HIPAA,
            overall_compliant,
            control_results,
            violations,
            recommendations,
            score,
            timestamp: Utc::now(),
            next_review_date: Utc::now() + chrono::Duration::days(60), /* More frequent reviews
                                                                        * for HIPAA */
        })
    }

    async fn validate_policy(
        &self,
        policy_content: &str,
        _metadata: &PolicyMetadata,
    ) -> Result<Vec<ControlResult>> {
        let mut results = Vec::new();

        for control in &self.controls {
            let result = self.validate_policy_against_control(policy_content, control);
            results.push(result);
        }

        Ok(results)
    }

    fn get_required_controls(&self) -> Vec<ComplianceControl> {
        self.controls.clone()
    }

    async fn generate_report(&self, result: &ComplianceResult) -> Result<String> {
        let mut report = String::new();

        report.push_str("# HIPAA Security and Privacy Rules Compliance Report\n\n");
        report.push_str(&format!(
            "**Report Date:** {}\n",
            result.timestamp.format("%Y-%m-%d %H:%M:%S UTC")
        ));
        report.push_str(&format!(
            "**Overall Compliance:** {}\n",
            if result.overall_compliant {
                "✓ COMPLIANT"
            } else {
                "✗ NON-COMPLIANT"
            }
        ));
        report.push_str(&format!("**Compliance Score:** {:.1}%\n\n", result.score));

        // HIPAA-specific warning
        if !result.overall_compliant {
            report.push_str(
                "⚠️  **REGULATORY WARNING:** Non-compliance with HIPAA requirements may result in \
                 significant civil and criminal penalties, including fines up to $1.5 million per \
                 incident and potential imprisonment.\n\n",
            );
        }

        // Control Results by Category
        report.push_str("## Control Results by Category\n\n");

        let categories = [
            "Technical Safeguards",
            "Administrative Safeguards",
            "Privacy Rule",
            "Physical Safeguards",
        ];
        for category in &categories {
            let category_controls: Vec<&ControlResult> = result
                .control_results
                .iter()
                .filter(|c| c.category == *category)
                .collect();

            if !category_controls.is_empty() {
                report.push_str(&format!("### {}\n", category));
                let compliant = category_controls.iter().filter(|c| c.compliant).count();
                let total = category_controls.len();
                report.push_str(&format!(
                    "**Status:** {}/{} controls compliant\n\n",
                    compliant, total
                ));

                for control in &category_controls {
                    let status = if control.compliant { "✓" } else { "✗" };
                    report.push_str(&format!(
                        "- {} **{}** - {}\n",
                        status, control.control_id, control.control_name
                    ));
                }
                report.push('\n');
            }
        }

        // High-Risk Violations
        let critical_violations: Vec<&ComplianceViolation> = result
            .violations
            .iter()
            .filter(|v| {
                matches!(
                    v.severity,
                    ViolationSeverity::Critical | ViolationSeverity::High
                )
            })
            .collect();

        if !critical_violations.is_empty() {
            report.push_str("## Critical and High-Risk Violations\n\n");
            for violation in &critical_violations {
                report.push_str(&format!(
                    "### ⚠️  {} - {} Risk\n",
                    violation.control_id, violation.severity
                ));
                report.push_str(&format!("**Description:** {}\n", violation.description));
                if let Some(deadline) = violation.remediation_deadline {
                    report.push_str(&format!(
                        "**⏰ Remediation Deadline:** {}\n",
                        deadline.format("%Y-%m-%d")
                    ));
                }
                report.push_str(
                    "**Regulatory Impact:** Potential HIPAA violation with civil penalties\n\n",
                );
            }
        }

        // Priority Recommendations
        let priority_recommendations: Vec<&ComplianceRecommendation> = result
            .recommendations
            .iter()
            .filter(|r| {
                matches!(
                    r.priority,
                    RecommendationPriority::Urgent | RecommendationPriority::High
                )
            })
            .collect();

        if !priority_recommendations.is_empty() {
            report.push_str("## Priority Remediation Actions\n\n");
            for (i, recommendation) in priority_recommendations.iter().enumerate() {
                report.push_str(&format!(
                    "{}. **{}** ({})\n",
                    i + 1,
                    recommendation.title,
                    recommendation.priority
                ));
                report.push_str(&format!(
                    "   - **Control:** {}\n",
                    recommendation.control_id
                ));
                report.push_str(&format!(
                    "   - **Action:** {}\n",
                    recommendation.description
                ));
                report.push_str(&format!(
                    "   - **Resources:** {}\n",
                    recommendation.resources_required.join(", ")
                ));
                report.push('\n');
            }
        }

        // Next Steps
        report.push_str("## Next Steps\n\n");
        report.push_str(
            "1. **Immediate Action:** Address all Critical and High-risk violations within \
             deadlines\n",
        );
        report.push_str(
            "2. **Documentation:** Update policies and procedures to reflect HIPAA requirements\n",
        );
        report.push_str(
            "3. **Training:** Ensure all workforce members receive appropriate HIPAA training\n",
        );
        report.push_str("4. **Monitoring:** Implement ongoing monitoring and audit procedures\n");
        report.push_str(
            "5. **Legal Review:** Consult with legal counsel regarding compliance status\n\n",
        );

        report.push_str(&format!(
            "**Next Review Date:** {}\n",
            result.next_review_date.format("%Y-%m-%d")
        ));
        report.push_str(
            "**Note:** HIPAA compliance requires continuous monitoring and regular assessments.\n",
        );

        Ok(report)
    }
}

impl Default for HIPAAChecker {
    fn default() -> Self {
        Self::new()
    }
}
