from __future__ import annotations

from celery import Celery
from kombu import Queue

from core.config.settings import config
from core.logging.celery import configure_celery_app


def create_celery_app() -> Celery:
    """Create and configure the Celery application."""
    celery_settings = config.celery

    app = Celery(
        "social_app",
        broker=config.celery_broker_url,
        backend=config.celery_result_backend,
    )

    app.conf.update(
        task_serializer=celery_settings.task_serializer,
        result_serializer=celery_settings.result_serializer,
        accept_content=celery_settings.accept_content,
        timezone=celery_settings.timezone,
        enable_utc=celery_settings.enable_utc,
        task_track_started=celery_settings.task_track_started,
        task_time_limit=celery_settings.task_time_limit,
        task_soft_time_limit=celery_settings.task_soft_time_limit,
        task_default_retry_delay=celery_settings.task_default_retry_delay,
        task_default_queue="default",
        task_create_missing_queues=False,
        task_queues=(
            Queue("default"),
            Queue("critical"),
            Queue("bulk"),
        ),
        task_routes={
            "tasks.critical.*": {"queue": "critical"},
            "tasks.bulk.*": {"queue": "bulk"},
        },
        task_acks_late=True,
        task_reject_on_worker_lost=True,
        worker_prefetch_multiplier=1,
    )

    configure_celery_app(app, settings=config)

    return app


celery_app = create_celery_app()
