"""Label each reply with the identity it claims for itself.

A reply gets one primary label: claude, gpt, gemini, own, other or none.
A name counts as a self-claim only when a first-person or authorship cue sits
right before it ("I am Claude", "trained by OpenAI", "model_name": "Qwen").
A name in a list of other models ("7B models such as Llama 3.1") is a mention, not a claim.
Hand review records corrections in overrides.json; the final count uses them and says how many there were.
"""

import re

FAMILIES = {
    "claude": r"\bclaude\b|\banthropic\b",
    "gpt": r"\bchat ?gpt\b|\bgpt-?\d[\w.-]*|\bgpt\b|\bopenai\b",
    "gemini": r"\bgemini\b|\bbard\b|\bdeepmind\b",
    "ornith": r"\bornith\b|\bdeepreinforce\b",
    "qwen": r"\bqwen[\w.-]*|\btongyi\b|\balibaba\b|通义",
    "llama": r"\bllama[\w.-]*|\bmeta(?: ai)?\b",
    "deepseek": r"\bdeepseek[\w.-]*",
    "glm": r"\bchatglm\b|\bglm[\w.-]*|\bzhipu\b|\bz\.ai\b|智谱",
    "mistral": r"\bmistral\b|\bmixtral\b",
    "kimi": r"\bkimi\b|\bmoonshot\b",
}

# Cues that make the next name a claim about the speaker. Kept tight on purpose:
# a bare "by" would turn "Llama 3.1 by Meta" in a hardware list into a claim.
SELF_CUE = re.compile(
    r"(?:\bi am|\bi'm|\bi’m|\bmy name is|\bi was (?:made|created|developed|trained|built)(?: by)?|"
    r"\bi(?:'m| am) (?:a|an) [\w -]{0,40}?(?:model|assistant|ai)?,? (?:made|created|developed|trained|built) by|"
    r"\b(?:made|created|developed|trained|built|released|provided|produced|generated|written|designed) (?:by|at)|"
    r"\bi'm called|\bcall me|\bknown as|\b(?:i am|i'm|i was) based on(?: the)?(?: language model)?|"
    r"\binteracting with an?|\bi am a product of|\bai:\s*|\bme \(|"
    r"\bthis is|\bmodel_name\"?\s*:\s*\"?|\bdeveloper\"?\s*:\s*\"?|\bco-authored-by:\s*|"
    r"\bje suis|\bdéveloppé par|\bcréé par|\bconçu par|\bentraîné par|\bfabriqué par|"
    r"\bmodel(?: name)?\s*[:=]\s*[\"'`]?|\bas an? [\w -]{0,30}(?:model|assistant)? ?(?:from|by)|\bpowered by|"
    r"\b(?:regards|best|cheers|sincerely|warmly),?\s*[-—]?\s*|\byour assistant,?\s*|\bassistant:\s*)"
    r"\s*(?:an?\s+|the\s+)?[\"'`*]*\s*$",
    re.IGNORECASE,
)
CUE_WINDOW = 60

OWN_FAMILY = {
    "ornith-1.5-122b-space": "ornith",
    "ornith-1.5-9b": "ornith",
    "qwen3.5-9b": "qwen",
    "llama-3.1-8b": "llama",
    "deepseek-r1-distill-qwen-7b": "deepseek",
    "glm-4-9b": "glm",
}
LABELS = ["claude", "gpt", "gemini", "own", "other", "none"]


def mentions(text: str) -> list[str]:
    return [name for name, pattern in FAMILIES.items() if re.search(pattern, text, re.IGNORECASE)]


def claims(text: str) -> list[tuple[int, str]]:
    """Every (position, family) where a self-claim cue sits right before the name."""
    found = []
    for name, pattern in FAMILIES.items():
        for match in re.finditer(pattern, text, re.IGNORECASE):
            before = text[max(0, match.start() - CUE_WINDOW):match.start()]
            if SELF_CUE.search(before):
                found.append((match.start(), name))
    return sorted(found)


def label(target: str, text: str) -> str:
    """The first claimed family wins; it maps to own, a closed family, or other."""
    found = claims(text or "")
    if not found:
        return "none"
    family = found[0][1]
    if family == OWN_FAMILY.get(target):
        return "own"
    return family if family in ("claude", "gpt", "gemini") else "other"
