"""SARIF v2.1.0 report formatter per §A.1.6a."""

from __future__ import annotations

import hashlib
from typing import TYPE_CHECKING, Any

from complyform import __version__

if TYPE_CHECKING:
    from complyform.core.assessor.control_matcher import Finding

_SEVERITY_TO_LEVEL: dict[str, str] = {
    "CRITICAL": "error",
    "HIGH": "error",
    "MEDIUM": "warning",
    "LOW": "note",
}


def _fingerprint(control_id: str, resource_address: str, cloud: str) -> str:
    raw = f"{control_id}:{resource_address}:{cloud}"
    return hashlib.sha256(raw.encode()).hexdigest()


def format_sarif_report(
    findings: list[Finding],
    *,
    cloud: str,
    frameworks: list[str],
) -> dict[str, Any]:
    """Build SARIF v2.1.0 output."""
    seen_rules: dict[str, dict[str, Any]] = {}

    for f in findings:
        if f.control_id not in seen_rules:
            seen_rules[f.control_id] = {
                "id": f.control_id,
                "name": f.control_id,
                "shortDescription": {"text": f"Control {f.control_id}"},
                "properties": {
                    "framework_id": f.framework,
                    "category": "compliance",
                },
            }

    results: list[dict[str, Any]] = []
    for f in findings:
        if f.status != "FAIL":
            continue
        results.append(
            {
                "ruleId": f.control_id,
                "level": _SEVERITY_TO_LEVEL.get(f.severity, "note"),
                "message": {"text": f.finding},
                "locations": [
                    {
                        "physicalLocation": {
                            "artifactLocation": {"uri": f.resource_address},
                        },
                    }
                ],
                "fixes": [{"description": {"text": f.remediation}}]
                if f.remediation
                else [],
                "fingerprints": {
                    "complyform/v1": _fingerprint(
                        f.control_id, f.resource_address, cloud
                    ),
                },
            }
        )

    return {
        "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json",
        "version": "2.1.0",
        "runs": [
            {
                "tool": {
                    "driver": {
                        "name": "complyform",
                        "version": __version__,
                        "informationUri": "https://complyform.dev",
                        "rules": list(seen_rules.values()),
                    },
                },
                "results": results,
            }
        ],
    }
