"""方法学小结自动生成（模板化，不依赖 AI）"""

from datetime import datetime


def generate_methods_summary(review: dict, flow: dict, language: str = "zh") -> str:
    """根据系统评价元数据和 PRISMA 流程计数生成方法学小结。"""
    databases = review.get("databases_searched") or []
    db_str = "、".join(databases) if databases else "PubMed"

    # 检索日期：从 search_strategy 取，或回退到创建时间
    search_date = None
    strategy = review.get("search_strategy") or {}
    if isinstance(strategy, dict):
        search_date = strategy.get("date") or strategy.get("last_searched") or strategy.get("search_date")
    if not search_date and review.get("created_at"):
        search_date = review["created_at"][:10]

    if language == "en":
        parts = [
            f"We searched {db_str}",
            f"up to {search_date}." if search_date else ".",
        ]
        ident = flow.get("identification_total", 0)
        screened = flow.get("screened", 0)
        ex_screen = flow.get("excluded_screening", 0)
        full_text = flow.get("full_text_assessed", 0)
        ex_elig = flow.get("excluded_eligibility", 0)
        included = flow.get("included_total", 0)
        ex_reasons = flow.get("excluded_reasons", {})

        parts.append(f" After removing duplicates, {screened} records were screened.")
        parts.append(f" {ex_screen} records were excluded based on title and abstract.")
        parts.append(f" {full_text} full-text articles were assessed for eligibility.")

        if ex_reasons:
            reason_items = [f"{k} (n={v})" for k, v in list(ex_reasons.items())[:5]]
            parts.append(f" {ex_elig} records were excluded: {'; '.join(reason_items)}.")

        parts.append(f" Finally, {included} studies were included in the systematic review.")
        return "".join(parts)

    # 中文
    parts = [
        f"我们检索了 {db_str}",
        f"，检索截止至 {search_date}。" if search_date else "。",
    ]
    ident = flow.get("identification_total", 0)
    screened = flow.get("screened", 0)
    ex_screen = flow.get("excluded_screening", 0)
    full_text = flow.get("full_text_assessed", 0)
    ex_elig = flow.get("excluded_eligibility", 0)
    included = flow.get("included_total", 0)
    ex_reasons = flow.get("excluded_reasons", {})

    parts.append(f"去重后共筛选 {screened} 篇文献，")
    parts.append(f"阅读标题摘要排除 {ex_screen} 篇，")
    parts.append(f"共 {full_text} 篇进行全文评估。")

    if ex_reasons:
        reason_items = [f"{k}(n={v})" for k, v in list(ex_reasons.items())[:5]]
        parts.append(f" 全文评估后排除 {ex_elig} 篇（{'；'.join(reason_items)}）。")

    parts.append(f"最终纳入 {included} 篇文献进行系统评价。")
    return "".join(parts)
