"""癌种关注通知服务：新药/指南更新时推送给关注对应癌种的用户"""

from uuid import UUID

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

from app.models.interaction import UserSubscription
from app.models.operations import SystemNotification
from app.models.literature import GlobalTag


async def notify_cancer_subscribers(
    db: AsyncSession,
    tag_id: UUID,
    title: str,
    content: str,
    url: str,
    *,
    tenant_id: UUID | None = None,
):
    """通知所有关注某癌种的用户

    Args:
        tenant_id: 如果提供，仅通知该租户内关注此癌种的用户
    """
    q = select(UserSubscription).where(
        UserSubscription.tag_id == tag_id,
        UserSubscription.is_active == True,
    )
    if tenant_id:
        q = q.where(UserSubscription.tenant_id == tenant_id)
    r = await db.execute(q)
    subs = r.scalars().all()
    if not subs:
        return 0

    # 去重 user_id（同用户可能订阅了父+子标签）
    seen = set()
    count = 0
    for sub in subs:
        uid = sub.user_id
        if uid in seen:
            continue
        seen.add(uid)
        notif = SystemNotification(
            title=title,
            content=content,
            target_type="user",
            target_id=uid,
        )
        db.add(notif)
        count += 1

    await db.commit()
    return count


async def notify_new_guideline(
    db: AsyncSession,
    tag_id: UUID,
    source: str,
    version: str,
    cancer_type: str,
    change_summary: str | None,
):
    """有新指南版本时推送给关注对应癌种的用户"""
    title = f"📋 {cancer_type} 指南更新"
    summary = (change_summary or "")[:100]
    content = f"{source} {version} — {summary}" if summary else f"{source} {version} 已更新"
    return await notify_cancer_subscribers(
        db, tag_id, title, content, url="/guidelines",
    )


async def notify_new_drug_approval(
    db: AsyncSession,
    tag_id: UUID,
    drug_name: str,
    target: str,
    indication: str,
):
    """有新药审批时推送给关注对应癌种的用户"""
    # 获取癌种中文名
    tag = await db.get(GlobalTag, tag_id)
    cancer_name = tag.name_zh or tag.name_en or "肿瘤" if tag else "肿瘤"
    title = f"💊 {cancer_name} 新药获批"
    content = f"{drug_name}（靶点 {target}）— {indication[:80]}{'…' if len(indication) > 80 else ''}"
    return await notify_cancer_subscribers(
        db, tag_id, title, content, url="/drugs",
    )
