"""Celery application configuration for background ingest tasks.

Celery 应用配置模块。
定义 Celery 实例及全局配置（序列化格式、时区、任务行为等），
并注册所有任务模块（ingest_task、graph_task）。
"""

from __future__ import annotations

from celery import Celery

from app.config import settings

celery_app = Celery(
    "zm_rag",
    broker=settings.celery_broker_url,
    backend=settings.celery_result_backend,
)

celery_app.conf.update(
    # Serialisation
    task_serializer="json",
    accept_content=["json"],
    result_serializer="json",
    timezone="Asia/Shanghai",
    enable_utc=True,

    # Task behaviour
    task_track_started=True,
    task_acks_late=True,
    worker_prefetch_multiplier=1,

    # 定期回收 worker 子进程，防止长时间运行导致内存泄漏
    worker_max_tasks_per_child=100,

    # 启动时自动重试 broker 连接，避免 broker 短暂不可用导致 worker 启动失败
    broker_connection_retry_on_startup=True,

    # Result expiry (24 h)
    result_expires=86400,

    # Task modules to import.
    imports=[
        "app.tasks.ingest_task",
        "app.tasks.graph_task",
        "app.tasks.research_task",
        "app.tasks.notebook_task",
    ],
)
