import os
from pathlib import Path
from typing import Dict, Any
from datetime import datetime, timedelta

from checkov.common.bridgecrew.platform_integration import bc_integration
from checkov.common.bridgecrew.vulnerability_scanning.integrations.twistcli import TwistcliIntegration
from checkov.common.util.str_utils import removeprefix


class DockerImageScanningIntegration(TwistcliIntegration):
    def report_results(
        self,
        twistcli_scan_result: Dict[str, Any],
        file_path: Path,
        file_content: str,
        docker_image_name: str,
        **kwargs: Any,
    ) -> None:
        super().report_results(
            twistcli_scan_result=twistcli_scan_result,
            file_path=file_path,
            file_content=file_content,
            docker_image_name=docker_image_name,
        )

    def _create_report(
        self,
        twistcli_scan_result: Dict[str, Any],
        file_path: Path,
        file_content: str,
        docker_image_name: str,
    ) -> Dict[str, Any]:
        vulnerabilities = [
            {
                "cveId": vul.get("id"),
                "status": vul.get("status", "open"),
                "severity": vul.get("severity"),
                "packageName": vul.get("packageName"),
                "packageVersion": vul.get("packageVersion"),
                "link": vul.get("link"),
                "cvss": vul.get("cvss"),
                "vector": vul.get("vector"),
                "description": vul.get("description"),
                "riskFactors": vul.get("riskFactors"),
                "publishedDate": vul.get("publishedDate")
                or (datetime.now() - timedelta(days=vul.get("publishedDays", 0))).isoformat(),
            }
            for vul in twistcli_scan_result["results"][0].get("vulnerabilities") or []
        ]
        payload = {
            "dockerImageName": docker_image_name,
            "dockerFilePath": removeprefix(str(file_path), os.getenv("BC_ROOT_DIR", "")),
            "dockerFileContent": file_content,
            "type": "Image",
            "sourceId": bc_integration.repo_id,
            "branch": bc_integration.repo_branch,
            "sourceType": bc_integration.bc_source.name,
            "vulnerabilities": vulnerabilities,
        }
        if bc_integration.cicd_details:
            payload["cicd_details"] = bc_integration.cicd_details
        return payload


docker_image_scanning_integration = DockerImageScanningIntegration()
