"""
为 CSCO/NHC 指南补充证据链.
每指南取该癌种被引最高的 2-3 条文献作为支撑证据。

安全: 只做 INSERT，已有则跳过，可反复运行。
"""

import asyncio
import uuid

from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine

from app.config import settings
from app.models.business import GuidelineVersion, GuidelineEvidence
from app.models.literature import GlobalLiterature, GlobalLiteratureTag


async def main():
    engine = create_async_engine(settings.DATABASE_URL)
    async with AsyncSession(engine) as db:
        # 收集所有指南信息（一次性提取到 dict，避免后续 lazy load）
        r = await db.execute(
            select(GuidelineVersion).where(
                GuidelineVersion.guideline_source.in_(["CSCO", "NHC"])
            )
        )
        all_gv = [(gv.id, gv.guideline_source, gv.version, gv.cancer_type_tag_id)
                  for gv in r.scalars().all()]
        print(f"找到 {len(all_gv)} 条 CSCO/NHC 指南")

        # 过滤已有证据的
        todo = []
        for gid, src, ver, tag_id in all_gv:
            if not tag_id:
                continue
            r = await db.execute(
                select(func.count(GuidelineEvidence.id))
                .where(GuidelineEvidence.guideline_version_id == gid)
            )
            cnt = r.scalar() or 0
            if cnt > 0:
                print(f"  [{src} {ver}] 已有 {cnt} 条证据，跳过")
                continue
            todo.append({"id": gid, "source": src, "version": ver, "tag_id": tag_id})

        # 逐一补证据
        total = 0
        for item in todo:
            r = await db.execute(
                select(GlobalLiterature)
                .where(
                    GlobalLiterature.id.in_(
                        select(GlobalLiteratureTag.literature_id)
                        .where(GlobalLiteratureTag.tag_id == item["tag_id"])
                    )
                )
                .order_by(GlobalLiterature.cited_by_count.desc().nullslast())
                .limit(3)
            )
            lits = r.scalars().all()
            if not lits:
                print(f"  [{item['source']} {item['version']}] 无匹配文献")
                continue
            # 提取数据到 plain tuple
            lit_data = [(lit.id, lit.pmid) for lit in lits]
            for lid, _ in lit_data:
                db.add(GuidelineEvidence(
                    id=uuid.uuid4(),
                    guideline_version_id=item["id"],
                    literature_id=lid,
                    recommendation_level="2A",
                ))
            await db.commit()
            pmids = [p for _, p in lit_data]
            print(f"  [{item['source']} {item['version']}] 插入 {len(lit_data)} 条证据 (PMID: {pmids})")
            total += len(lit_data)

        print(f"\n完成！共插入 {total} 条证据")
    await engine.dispose()


if __name__ == "__main__":
    asyncio.run(main())
