"""
spidercrypt.firewall
~~~~~~~~~~~~~~~~~~~~
Prompt-injection detection for LLM inputs.
"""

import re
from pathlib import Path
from typing import Dict, Any

from .patterns import PROMPT_INJECTION_PATTERNS


def check_injection(text: str) -> Dict[str, Any]:
    """
    Screen *text* for prompt-injection attempts.

    Args:
        text: Raw text to analyse (inline prompt or file content).

    Returns:
        A dict with keys:

        - ``blocked`` (bool): ``True`` if at least one pattern matched.
        - ``hits`` (list[str]): Matched patterns.
        - ``risk_score`` (float): ``len(hits) / 5``, capped at 1.0.
    """
    hits = [p for p in PROMPT_INJECTION_PATTERNS
            if re.search(p, text, re.IGNORECASE)]
    return {
        "blocked":    len(hits) > 0,
        "hits":       hits,
        "risk_score": min(len(hits) / 5, 1.0),
    }


def check_file(filepath: str) -> Dict[str, Any]:
    """Convenience wrapper: read *filepath* then call :func:`check_injection`."""
    text = Path(filepath).read_text(encoding="utf-8", errors="replace")
    return check_injection(text)