# Copyright (c) 2025 CoReason, Inc.
#
# This software is proprietary and dual-licensed.
# Licensed under the Prosperity Public License 3.0 (the "License").
# A copy of the license is available at https://prosperitylicense.com/versions/3.0.0
# For details, see the LICENSE file.
# Commercial use beyond a 30-day trial requires a separate license.
#
# Source Code: https://github.com/CoReason-AI/coreason_navigator

import re
from typing import Protocol, runtime_checkable

from coreason_navigator.exceptions import PIIViolationError

__all__ = ["PIIGuard", "RegexPIIGuard", "PIIViolationError"]


@runtime_checkable
class PIIGuard(Protocol):
    """Protocol for PII detection guardrails."""

    async def check(self, text: str) -> None:
        """
        Checks the text for PII.

        Args:
            text: The text to analyze.

        Raises:
            PIIViolationError: If PII is detected.
        """
        ...


class RegexPIIGuard:
    """
    Blocks inputs containing common PII patterns using regex.
    """

    # Patterns defined in requirements
    PATTERNS = {
        "email": r"\b[\w\.-]+@[\w\.-]+\.\w+\b",
        "phone": r"\b\d{3}[-.]?\d{3}[-.]?\d{4}\b",
        "ssn": r"\b\d{3}-\d{2}-\d{4}\b",
    }

    def __init__(self) -> None:
        """Initializes the RegexPIIGuard by compiling patterns."""
        self.compiled_patterns = {k: re.compile(v) for k, v in self.PATTERNS.items()}

    async def check(self, text: str) -> None:
        """
        Checks the text against all compiled regex patterns.

        Args:
            text: The text to check for PII.

        Raises:
            PIIViolationError: If any PII pattern matches.
        """
        for pii_type, pattern in self.compiled_patterns.items():
            match = pattern.search(text)
            if match:
                raise PIIViolationError(pii_type, match.group())
