"""RCT 规则检测器：基于 pub_type + 关键词的 RCT 判断，两档可信度。

Trialstreamer 的 num_randomized 仅覆盖约 66 万篇 RCT（全球），
肿瘤学 4-6 万篇中可能有 20-30% 未命中。
此模块提供规则补标，分两档：

- confirmed: pub_type 明确标注 "Randomized Controlled Trial"
- suspected: Clinical Trial pub_type / pub_year>=2000 + 摘要含随机关键词
"""

import re

_RCT_KEYWORD_PAT = re.compile(
    r"\b(randomized|randomised|randomly|randomisation|randomization|"
    r"allocated\s+to\s+(receive|treatment|group|arm)|"
    r"RCT|double-blind|double_blind|placebo-controlled)\b",
    re.IGNORECASE,
)

# 假阳性关键词：回顾性文献中提到 "previous RCT" 或 "a prior RCT" 等情况
_FALSE_POSITIVE_PAT = re.compile(
    r"\b(previous\s+RCT|prior\s+RCT|a\s+prior\s+randomized|"
    r"described\s+elsewhere)\b",
    re.IGNORECASE,
)


def detect_rct(
    pub_types: list[str] | None,
    title: str | None,
    abstract: str | None,
    pub_year: int | None,
) -> dict | None:
    """规则式 RCT 检测，返回两档可信度。

    Args:
        pub_types: PubMed 文献类型列表（GlobalLiterature.pub_types）
        title: 标题
        abstract: 摘要
        pub_year: 发表年份

    Returns:
        {
            "is_rct": True,
            "confidence": "confirmed" | "suspected",
            "source": "pub_type" | "keyword",
            "evidence": "Randomized Controlled Trial" | "abstract: 'randomized to receive...'",
        }
        或 None（非 RCT）
    """
    if not pub_types and not (title or abstract):
        return None

    # ── 第一档：pub_type 明确标注 → confirmed ──
    if pub_types:
        for pt in pub_types:
            if pt in ("Randomized Controlled Trial", "Controlled Clinical Trial"):
                return {
                    "is_rct": True,
                    "confidence": "confirmed",
                    "source": "pub_type",
                    "evidence": pt,
                }

    # ── 第二档：规则补标 → suspected ──
    # 限制年份：2000 年前的老文献不做规则推断
    if pub_year is not None and pub_year < 2000:
        return None

    # 合并标题 + 摘要做关键词匹配
    haystack = " ".join(filter(None, [title or "", abstract or ""]))

    # 假阳性检查
    if _FALSE_POSITIVE_PAT.search(haystack):
        return None

    # 关键词匹配
    m = _RCT_KEYWORD_PAT.search(haystack)
    if not m:
        return None

    # 默认 check_typo is_rct is_rct is_rct  is_rct
    # "Clinical Trial" pub_type + 关键词 = suspected
    is_clinical_trial = bool(
        pub_types and any("Clinical Trial" in pt for pt in pub_types)
    )
    if not is_clinical_trial:
        # 没有 Clinical Trial 发表类型时，仅标题含关键词才标（降低摘要假阳性）
        if not title or not re.search(_RCT_KEYWORD_PAT, title):
            return None

    return {
        "is_rct": True,
        "confidence": "suspected",
        "source": "keyword",
        "evidence": f"{'title' if title and _RCT_KEYWORD_PAT.search(title) else 'abstract'}: '{m.group(0)}'",
    }
