"""批量补全 DrugApproval.cancer_type_tag_id (瘦客户端版，使用共享服务)"""
import asyncio
from collections import defaultdict

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

from app.config import settings
from app.models.business import DrugApproval, DrugLabel
from app.models.literature import GlobalTag


async def main():
    engine = create_async_engine(settings.DATABASE_URL)
    async with AsyncSession(engine) as db:
        # 构建 tag_cache
        r = await db.execute(
            select(GlobalTag).where(
                GlobalTag.tag_category == "cancer",
                GlobalTag.is_active == True,
            )
        )
        tag_by_name: dict[str, str] = {}
        for t in r.scalars():
            if t.name_en:
                tag_by_name[t.name_en.lower().strip()] = str(t.id)
            if t.name_zh:
                tag_by_name[t.name_zh.lower().strip()] = str(t.id)

        # 先跑 label 回填
        from app.services.drug_cancer_mapper import backfill_from_labels, backfill_from_maps
        label_fixed = await backfill_from_labels(db)
        map_fixed = await backfill_from_maps(db)

        # 统计最终结果
        total = (await db.execute(select(DrugApproval.id))).scalars().all()
        missing_r = await db.execute(
            select(DrugApproval).where(DrugApproval.cancer_type_tag_id.is_(None))
        )
        missing_list = missing_r.scalars().all()
        print(f"总记录: {len(total)}")
        print(f"从 parsed_indications 回填: {label_fixed}")
        print(f"从药品/靶点映射回填: {map_fixed}")
        print(f"仍缺失: {len(missing_list)}")
        for d in missing_list[:10]:
            print(f"  [{d.drug_name}] target={d.target} indication={d.indication[:50]}")
    await engine.dispose()


asyncio.run(main())
