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

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


class PackageScanningIntegration(TwistcliIntegration):
    def _create_report(
        self,
        twistcli_scan_result: Dict[str, Any],
        bc_platform_integration: BcPlatformIntegration,
        file_path: Path,
        **kwargs: Any,
    ) -> 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.get("vulnerabilities") or []
        ]
        packages = [
            {
                "type": package.get("type"),
                "name": package.get("name"),
                "version": package.get("version"),
                "licenses":  package.get("licenses") or []
            }
            for package in twistcli_scan_result.get("packages") or []
        ]
        payload = {
            "packageName": str(file_path.name),
            "packageFilePath": removeprefix(str(file_path), os.getenv("BC_ROOT_DIR", "")),
            "type": "Package",
            "sourceId": bc_platform_integration.repo_id,
            "branch": bc_platform_integration.repo_branch,
            "sourceType": bc_platform_integration.bc_source.name,
            "vulnerabilities": vulnerabilities,
            "packages": packages,
        }
        return payload


package_scanning_integration = PackageScanningIntegration()
