"""
Error handler for worker.

Single Responsibility: Handle job processing errors and update status.
"""

import traceback

from .status_updater import StatusUpdater
from .error_enrichment import enrich_error


class ErrorHandler:
    """
    Handle job processing errors.

    Updates DynamoDB with error information and structured error details.
    """

    def __init__(self, status_updater: StatusUpdater):
        """
        Initialize error handler.

        Args:
            status_updater: Status updater for DynamoDB
        """
        self.status_updater = status_updater

    def handle_error(self, job_id: str, error: Exception, stage: str = "unknown") -> None:
        """
        Handle job processing error with structured error enrichment.

        Updates job status to failed with user-friendly error details.
        Re-raises exception to prevent SQS message deletion (enables retry).

        Args:
            job_id: Job identifier
            error: Exception that occurred
            stage: Processing stage where error occurred (e.g., "usage", "metadata")

        Raises:
            Exception: Re-raises the original exception
        """
        # Format simple error message
        error_message = self._format_error_message(error)

        # Enrich error with actionable details
        error_details = enrich_error(stage, error)

        # Update job status to failed with structured details
        try:
            self.status_updater.update_to_failed(
                job_id,
                error_message,
                error_details=error_details
            )
        except Exception as status_error:
            # Log but don't fail if status update fails
            print(f"ERROR: Failed to update job status: {status_error}")

        # Re-raise to prevent SQS message deletion
        raise error

    def _format_error_message(self, error: Exception) -> str:
        """
        Format error message with traceback.

        Args:
            error: Exception to format

        Returns:
            Formatted error message string
        """
        error_type = type(error).__name__
        error_msg = str(error)
        tb = traceback.format_exc()

        return f"{error_type}: {error_msg}\n\nTraceback:\n{tb}"
