content: import os
  from urllib.parse import urlparse, urlunparse
  
  from celery import Celery
  from dotenv import load_dotenv
  
  from app.core.models import *  # noqa #This will import and initialize all models
  from app.modules.utils.logger import configure_logging, setup_logger
  
  # Load environment variables from a .env file if present
  load_dotenv()
  
  # Configure logging
  configure_logging()
  logger = setup_logger(__name__)
  
  # Redis configuration
  redishost = os.getenv("REDISHOST", "localhost")
  redisport = int(os.getenv("REDISPORT", 6379))
  redisuser = os.getenv("REDISUSER", "")
  redispassword = os.getenv("REDISPASSWORD", "")
  queue_name = os.getenv("CELERY_QUEUE_NAME", "staging")
  
  # Construct the Redis URL
  if redisuser and redispassword:
      redis_url = f"redis://{redisuser}:{redispassword}@{redishost}:{redisport}/0"
  else:
      redis_url = f"redis://{redishost}:{redisport}/0"
  
  
  def sanitize_redis_url(url: str) -> str:
      """
      Sanitize Redis URL by masking credentials for safe logging.
      Returns URL with masked credentials (e.g., redis://***:***@host:port/0)
      """
      try:
          parsed = urlparse(url)
          if parsed.username or parsed.password:
              # Mask username and password
              masked_netloc = f"***:***@{parsed.hostname}"
              if parsed.port:
                  masked_netloc += f":{parsed.port}"
              sanitized = urlunparse(
                  (
                      parsed.scheme,
                      masked_netloc,
                      parsed.path,
                      parsed.params,
                      parsed.query,
                      parsed.fragment,
                  )
              )
              return sanitized
          return url
      except Exception:
          # If parsing fails, return a safe fallback
          return "redis://***:***@***:***/0"
  
  
  # Initialize the Celery app
  celery_app = Celery("KnowledgeGraph", broker=redis_url, backend=redis_url)
  
  # Add logging for Redis connection
  logger.info("Connecting to Redis", redis_url=sanitize_redis_url(redis_url))
  try:
      celery_app.backend.client.ping()
      logger.info("Successfully connected to Redis")
  except Exception:
      logger.exception(
          "Failed to connect to Redis", redis_url=sanitize_redis_url(redis_url)
      )
  
  
  def configure_celery(queue_prefix: str):
      celery_app.conf.update(
          task_serializer="json",
          accept_content=["json"],
          result_serializer="json",
          timezone="UTC",
          enable_utc=True,
          # Disable Celery's default logging hijacking so our intercept handler works
          worker_hijack_root_logger=False,
          task_routes={
              "app.celery.tasks.parsing_tasks.process_parsing": {
                  "queue": f"{queue_prefix}_process_repository"
              },
              "app.celery.tasks.agent_tasks.execute_agent_background": {
                  "queue": f"{queue_prefix}_agent_tasks"
              },
              "app.celery.tasks.agent_tasks.execute_regenerate_background": {
                  "queue": f"{queue_prefix}_agent_tasks"  # Same queue as other agent tasks
              },
              # Event bus task routes - both go to the same queue
              "app.modules.event_bus.tasks.event_tasks.process_webhook_event": {
                  "queue": "external-event"
              },
              "app.modules.event_bus.tasks.event_tasks.process_custom_event": {
                  "queue": "external-event"
              },
          },
          # Optimize task distribution
          worker_prefetch_multiplier=1,
          task_acks_late=True,
          task_track_started=True,
          task_time_limit=5400,  # 90 minutes in seconds
          # Add fair task distribution settings
          worker_max_tasks_per_child=200,  # Restart worker after 200 tasks to prevent memory leaks
          worker_max_memory_per_child=2000000,  # Restart worker if using more than 2GB
          task_default_rate_limit="10/m",  # Limit tasks to 10 per minute per worker
          task_reject_on_worker_lost=True,  # Requeue tasks if worker dies
          broker_transport_options={
              "visibility_timeout": 5400
          },  # 45 minutes visibility timeout
      )
  
  
  configure_celery(queue_name)
  
  
  def setup_phoenix_tracing():
      """Initialize Phoenix tracing for LLM monitoring in Celery workers."""
      try:
          from app.modules.intelligence.tracing.phoenix_tracer import (
              initialize_phoenix_tracing,
          )
  
          initialize_phoenix_tracing()
      except Exception as e:
          logger.warning(
              "Phoenix tracing initialization failed in Celery worker (non-fatal)",
              error=str(e),
          )
  
  
  setup_phoenix_tracing()
  
  # Import the lock decorator
  from celery.contrib.abortable import AbortableTask  # noqa
  
  # Import tasks to ensure they are registered
  import app.celery.tasks.parsing_tasks  # noqa # Ensure the task module is imported
  import app.celery.tasks.agent_tasks  # noqa # Ensure the agent task module is imported
  import app.modules.event_bus.tasks.event_tasks  # noqa # Ensure event bus tasks are registered
  