"""Trivy scanner integration — filesystem vulnerability scanning via subprocess."""

from __future__ import annotations

import json
import logging
import subprocess
from pathlib import Path
from typing import Any

from secagent.scanners.base_scanner import BaseScanner

logger = logging.getLogger(__name__)

# GitHub coordinates for auto-install
_GITHUB_OWNER = "aquasecurity"
_GITHUB_REPO = "trivy"


class TrivyScanner(BaseScanner):
    """Runs ``trivy fs`` and returns parsed JSON findings."""

    name = "trivy"
    github_owner = _GITHUB_OWNER
    github_repo = _GITHUB_REPO

    def run(self, target: Path) -> list[dict[str, Any]]:
        """Execute Trivy filesystem scan and return raw results."""
        exe = self.get_executable()
        if not exe:
            return []

        cmd = [
            exe,
            "fs",
            "--format",
            "json",
            "--scanners",
            "vuln,secret,misconfig",
            str(target),
        ]

        logger.info("Running: %s", " ".join(cmd))

        try:
            result = subprocess.run(
                cmd,
                capture_output=True,
                text=True,
                timeout=180,
                check=False,
            )

            stdout = result.stdout.strip()
            if not stdout:
                return []

            data = json.loads(stdout)

            # Trivy wraps findings under "Results"
            if isinstance(data, dict) and "Results" in data:
                return data["Results"]
            if isinstance(data, list):
                return data
            return [data]

        except subprocess.TimeoutExpired:
            logger.error("Trivy timed out after 180 s")
            return []
        except (json.JSONDecodeError, OSError) as exc:
            logger.error("Trivy output parsing failed: %s", exc)
            return []
