"""PII classifier post-processor (Phase 9)."""

from __future__ import annotations

from typing import Any

from dsc.detectors import context as ctx
from dsc.detectors import pii
from dsc.llm import fix_prompts
from dsc.scanner.models import Finding

from ._data_class_base import base_metadata, context_label, make_finding, to_severity
from .base import PostProcessor, SarifMatch, ScanContext


class PIIClassifierPostProcessor:
    name = "pii_classifier"

    def process(
        self,
        match: SarifMatch,
        rule_metadata: dict[str, Any],
        args: dict[str, Any],
        context: ScanContext,
    ) -> list[Finding]:
        line_text = match.raw_lines or ""
        if not line_text:
            return []

        hits = pii.scan(line_text)
        if not hits:
            return []

        line_context = ctx.classify_context(line_text, file_path=match.file_path)
        out: list[Finding] = []

        for hit in hits:
            tier = pii.severity_for_context(
                line_context,
                kind=hit.kind,
                is_fixture_value=hit.is_fixture,
            )
            cwe = rule_metadata.get("cwe", "CWE-359")
            label = context_label(line_context)
            template = fix_prompts.for_pii(
                kind=hit.kind,
                line_context_label=label,
                file_path=match.file_path,
                line=match.line_start,
                snippet=line_text.strip(),
            )
            meta = base_metadata(
                data_class="pii",
                detector_kind=hit.kind,
                line_context=line_context,
                severity_tier=tier,
                extra={
                    "pii_kind": hit.kind,
                    "pii_is_fixture": hit.is_fixture,
                    "fix_template": template.llm,
                },
            )
            message = (
                f"PII ({hit.kind}) detected in {label} context. GDPR Art. 5 / "
                "CCPA \xa7 1798.100 require minimization and pseudonymization."
            )
            out.append(
                make_finding(
                    rule_id=match.rule_id,
                    cwe=cwe,
                    severity=to_severity(tier),
                    file_path=match.file_path,
                    line_start=match.line_start,
                    line_end=match.line_end,
                    column=match.column,
                    message=message,
                    snippet=line_text.strip() or None,
                    fix_suggestion=template.inline,
                    metadata=meta,
                )
            )
        return out


__all__ = ["PIIClassifierPostProcessor"]
