"""研究设计分类映射表：PubMed pub_types → 分层研究设计分类"""

from typing import Literal

# 一级分类（研究大类）
StudyCategory = Literal[
    "interventional",     # 干预性研究（RCT / non-RCT / single-arm）
    "observational",      # 观察性研究（队列 / 病例对照 / 横断面）
    "diagnostic",         # 诊断性研究
    "synthesis",          # 综合研究（Meta 分析 / 系统评价 / 综述）
    "qualitative",        # 定性研究
    "case_series",        # 病例系列 / 病例报告
    "guideline",          # 指南 / 共识
    "other",              # 其他
]

# 二级分类（具体设计）
StudySubType = Literal[
    "rct", "rct_phase_3", "rct_phase_2", "rct_phase_1",
    "non_randomized", "single_arm",
    "cohort", "case_control", "cross_sectional",
    "diagnostic_accuracy",
    "meta_analysis", "systematic_review", "narrative_review",
    "case_report", "case_series",
    "guideline", "consensus",
    "editorial", "letter", "comment",
    "other",
]

# 三级：具体设计特征
StudyDesignFeature = Literal[
    "parallel", "crossover", "factorial",
    "superiority", "non_inferiority", "equivalence",
    "prospective", "retrospective", "ambidirectional",
    "multicenter", "single_center",
    "open_label", "double_blind", "single_blind",
    "pragmatic", "explanatory",
    "adaptive",
]

# ═══ 映射规则 ═══

# pub_type → (primary category, sub_type, design hint)
PUBTYPE_MAP: dict[str, tuple[str, str, str | None]] = {
    # 干预性研究
    "Randomized Controlled Trial":           ("interventional", "rct", "parallel"),
    "Controlled Clinical Trial":             ("interventional", "rct", "parallel"),
    "Clinical Trial, Phase III":             ("interventional", "rct_phase_3", "parallel"),
    "Clinical Trial, Phase II":              ("interventional", "rct_phase_2", None),
    "Clinical Trial, Phase I":               ("interventional", "rct_phase_1", None),
    "Clinical Trial, Phase IV":              ("interventional", "rct", None),
    "Clinical Trial":                        ("interventional", "non_randomized", None),
    "Equivalence Trial":                     ("interventional", "rct", "equivalence"),
    "Non-Randomized Controlled Trial":       ("interventional", "non_randomized", None),
    "Adaptive Clinical Trial":               ("interventional", "rct", "adaptive"),
    "Pragmatic Clinical Trial":              ("interventional", "rct", "pragmatic"),
    "Single-Arm Study":                      ("interventional", "single_arm", None),

    # 观察性研究
    "Observational Study":                   ("observational", "cohort", None),
    "Cohort Study":                          ("observational", "cohort", None),
    "Case-Control Study":                    ("observational", "case_control", None),
    "Cross-Sectional Study":                 ("observational", "cross_sectional", None),
    "Longitudinal Study":                    ("observational", "cohort", "prospective"),
    "Prospective Study":                     ("observational", "cohort", "prospective"),
    "Retrospective Study":                   ("observational", "cohort", "retrospective"),
    "Twin Study":                            ("observational", "cohort", None),
    "Comparative Study":                     ("observational", "cohort", None),

    # 诊断性研究
    "Diagnostic Study":                      ("diagnostic", "diagnostic_accuracy", None),
    "Evaluation Study":                      ("diagnostic", "diagnostic_accuracy", None),
    "Validation Study":                      ("diagnostic", "diagnostic_accuracy", None),

    # 综合研究
    "Meta-Analysis":                         ("synthesis", "meta_analysis", None),
    "Systematic Review":                     ("synthesis", "systematic_review", None),
    "Review":                                ("synthesis", "narrative_review", None),
    "Narrative Review":                      ("synthesis", "narrative_review", None),
    "Scoping Review":                        ("synthesis", "systematic_review", None),
    "Systematic Review as Topic":            ("synthesis", "systematic_review", None),
    "Meta-Analysis as Topic":                ("synthesis", "meta_analysis", None),

    # 指南 / 共识
    "Practice Guideline":                    ("guideline", "guideline", None),
    "Guideline":                             ("guideline", "guideline", None),
    "Consensus Development Conference":      ("guideline", "consensus", None),
    "Consensus Development Conference, NIH": ("guideline", "consensus", None),

    # 病例报告 / 系列
    "Case Reports":                          ("case_series", "case_report", None),
    "Case Report":                           ("case_series", "case_report", None),
    "Clinical Conference":                   ("case_series", "case_report", None),
    "Case Series":                           ("case_series", "case_series", None),

    # 定性研究
    "Qualitative Research":                  ("qualitative", "other", None),
    "Interview":                             ("qualitative", "other", None),
    "Focus Group":                           ("qualitative", "other", None),

    # 其他
    "Editorial":                             ("other", "editorial", None),
    "Letter":                                ("other", "letter", None),
    "Comment":                               ("other", "comment", None),
    "News":                                  ("other", "comment", None),
    "Historical Article":                    ("other", "other", None),
    "Biography":                             ("other", "other", None),
    "Portrait":                              ("other", "other", None),
    "Published Erratum":                     ("other", "other", None),
    "Introductory Journal Article":          ("other", "other", None),
    "Address":                               ("other", "other", None),
    "Festschrift":                           ("other", "other", None),
    "Lecture":                               ("other", "other", None),
    "Personal Narrative":                    ("other", "other", None),
    "Webcast":                               ("other", "other", None),
}

# 中文标签（供前端展示）
CATEGORY_LABELS: dict[str, str] = {
    "interventional": "干预性研究",
    "observational": "观察性研究",
    "diagnostic": "诊断性研究",
    "synthesis": "综合研究",
    "qualitative": "定性研究",
    "case_series": "病例报告",
    "guideline": "指南/共识",
    "other": "其他",
}

SUB_LABELS: dict[str, str] = {
    "rct": "RCT",
    "rct_phase_3": "3期RCT",
    "rct_phase_2": "2期RCT",
    "rct_phase_1": "1期RCT",
    "non_randomized": "非随机对照",
    "single_arm": "单臂研究",
    "cohort": "队列研究",
    "case_control": "病例对照",
    "cross_sectional": "横断面研究",
    "diagnostic_accuracy": "诊断准确性",
    "meta_analysis": "Meta分析",
    "systematic_review": "系统评价",
    "narrative_review": "综述",
    "case_report": "病例报告",
    "case_series": "病例系列",
    "guideline": "指南",
    "consensus": "共识",
    "editorial": "社论",
    "letter": "信件",
    "comment": "评论",
    "other": "其他",
}


def classify_study_design(pub_types: list[str]) -> dict | None:
    """将 PubMed pub_types 映射为分层研究设计分类。

    返回:
    {"primary": "interventional", "sub": "rct", "design": "parallel", "label_zh": "RCT"}
    或 None（无法识别时）
    """
    if not pub_types:
        return None

    # 按优先级取第一个可识别的
    for pt in pub_types:
        mapped = PUBTYPE_MAP.get(pt)
        if mapped:
            cat, sub, design = mapped
            return {
                "primary": cat,
                "sub": sub,
                "design": design,
                "label_zh": SUB_LABELS.get(sub, sub),
            }

    return None
