"""
Regex pattern-matching judge.

Always returns confidence=1.0 (deterministic).
"""

from __future__ import annotations

import re
from typing import Any, Dict, Optional

from llmhq_releaseops.models.eval_result import AssertionResult
from llmhq_releaseops.models.eval_suite import Assertion


class RegexJudge:
    """Checks if output matches a regex pattern."""

    def evaluate(
        self,
        output: str,
        assertion: Assertion,
        expected: Optional[str] = None,
        context: Optional[Dict[str, Any]] = None,
    ) -> AssertionResult:
        pattern = assertion.config.get("pattern")
        if not pattern:
            return AssertionResult(
                judge_type="regex",
                passed=False,
                confidence=1.0,
                reasoning="Missing 'pattern' in assertion config",
                weight=assertion.weight,
            )

        flags = assertion.config.get("flags", 0)

        try:
            match = re.search(pattern, output, flags=flags)
        except re.error as e:
            return AssertionResult(
                judge_type="regex",
                passed=False,
                confidence=1.0,
                reasoning=f"Invalid regex pattern: {e}",
                weight=assertion.weight,
                details={"pattern": pattern},
            )

        return AssertionResult(
            judge_type="regex",
            passed=match is not None,
            confidence=1.0,
            weight=assertion.weight,
            details={
                "pattern": pattern,
                "matched": match is not None,
                "match": match.group(0) if match else None,
            },
        )
