"""每日摘要邮件定时发送服务"""

import logging
import uuid

logger = logging.getLogger(__name__)

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

from app.db import async_session
from app.models.interaction import UserFeed
from app.models.literature import GlobalLiterature
from app.models.user import User
from app.services.email_service import build_daily_digest, send_email


async def send_daily_digest_to_user(db: AsyncSession, user_id: str, user_email: str, user_name: str) -> int:
    """为一个用户生成并发送每日摘要邮件"""
    uid = uuid.UUID(user_id)
    # 查今日 Feed
    result = await db.execute(
        select(UserFeed, GlobalLiterature)
        .join(GlobalLiterature, UserFeed.literature_id == GlobalLiterature.id)
        .where(UserFeed.user_id == uid, UserFeed.is_read == False, UserFeed.is_dismissed == False)
        .order_by(UserFeed.priority).limit(30)
    )
    rows = result.all()
    if not rows:
        return 0

    feed_items = []
    for feed, lit in rows:
        authors = lit.authors or []
        first_author = authors[0].get("family", "") if authors else ""
        feed_items.append({
            "title": lit.title,
            "journal": lit.journal,
            "first_author": first_author,
            "priority": feed.priority,
            "tags": [],
        })

    html = build_daily_digest(feed_items, user_name)
    success = await send_email(user_email, f"📖 今日肿瘤学速览 ({len(feed_items)}篇)", html)
    return len(feed_items) if success else 0


async def send_all_daily_digests() -> dict:
    """遍历所有活跃用户，发送每日摘要"""
    stats = {"users": 0, "sent": 0, "total_feed_items": 0}
    async with async_session() as db:
        # 找所有订阅了标签的活跃用户
        result = await db.execute(
            select(User.id, User.email, User.display_name)
            .where(User.is_active == True)
            .limit(1000)
        )
        users = result.all()

        for uid, email, name in users:
            count = await send_daily_digest_to_user(db, str(uid), email, name)
            if count > 0:
                stats["sent"] += 1
                stats["total_feed_items"] += count
            stats["users"] += 1

    return stats


async def run_daily_digest() -> None:
    """定时任务入口（供 ARQ 定时调用）"""
    stats = await send_all_daily_digests()
    logger.info("Daily digest sent to %d/%d users, %d items", stats['sent'], stats['users'], stats['total_feed_items'])
    return stats
