"""Parser for AI scanner findings."""

from __future__ import annotations

from typing import Any

from secagent.models import Severity, Vulnerability
from secagent.parsers.base_parser import BaseParser

_CONFIDENCE_TO_SEVERITY = {
    "HIGH": Severity.HIGH,
    "MEDIUM": Severity.MEDIUM,
    "LOW": Severity.LOW,
}


class AIParser(BaseParser):
    """Convert AI scanner findings into ``Vulnerability`` objects."""

    def parse(self, raw_findings: list[dict[str, Any]]) -> list[Vulnerability]:
        results: list[Vulnerability] = []

        for finding in raw_findings:
            confidence = str(finding.get("confidence", "MEDIUM")).upper()
            severity = _CONFIDENCE_TO_SEVERITY.get(confidence, Severity.MEDIUM)

            cwe_list: list[str] = finding.get("cwe", [])
            vuln_type = cwe_list[0] if cwe_list else finding.get("vuln", "unknown").split(":")[0].strip()

            vuln = Vulnerability(
                scanner="ai-scanner",
                file=finding.get("_file", "unknown"),
                line=finding.get("affected_code_line_start", 0),
                severity=severity,
                vuln_type=vuln_type,
                description=finding.get("message", finding.get("vuln", "AI-detected vulnerability")),
                raw=finding,
            )
            results.append(vuln)

        return results
