# -*- coding: utf-8 -*-

from checkmate.lib.analysis.base import BaseAnalyzer
from checkmate.helpers.docker_runner import get_image, run_json_tool

import logging
import os

logger = logging.getLogger(__name__)


class TrivyAnalyzer(BaseAnalyzer):

    def summarize(self, items):
        pass

    def analyze(self, file_revision):
        issues = []
        code_dir = os.environ.get("CODE_DIR", os.getcwd())
        image = get_image("CHECKMATE_IMAGE_TRIVY", "aquasec/trivy:latest")

        try:
            json_result = run_json_tool(
                image,
                ["trivy", "config", "--format", "json", "/workspace"],
                mount_path=code_dir,
            )
        except Exception:
            json_result = {}

        for result in json_result.get("Results", []) or []:
            target = result.get("Target") or ""
            for misconfig in result.get("Misconfigurations", []) or []:
                location_data = misconfig.get("Location") or {}
                line = location_data.get("StartLine") or 1
                filename = location_data.get("File") or target or file_revision.path

                location = (((line, None), (line, None)),)
                description = (
                    misconfig.get("Title")
                    or misconfig.get("Description")
                    or misconfig.get("Message")
                    or "Trivy misconfiguration"
                )

                issues.append({
                    "code": misconfig.get("ID") or "TrivyMisconfig",
                    "severity": misconfig.get("Severity") or "Unknown",
                    "location": location,
                    "data": description,
                    "file": filename,
                    "line": line,
                    "fingerprint": self.get_fingerprint_from_code(
                        file_revision, location, extra_data=description
                    ),
                })

        return {"issues": issues}
