from prowler.lib.check.models import Check, CheckReportAlibabaCloud
from prowler.providers.alibabacloud.services.securitycenter.securitycenter_client import (
    securitycenter_client,
)


class securitycenter_vulnerability_scan_enabled(Check):
    """Check if scheduled vulnerability scan is enabled on all servers."""

    def execute(self) -> list[CheckReportAlibabaCloud]:
        findings = []

        # Required vulnerability types that must be enabled
        required_vul_types = ["yum", "cve", "sys", "cms", "emg"]

        # Required scan levels: "asap" (high) and "later" (medium)
        required_scan_levels = ["asap", "later"]

        vul_configs = securitycenter_client.vul_configs
        concern_necessity = securitycenter_client.concern_necessity

        # Check vulnerability types
        disabled_types = []
        for vul_type in required_vul_types:
            config = vul_configs.get(vul_type)
            if not config or not config.enabled:
                disabled_types.append(vul_type)

        # Check scan levels
        missing_levels = []
        for level in required_scan_levels:
            if level not in concern_necessity:
                missing_levels.append(level)

        # Create report
        report = CheckReportAlibabaCloud(metadata=self.metadata(), resource={})
        report.region = securitycenter_client.region
        report.resource_id = securitycenter_client.audited_account
        report.resource_arn = f"acs:sas::{securitycenter_client.audited_account}:vulnerability-scan-config"

        if not disabled_types and not missing_levels:
            report.status = "PASS"
            report.status_extended = (
                "Scheduled vulnerability scan is enabled for all vulnerability types "
                "(yum, cve, sys, cms, emg) and all required scan levels (high/asap, medium/later) are enabled."
            )
        else:
            report.status = "FAIL"
            issues = []
            if disabled_types:
                issues.append(
                    f"Vulnerability types disabled: {', '.join(disabled_types)}"
                )
            if missing_levels:
                level_names = {"asap": "high", "later": "medium"}
                missing_names = [
                    level_names.get(level, level) for level in missing_levels
                ]
                issues.append(
                    f"Scan levels not enabled: {', '.join(missing_names)} ({', '.join(missing_levels)})"
                )
            report.status_extended = (
                "Scheduled vulnerability scan is not properly configured. "
                + "; ".join(issues)
            )

        findings.append(report)
        return findings
