"""Finding enrichment with compliance cross-reference data."""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

from sanicode.compliance.mapper import ComplianceMapper, ComplianceMapping, derive_severity
from sanicode.scanner.patterns import Finding, Severity


@dataclass
class EnrichedFinding:
    """A Finding augmented with compliance mapping data."""

    # Original Finding fields
    file: Path
    line: int
    column: int
    rule_id: str
    message: str
    severity: Severity
    cwe_id: int

    # Compliance fields
    cwe_name: str = ""
    compliance: ComplianceMapping | None = None
    derived_severity: str = ""  # severity derived from STIG category
    remediation: str = ""


def enrich_finding(finding: Finding, mapper: ComplianceMapper) -> EnrichedFinding:
    """Enrich a raw Finding with compliance cross-reference data.

    Maps the finding's CWE ID to compliance controls across OWASP ASVS,
    NIST 800-53, ASD STIG, and PCI DSS. Derives severity from the highest
    STIG category found for the CWE.

    Args:
        finding: The raw scanner finding to enrich.
        mapper: A ComplianceMapper instance (may be shared across calls).

    Returns:
        An EnrichedFinding with compliance fields populated.
    """
    mapping = mapper.map_cwe(finding.cwe_id)
    return EnrichedFinding(
        file=finding.file,
        line=finding.line,
        column=finding.column,
        rule_id=finding.rule_id,
        message=finding.message,
        severity=finding.severity,
        cwe_id=finding.cwe_id,
        cwe_name=mapping.cwe_name,
        compliance=mapping,
        derived_severity=derive_severity(mapping),
        remediation=mapping.remediation,
    )


def enrich_findings(
    findings: list[Finding], mapper: ComplianceMapper | None = None
) -> list[EnrichedFinding]:
    """Enrich a list of findings with compliance cross-reference data.

    Args:
        findings: Raw scanner findings to enrich.
        mapper: Optional ComplianceMapper; a default instance is created if
            not provided (loads the bundled compliance_db.json).

    Returns:
        List of EnrichedFinding objects in the same order as the input.
    """
    if mapper is None:
        mapper = ComplianceMapper()
    return [enrich_finding(f, mapper) for f in findings]
