"""
Abstract worker base class for implementing job processors.

This module provides the Worker abstract base class that defines the interface
for all worker implementations in the Auror framework.
"""

import json
import logging
from abc import ABC, abstractmethod
from typing import Any, Dict

logger = logging.getLogger(__name__)


class Worker(ABC):
    """
    Abstract base class for job processing workers.

    Workers are responsible for processing jobs received from the messaging system.
    Each worker implementation must define how to process jobs specific to their
    inference type (e.g., LTX Video, Stable Diffusion, etc.).

    Subclasses must implement the `process` method to define their specific
    job processing logic.
    """

    def __init__(self):
        """Initialize the worker."""
        pass

    def __call__(self, job_json: str) -> None:
        """
        Process a job received as JSON string.

        This method serves as the entry point when the worker is used as a callback.
        It handles JSON parsing and error handling, then delegates to the `process` method.

        Args:
            job_json: JSON string containing the job data

        Note:
            This method catches all exceptions to prevent worker crashes and logs errors.
        """
        try:
            job = json.loads(job_json)
            job_id = job.get("id", "unknown")

            logger.info(f"[{job_id}] Processing job")
            self.process(job)
            logger.info(f"[{job_id}] Job completed successfully")

        except json.JSONDecodeError as e:
            logger.error(f"Failed to parse job JSON: {e}")
        except Exception as e:
            job_id = "unknown"
            try:
                job = json.loads(job_json)
                job_id = job.get("id", "unknown")
            except:
                pass

            logger.error(f"[{job_id}] Error processing job: {e}", exc_info=True)

    @abstractmethod
    def process(self, job: Dict[str, Any]) -> None:
        """
        Process a job.

        This method must be implemented by subclasses to define the specific
        job processing logic for their inference type.

        Args:
            job: Dictionary containing the job data with at minimum an 'id' field

        Raises:
            NotImplementedError: If not implemented by subclass
        """
        raise NotImplementedError("Subclasses must implement the process() method")
