"""Celery worker application initialization."""

import os
from celery import Celery
from src.core.config import get_config

# Load configuration
config = get_config()

# Get broker and backend URLs
redis_config = config.get("redis", {})
host = redis_config.get("host", "localhost")
port = redis_config.get("port", 6379)
db = redis_config.get("db", 0)
password = redis_config.get("password")

if password:
    auth = f":{password}@"
else:
    auth = ""

broker_url = f"redis://{auth}{host}:{port}/{db}"

# Initialize Celery app
app = Celery(
    "crypto_trader_worker",
    broker=broker_url,
    backend=broker_url,
    include=["src.worker.tasks"]
)

# Configure Celery
app.conf.update(
    task_serializer="json",
    accept_content=["json"],
    result_serializer="json",
    timezone="UTC",
    enable_utc=True,
    task_track_started=True,
    worker_prefetch_multiplier=1,  # Good for long running ML tasks
    task_acks_late=True,  # Ensure task is not lost if worker crashes
)

# Queue routing disabled - all tasks go to default 'celery' queue
# If you want to use separate queues, start workers with: celery -A src.worker.app worker -Q ml_training,celery
# app.conf.task_routes = {
#     "src.worker.tasks.train_model_task": {"queue": "ml_training"},
#     "src.worker.tasks.bootstrap_task": {"queue": "ml_training"},
#     "src.worker.tasks.optimize_strategy_task": {"queue": "ml_training"},
#     "src.worker.tasks.generate_report_task": {"queue": "reporting"},
#     "src.worker.tasks.export_data_task": {"queue": "reporting"},
# }

if __name__ == "__main__":
    app.start()
