"""ARQ Worker 启动配置 + 定时任务"""

from arq import cron
from arq.connections import RedisSettings

from app.config import settings
from app.services.pubmed_api import pull_daily_oncology, pull_broad_oncology


async def startup(ctx):
    """Worker 启动时初始化资源"""
    pass


async def shutdown(ctx):
    """Worker 关闭时清理"""
    pass


async def daily_pubmed_pipeline(ctx):
    """每日 PubMed 管道任务"""
    stats = await pull_daily_oncology()
    return stats if isinstance(stats, dict) else {"status": "ok"}


async def daily_digest_task(ctx):
    """每日摘要邮件任务"""
    from app.services.daily_digest import run_daily_digest
    return await run_daily_digest()


async def daily_citation_update(ctx):
    """每日引用次数更新任务"""
    from app.services.citation_updater import run_citation_update
    return await run_citation_update(cached_hours=24)


async def weekly_broad_pipeline(ctx):
    """每周宽搜补充：Title/Abstract 覆盖 in-process + publisher"""
    stats = await pull_broad_oncology()
    return stats if isinstance(stats, dict) else {"status": "ok"}


async def refresh_hot_articles_cache(ctx):
    """每 30 分钟刷新热搜缓存"""
    from app.services.hot_articles_cache import precompute_hot_articles
    await precompute_hot_articles()


async def refresh_homepage_feed(ctx):
    """每 30 分钟刷新首页 Feed 缓存"""
    from app.services.homepage_feed_cache import precompute_homepage_feed
    await precompute_homepage_feed()


async def daily_mesh_retagger(ctx):
    """每日回查未标引文献（in-process/publisher→medline）"""
    from app.services.mesh_retagger import run_retagger
    stats = await run_retagger(max_articles=2000)
    return stats


async def weekly_drug_approval_sync(ctx):
    """每周同步 FDA 新药审批数据（仅最近 90 天新药）"""
    from app.services.drug_approval_sync import sync_recent_fda_approvals
    stats = await sync_recent_fda_approvals()
    return stats if isinstance(stats, dict) else {"status": "ok"}


async def daily_approval_notification(ctx):
    """每日审批通知推送：用户订阅的靶点有新批药时发邮件"""
    from app.services.approval_notification import run_approval_notification
    return await run_approval_notification()


class WorkerSettings:
    on_startup = startup
    on_shutdown = shutdown
    redis_settings = RedisSettings.from_dsn(settings.REDIS_URL)
    functions = [daily_pubmed_pipeline, daily_digest_task, daily_citation_update, weekly_broad_pipeline, refresh_hot_articles_cache, refresh_homepage_feed, daily_mesh_retagger, weekly_drug_approval_sync, daily_approval_notification]

    # 定时任务（UTC 时间）
    cron_jobs = [
        cron(daily_pubmed_pipeline, hour=3, minute=7),      # 03:07 UTC = 11:07 Beijing
        cron(weekly_broad_pipeline, hour=3, minute=37, weekday='sun'),  # 周日 03:37 UTC = 11:37 Beijing
        cron(daily_digest_task, hour=22, minute=30),        # 22:30 UTC = 06:30 Beijing
        cron(daily_citation_update, hour=5, minute=13),     # 05:13 UTC = 13:13 Beijing
        cron(daily_mesh_retagger, hour=4, minute=47),       # 04:47 UTC = 12:47 Beijing
        cron(weekly_drug_approval_sync, hour=6, minute=23, weekday='mon'),  # 周一 06:23 UTC = 14:23 Beijing 同步FDA审批
        cron(daily_approval_notification, hour=7, minute=47),  # 07:47 UTC = 15:47 Beijing 审批通知推送
        cron(refresh_hot_articles_cache, minute=0),    # 每整点刷新热搜缓存
        cron(refresh_hot_articles_cache, minute=30),   # 每半点刷新热搜缓存
        cron(refresh_homepage_feed, minute=0),         # 每整点刷新首页 Feed
        cron(refresh_homepage_feed, minute=30),        # 每半点刷新首页 Feed
    ]
