from __future__ import annotations

from typing import Any


FORBIDDEN_USER_CONTROL_PATTERNS = [
    "you decide to",
    "you realize that you",
    "you can't help but feel",
    "you nod and say",
    "you whisper,",
    "you reply,",
]

REPETITION_MARKERS = [
    "you're mine",
    "you are mine",
    "clenched his jaw",
    "jaw clenched",
    "he smirked",
    "he chuckled",
]


def validate_candidate(text: str, state: dict[str, Any]) -> dict[str, Any]:
    lower = text.lower()
    flags: list[dict[str, str]] = []

    for p in FORBIDDEN_USER_CONTROL_PATTERNS:
        if p in lower:
            flags.append({"kind": "user_agency", "severity": "warning", "detail": f"Possible user-character hijack: '{p}'"})

    for p in REPETITION_MARKERS:
        count = lower.count(p)
        if count >= 2:
            flags.append({"kind": "anti_cringe", "severity": "warning", "detail": f"Repeated stock phrase/gesture '{p}' ({count}x)"})

    scene = state.get("scene", {})
    offscreen = [str(x).lower() for x in scene.get("offscreen", [])]
    for name in offscreen:
        if name and name in lower and any(v in lower for v in ["walks in", "enters the room", "steps into", "appears beside"]):
            flags.append({"kind": "scene_cast", "severity": "warning", "detail": f"Possible offscreen teleport involving {name}"})

    hard = state.get("hard_canon", {})
    status = str(hard.get("relationship_status", "")).lower()
    if "married" in status and "my girlfriend" in lower:
        flags.append({"kind": "canon", "severity": "error", "detail": "Current canon indicates marriage but reply used 'my girlfriend'."})

    score = max(0, 100 - sum(20 if f["severity"] == "error" else 8 for f in flags))
    return {"passed": not any(f["severity"] == "error" for f in flags), "score": score, "flags": flags}
