"""系统评价导出引擎：Rich CSV + RevMan-compatible RIS"""

# ═══ License 映射 ═══
# 用于导出时自动标注许可使用限制。
# 自动识别仅供参考，请用户自行核对最终输出。

_LICENSE_NOTES: dict[str, str] = {
    "CC-BY": "无限制（CC BY）",
    "CC-BY-2.0": "无限制（CC BY 2.0）",
    "CC-BY-2.5": "无限制（CC BY 2.5）",
    "CC-BY-3.0": "无限制（CC BY 3.0）",
    "CC-BY-4.0": "无限制（CC BY 4.0）",
    "CC-BY-SA": "可再分发（CC BY-SA）",
    "CC-BY-NC": "仅个人科研/教学（CC BY-NC）",
    "CC-BY-NC-3.0": "仅个人科研/教学（CC BY-NC 3.0）",
    "CC-BY-NC-4.0": "仅个人科研/教学（CC BY-NC 4.0）",
    "CC-BY-NC-ND": "仅个人科研/教学，不可改编（CC BY-NC-ND）",
    "CC0": "无限制（CC0）",
    "PDM": "无限制（Public Domain Mark）",
}


def _get_license_note(license_info: dict | None) -> str:
    """从 license_info 推断导出许可备注。"""
    if not license_info:
        return "请核对出版社政策"
    lic_type = license_info.get("type")
    if lic_type in _LICENSE_NOTES:
        return _LICENSE_NOTES[lic_type]
    # 从文字推断
    text = (license_info.get("text") or "").lower()
    href = (license_info.get("href") or "").lower()
    if "cc by" in text or "creative commons" in text or "cc by" in href:
        if "noncommercial" in text or "non-commercial" in text or "nc" in href:
            if "nd" in href or "nd" in text:
                return "仅个人科研/教学，不可改编（CC BY-NC-ND，自动识别仅供参考）"
            return "仅个人科研/教学（CC BY-NC，自动识别仅供参考）"
        if "sa" in href or "sharealike" in text:
            return "可再分发（CC BY-SA，自动识别仅供参考）"
        return "无限制（CC BY，自动识别仅供参考）"
    return "请核对出版社政策"


def _clean(s: str | None) -> str:
    return (s or "").replace('"', '""').replace("\n", " ").replace("\r", "")


def _first_author(authors: list) -> str:
    if not authors:
        return ""
    a = authors[0]
    return f"{a.get('family', '')}, {a.get('given', '')}".strip(", ")


def _pico_field(pico: dict | None, key: str) -> str:
    if not pico:
        return ""
    val = pico.get(key)
    if isinstance(val, str):
        return _clean(val)
    return ""


def export_review_csv(review: dict, literatures: list[dict]) -> str:
    """评价富 CSV 导出：包含研究设计、PICO、质量评分、撤稿状态、许可信息等。"""
    cols = [
        "PMID", "Title", "Authors", "Journal", "Year", "DOI",
        "StudyDesign", "StudySubType", "Population", "Intervention",
        "Comparator", "Outcome", "SampleSize", "EffectSize",
        "QualityScore", "Retracted", "TrialRegNCT",
        "LicenseType", "LicenseNote",
        "PRISMA_Stage", "ExclusionReason", "Notes",
    ]
    header = ",".join(f'"{c}"' for c in cols) + "\n"
    rows = []
    for lit in literatures:
        authors = (lit.get("authors") or []) if isinstance(lit.get("authors"), list) else []
        sd = lit.get("study_design") or {}
        pico = lit.get("pico") or {}
        trial_reg = lit.get("trial_reg") or {}
        license_info = lit.get("license_info") or {}
        row = [
            str(lit.get("pmid", "")),
            _clean(lit.get("title", "")),
            _clean(_first_author(authors)),
            _clean(lit.get("journal", "")),
            str(lit.get("pub_year", "")),
            _clean(lit.get("doi", "")),
            _clean(sd.get("primary", "")),
            _clean(sd.get("sub", "")),
            _pico_field(pico, "population"),
            _pico_field(pico, "intervention"),
            _pico_field(pico, "comparator"),
            _pico_field(pico, "outcome"),
            _clean(str(pico.get("sample_size", ""))),
            _clean(str(pico.get("effect_size", ""))),
            lit.get("quality_score", ""),
            "Yes" if lit.get("retracted") else "",
            _clean(trial_reg.get("nct", "")),
            _clean(license_info.get("type", "")),
            _get_license_note(license_info),
            lit.get("stage", ""),
            _clean(lit.get("exclusion_reason", "")),
            _clean(lit.get("notes", "")),
        ]
        rows.append(",".join(f'"{c}"' for c in row))
    return header + "\n".join(rows)


def export_review_ris(review: dict, literatures: list[dict]) -> str:
    """RevMan-compatible RIS 导出。
    标准 RIS 字段 + 自定义标签:
      L1  - Study design (primary)
      L2  - Study sub-type
      CT  - Clinical trial registry (NCT)
      LB  - Retracted flag
      N2  - License note, quality score, notes
    """
    records = []
    for lit in literatures:
        authors = (lit.get("authors") or []) if isinstance(lit.get("authors"), list) else []
        sd = lit.get("study_design") or {}
        trial_reg = lit.get("trial_reg") or {}
        quality = lit.get("quality_score", "")
        license_info = lit.get("license_info") or {}

        lines = ["TY  - JOUR"]
        lines.append(f"TI  - {_clean(lit.get('title'))}")
        lines.append(f"JO  - {_clean(lit.get('journal'))}")
        if lit.get("pub_year"):
            lines.append(f"PY  - {lit.get('pub_year')}")
        if lit.get("doi"):
            lines.append(f"DO  - {lit.get('doi')}")
        if lit.get("volume"):
            lines.append(f"VL  - {lit.get('volume')}")
        if lit.get("issue"):
            lines.append(f"IS  - {lit.get('issue')}")
        if lit.get("pages"):
            lines.append(f"SP  - {lit.get('pages')}")
        for a in authors:
            family = a.get("family", "")
            given = a.get("given", "")
            if family or given:
                lines.append(f"AU  - {family}, {given}")
        lines.append(f"UR  - https://pubmed.ncbi.nlm.nih.gov/{lit.get('pmid', '')}/")

        # 自定义标签
        if sd.get("primary"):
            lines.append(f"L1  - {sd['primary']}")
        if sd.get("sub"):
            lines.append(f"L2  - {sd['sub']}")
        if trial_reg.get("nct"):
            lines.append(f"CT  - {trial_reg['nct']}")
        if lit.get("retracted"):
            lines.append("LB  - Retracted")
        if license_info.get("type"):
            lines.append(f"N2  - License: {_clean(license_info['type'])}")
            lines.append(f"N2  - {_get_license_note(license_info)}")
        if quality:
            lines.append(f"N2  - Quality: {quality}")
        if lit.get("exclusion_reason"):
            lines.append(f"N2  - Exclusion: {_clean(lit['exclusion_reason'])}")

        lines.append("ER  - ")
        records.append("\n".join(lines))

    return "\n\n".join(records)
