"""Exact prompt templates and strict score parser for HTV-Unseen-v1."""
from __future__ import annotations

import re

SCORE_LINE_RE = re.compile(r"(?im)^\s*(?:\*\*)?(?:Rule-based\s+)?Score(?:\*\*)?\s*[:=]\s*<?([1-5])>?\b")
SCORE_FALLBACK_RE = re.compile(r"(?i)\bScore\)?\s*[:=]\s*<?([1-5])>?(?:\b|(?=>))")
SCORE_PROSE_RE = re.compile(
    r"(?i)\b(?:score(?:\s+of|\s+is)?|scoring|rate\s+it(?:\s+a)?|rating(?:\s+it)?|making\s+it|explanation\s+is)\s*[:=]?\s*(?:a\s+)?([1-5])\b"
)
VARIATION_RE = re.compile(r"(?im)^\s*(?:\*\*)?Variation(?:\*\*)?\s*:\s*(.+)$")

V0_RUBRIC_BODY = """Score each explanation on its own, from 1 to 5. Score how it is built, not whether it is true: a wrong explanation can be hard to vary, and a vague one can happen to be right.

Find the free details. A detail is free if you can change it to something different and the explanation still accounts for the phenomenon just as well, judged with the general knowledge of an educated reader. A detail is a cause, an agent, a mechanism, or a quantity the explanation actually uses. Write down the best variation you found.

Go down the table and give the first score whose description fits:
1: It would explain the opposite observation just as well.
2: Most of its details are free, or it contains a clause that does nothing except match a known fact.
3: At least one central detail (the cause, agent or mechanism) is free.
4: Only a minor detail is free, such as a quantity that could shift a little without breaking anything.
5: You found no free detail.

Explanations are short, so judge what the text says, not what a textbook version of it would add."""


def build_messages(protocol: str, phenomenon: str, explanation: str) -> list[dict[str, str]]:
    if protocol == "P_naive":
        sys_msg = (
            "You rate short scientific and everyday explanations on a 1 to 5 quality scale "
            "(1 = very poor, 5 = excellent). Reply concisely in exactly one line:\nScore: <integer 1-5>"
        )
        usr_msg = (
            f"Phenomenon: {phenomenon}\n"
            f"Explanation: {explanation}\n\n"
            "Rate how good this explanation is from 1 to 5.\n"
            "End with exactly: Score: <1-5>"
        )
        return [{"role": "system", "content": sys_msg}, {"role": "user", "content": usr_msg}]

    if protocol == "P_v0":
        sys_msg = (
            "You apply the following explanation rubric strictly to the text provided. "
            "Be concise (at most 20 words for Variation) and always end with:\n"
            "Variation: <short description of the best variation, or none>\n"
            "Score: <integer 1-5>"
        )
        usr_msg = (
            f"{V0_RUBRIC_BODY}\n\n"
            f"Phenomenon: {phenomenon}\n"
            f"Explanation: {explanation}\n\n"
            "Reply concisely in these exact two lines:\n"
            "Variation: <short variation under 20 words, or none>\n"
            "Score: <1-5>"
        )
        return [{"role": "system", "content": sys_msg}, {"role": "user", "content": usr_msg}]

    if protocol == "P_counterfactual":
        sys_msg = (
            "You apply the following explanation rubric strictly to the text provided, using a concise two-step counterfactual substitution check before scoring.\n\n"
            f"{V0_RUBRIC_BODY}\n\n"
            "Two-step counterfactual check (judge ONLY what the text states):\n"
            "1. Core swap: pick the central cause/mechanism in the text, write `<original> -> <different cause/mechanism>`, and mark [BOUND] if that swap breaks or reverses the explanation, [FREE] if it still accounts for the phenomenon, or [OPPOSITE] if the unchanged text already explains the opposite observation just as well.\n"
            "2. Extra swap: if the text contains any specific number, timestamp, measurement, or extra clause, write `<original> -> <different value>` and mark [FREE] if changing it leaves the explanation accounting for the phenomenon just as well, [BOUND] if changing it breaks the mechanism, or `none -> none [NONE]` if there is no extra number/clause.\n"
            "3. Score (first matching rule 1 -> 5): give 1 if [OPPOSITE]; give 2 if Extra swap is [FREE] or most details are [FREE]; give 3 if Core swap is [FREE]; give 4 if Core swap is [BOUND] and only a minor quantity shifts slightly; give 5 if Core swap is [BOUND] and Extra swap is [BOUND] or [NONE].\n\n"
            "Reply ONLY in these exact three lines (under 18 words per line, no extra commentary):\n"
            "Core swap: <original> -> <swap> [BOUND or FREE or OPPOSITE]\n"
            "Extra swap: <original> -> <swap> [FREE or BOUND or NONE]\n"
            "Score: <1-5>"
        )
        usr_msg = (
            f"Phenomenon: {phenomenon}\n"
            f"Explanation: {explanation}\n\n"
            "Reply in the exact three lines (Core swap / Extra swap / Score):"
        )
        return [{"role": "system", "content": sys_msg}, {"role": "user", "content": usr_msg}]

    raise ValueError(f"Unknown protocol: {protocol}")


def parse_score(text: str) -> int | None:
    matches = SCORE_LINE_RE.findall(text)
    if matches:
        return int(matches[-1])
    fb = SCORE_FALLBACK_RE.findall(text)
    if fb:
        return int(fb[-1])
    prose = SCORE_PROSE_RE.findall(text)
    if prose:
        return int(prose[-1])
    return None


def parse_variation(text: str) -> str | None:
    m = VARIATION_RE.findall(text)
    return m[-1].strip() if m else None
