"""Expert 2 — Relational Fidelity.

Is the cause + mechanism correct?
Source: Scientific Narrative Fidelity, Layer 2.

We check token overlap between the story and the `mechanism` field of
the KC's misconceptions. 2+ overlapping content words => the story has
covered the actual mechanism, not just the phenomenon name.

Scoring:
  1.0  >= 2 mechanism tokens appear in the story
  0.7  1 mechanism token appears
  0.4  >= 2 misconception tokens appear
  0.2  1 misconception token appears
  0.1  neither
"""
import re

STOPWORDS = {
    'the', 'a', 'an', 'is', 'are', 'was', 'were', 'and', 'or', 'of',
    'to', 'in', 'on', 'at', 'by', 'for', 'with', 'as', 'that', 'this',
    'aik', 'aur', 'hai', 'hain', 'ka', 'ki', 'ko', 'se', 'me', 'mein',
    'ye', 'wo', 'ne', 'us', 'un', 'hum', 'tum',
}
TOKEN_RE = re.compile(r'[a-z\u0600-\u06ff]+')


def _tokens(text):
    if not text:
        return set()
    words = TOKEN_RE.findall(text.lower())
    return {w for w in words if w not in STOPWORDS and len(w) > 2}


def evaluate(kc, story_text):
    story_tokens = _tokens(story_text)
    if not story_tokens:
        return 0.0

    misconceptions = kc.misconceptions if isinstance(kc.misconceptions, list) else []
    if not misconceptions:
        return 0.1

    best_mech = 0
    best_mis = 0
    for m in misconceptions:
        if not isinstance(m, dict):
            continue
        mech_tokens = _tokens(m.get('mechanism') or '')
        mis_tokens = _tokens(m.get('text') or '')
        best_mech = max(best_mech, len(story_tokens & mech_tokens))
        best_mis = max(best_mis, len(story_tokens & mis_tokens))

    if best_mech >= 2:
        return 1.0
    if best_mech >= 1:
        return 0.7
    if best_mis >= 2:
        return 0.4
    if best_mis >= 1:
        return 0.2
    return 0.1
