"""
Starvex NeMo Engine - Jailbreak, toxicity, and competitor detection

Provides pattern-based and ML-based detection for various security threats.
"""

import logging
import re
from dataclasses import dataclass, field
from typing import Dict, Any, List, Optional

logger = logging.getLogger(__name__)


@dataclass
class NemoResult:
    """Result from NeMo engine check"""
    passed: bool
    confidence: float = 0.0
    message: Optional[str] = None
    details: Dict[str, Any] = field(default_factory=dict)


class NemoEngine:
    """
    Detection engine for jailbreak, toxicity, and competitor mentions.

    Uses pattern matching with optional NeMo Guardrails integration
    for ML-based detection.
    """

    # Jailbreak patterns
    JAILBREAK_PATTERNS = [
        r"ignore\s+(all\s+)?(previous\s+)?instructions",
        r"disregard\s+(all\s+)?(previous\s+)?instructions",
        r"forget\s+(all\s+)?(previous\s+)?instructions",
        r"override\s+(all\s+)?(previous\s+)?instructions",
        r"bypass\s+(all\s+)?(safety|security|filter)",
        r"you\s+are\s+now\s+(dan|evil|uncensored)",
        r"pretend\s+you\s+(have\s+no|don'?t\s+have)\s+(rules|restrictions|filters)",
        r"let'?s\s+play\s+a\s+game\s+where\s+you\s+(have\s+no|don'?t\s+have)",
        r"developer\s+mode\s+(enabled|activated|on)",
        r"sudo\s+mode",
        r"admin\s+override",
        r"jailbreak",
        r"reveal\s+(your\s+)?(system\s+)?prompt",
        r"show\s+me\s+(your\s+)?(system\s+)?prompt",
        r"what\s+are\s+your\s+instructions",
        r"act\s+as\s+(if|though)\s+you\s+(were|are)\s+(?!help)",
        r"roleplay\s+as\s+(?!a\s+helpful)",
        r"from\s+now\s+on\s+you\s+(will|must|shall)",
        r"i\s+am\s+your\s+(creator|developer|master)",
        r"test\s+from\s+(openai|anthropic|the\s+developers)",
    ]

    # Toxicity patterns
    TOXICITY_PATTERNS = [
        r"\b(hate|hating|hated)\s+(you|this|it|them)\b",
        r"\b(stupid|idiot|dumb|moron|retard)\b",
        r"\b(kill|murder|hurt|harm|attack)\s+(you|yourself|myself|someone)\b",
        r"\b(die|death)\s+(to|for)\b",
        r"\bf+[u*]+c*k+\b",
        r"\bs+h+[i*]+t+\b",
        r"\ba+s+s+h+o+l+e+\b",
        r"\bworthless\b",
        r"\bpathetic\b",
        r"\bgo\s+(kill|hurt|harm)\s+(yourself|myself)\b",
        r"\bi\s+hope\s+you\s+(die|suffer|fail)\b",
    ]

    def __init__(
        self,
        custom_jailbreak_patterns: Optional[List[str]] = None,
        custom_toxicity_patterns: Optional[List[str]] = None,
        competitor_patterns: Optional[List[str]] = None,
    ):
        """
        Initialize NeMo engine.

        Args:
            custom_jailbreak_patterns: Additional jailbreak patterns
            custom_toxicity_patterns: Additional toxicity patterns
            competitor_patterns: Patterns for competitor detection
        """
        self.jailbreak_patterns = [
            re.compile(p, re.IGNORECASE)
            for p in self.JAILBREAK_PATTERNS + (custom_jailbreak_patterns or [])
        ]
        self.toxicity_patterns = [
            re.compile(p, re.IGNORECASE)
            for p in self.TOXICITY_PATTERNS + (custom_toxicity_patterns or [])
        ]
        self.competitor_patterns = [
            re.compile(p, re.IGNORECASE)
            for p in (competitor_patterns or [])
        ]

        self._nemo = None
        self._load_nemo()

    def _load_nemo(self):
        """Attempt to load NeMo Guardrails"""
        try:
            import nemoguardrails
            self._nemo = nemoguardrails
            logger.debug("NeMo Guardrails loaded")
        except ImportError:
            logger.debug("NeMo Guardrails not installed, using pattern matching")

    def check_jailbreak(self, text: str) -> NemoResult:
        """
        Check text for jailbreak attempts.

        Args:
            text: Text to check

        Returns:
            NemoResult with detection result
        """
        for pattern in self.jailbreak_patterns:
            if pattern.search(text):
                return NemoResult(
                    passed=False,
                    confidence=0.9,
                    message="Jailbreak pattern detected",
                    details={"pattern": pattern.pattern},
                )

        return NemoResult(
            passed=True,
            confidence=1.0,
            message="No jailbreak detected",
        )

    # Alias for backward compatibility
    def _check_jailbreak(self, text: str) -> NemoResult:
        return self.check_jailbreak(text)

    def check_toxicity(self, text: str) -> NemoResult:
        """
        Check text for toxic content.

        Args:
            text: Text to check

        Returns:
            NemoResult with detection result
        """
        matched_patterns = []

        for pattern in self.toxicity_patterns:
            if pattern.search(text):
                matched_patterns.append(pattern.pattern)

        if matched_patterns:
            confidence = min(0.9 + len(matched_patterns) * 0.02, 1.0)
            return NemoResult(
                passed=False,
                confidence=confidence,
                message="Toxic content detected",
                details={"patterns_matched": len(matched_patterns)},
            )

        return NemoResult(
            passed=True,
            confidence=1.0,
            message="No toxicity detected",
        )

    # Alias for backward compatibility
    def _check_toxicity(self, text: str) -> NemoResult:
        return self.check_toxicity(text)

    def check_competitor(self, text: str) -> NemoResult:
        """
        Check text for competitor mentions.

        Args:
            text: Text to check

        Returns:
            NemoResult with detection result
        """
        if not self.competitor_patterns:
            return NemoResult(
                passed=True,
                confidence=1.0,
                message="No competitor patterns configured",
            )

        for pattern in self.competitor_patterns:
            match = pattern.search(text)
            if match:
                return NemoResult(
                    passed=False,
                    confidence=0.95,
                    message=f"Competitor mention detected: {match.group()}",
                    details={"matched": match.group()},
                )

        return NemoResult(
            passed=True,
            confidence=1.0,
            message="No competitor mentions detected",
        )

    # Alias for backward compatibility
    def _check_competitor(self, text: str) -> NemoResult:
        return self.check_competitor(text)

    @property
    def stats(self) -> Dict[str, int]:
        """Get engine statistics"""
        return {
            "jailbreak_patterns": len(self.jailbreak_patterns),
            "toxicity_patterns": len(self.toxicity_patterns),
            "competitor_patterns": len(self.competitor_patterns),
            "cache_size": 0,
            "blocked_phrases": 0,
        }
