"""阴性结果检测器：规则模式为主，AI 辅助兜底"""

import logging
import re

logger = logging.getLogger(__name__)

# 阴性结果正则模式
NEGATIVE_PATTERNS: list[re.Pattern] = [
    re.compile(r"no\s+significant\s+difference", re.IGNORECASE),
    re.compile(r"failed\s+to\s+(meet|show|demonstrate|reach|improve)", re.IGNORECASE),
    re.compile(r"negative\s+(result|trial|study|finding)", re.IGNORECASE),
    re.compile(r"did\s+not\s+(show|improve|reduce|meet|demonstrate|achieve)", re.IGNORECASE),
    re.compile(r"not\s+statistically\s+significant", re.IGNORECASE),
    re.compile(r"non[\s-]?significant", re.IGNORECASE),
    re.compile(r"no\s+benefit", re.IGNORECASE),
    re.compile(r"null\s+(result|finding)", re.IGNORECASE),
    re.compile(r"lack\s+of\s+(efficacy|benefit|effect)", re.IGNORECASE),
    re.compile(r"p\s*[≥>]\s*0\.0[5-9]", re.IGNORECASE),
]

# 阳性反匹配：如果这些也存在，降低阴性置信度
POSITIVE_COUNTER_PATTERNS: list[re.Pattern] = [
    re.compile(r"significant\s+(improvement|reduction|benefit|increase|decrease)", re.IGNORECASE),
    re.compile(r"demonstrated\s+(superiority|efficacy|benefit)", re.IGNORECASE),
    re.compile(r"primary\s+endpoint\s+was\s+met", re.IGNORECASE),
    re.compile(r"positive\s+(result|trial|finding)", re.IGNORECASE),
]


def detect_negative_result(abstract: str | None, title: str = "") -> dict:
    """规则式阴性结果检测。

    返回：
    {
        "is_negative": bool,
        "confidence": "high" | "medium" | "low",
        "matched_patterns": ["...", "..."],
    }
    """
    text = f"{title}\n{abstract}" if abstract else title
    if not text.strip():
        return {"is_negative": False, "confidence": "low", "matched_patterns": []}

    matched_neg = []
    for pat in NEGATIVE_PATTERNS:
        m = pat.search(text)
        if m:
            matched_neg.append(m.group(0))

    matched_pos = []
    for pat in POSITIVE_COUNTER_PATTERNS:
        m = pat.search(text)
        if m:
            matched_pos.append(m.group(0))

    if not matched_neg:
        return {"is_negative": False, "confidence": "low", "matched_patterns": []}

    # 阴性模式多于阳性模式时判定为阴性
    neg_count = len(matched_neg)
    pos_count = len(matched_pos)

    if neg_count > pos_count and neg_count >= 2:
        confidence = "high"
        is_negative = True
    elif neg_count > pos_count:
        confidence = "medium"
        is_negative = True
    else:
        return {"is_negative": False, "confidence": "low", "matched_patterns": matched_neg}

    return {
        "is_negative": is_negative,
        "confidence": confidence,
        "matched_patterns": matched_neg,
    }
