"""Layer 3: Cross-lens integration scoring via LLM judge."""

from __future__ import annotations

import re

from .llm_client import JudgeLLM
from .prompts import INTEGRATION_SYSTEM_PROMPT, INTEGRATION_USER_PROMPT


def _parse_score(response: str) -> int:
    m = re.search(r"Score:\s*(\d)", response)
    if m:
        return max(1, min(5, int(m.group(1))))
    m = re.search(r"\d", response)
    return max(1, min(5, int(m.group(0)))) if m else 3


async def evaluate_layer3(
    judge: JudgeLLM,
    output: str,
    input_text: str,
    repeat: int = 3,
) -> float:
    """Score cross-lens integration (1-5), averaged over *repeat* runs."""
    scores: list[int] = []
    for _ in range(repeat):
        user = INTEGRATION_USER_PROMPT.format(
            input_text=input_text[:2000],
            output=output[:4000],
        )
        response = await judge.judge(INTEGRATION_SYSTEM_PROMPT, user)
        scores.append(_parse_score(response))
    return sum(scores) / len(scores)
