"""RQ worker entrypoint for PunimTag."""

from __future__ import annotations

import signal
import sys
from typing import NoReturn

import uuid

from rq import Worker
from redis import Redis

from src.web.services.tasks import import_photos_task, process_faces_task

# Redis connection for RQ
redis_conn = Redis(host="localhost", port=6379, db=0, decode_responses=False)


def main() -> NoReturn:
    """Worker entrypoint - starts RQ worker to process background jobs."""
    def _handle_sigterm(_signum, _frame):
        sys.exit(0)

    signal.signal(signal.SIGTERM, _handle_sigterm)
    signal.signal(signal.SIGINT, _handle_sigterm)

    # Generate unique worker name to avoid conflicts
    worker_name = f"punimtag-worker-{uuid.uuid4().hex[:8]}"
    
    print(f"[Worker] Starting worker: {worker_name}")
    print(f"[Worker] Listening on queue: default")
    
    # Check if Redis is accessible
    try:
        redis_conn.ping()
        print(f"[Worker] Redis connection successful")
    except Exception as e:
        print(f"[Worker] ❌ Redis connection failed: {e}")
        sys.exit(1)
    
    # Register tasks with worker
    # Tasks are imported from services.tasks
    worker = Worker(
        ["default"],
        connection=redis_conn,
        name=worker_name,
    )
    
    print(f"[Worker] ✅ Worker ready, waiting for jobs...")

    # Start worker
    worker.work()


if __name__ == "__main__":
    main()


