"""SQS queue service for retry mechanism."""

import boto3
import json
import logging
from datetime import datetime
from typing import Optional, List, Dict, Any
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


class RetryQueueManager:
    """SQS queue manager for payment retry mechanism."""
    
    def __init__(self, queue_url: str, region: str = "us-east-1"):
        self.queue_url = queue_url
        self.region = region
        self.sqs_client = boto3.client("sqs", region_name=region)
        logger.info(f"RetryQueueManager initialized with queue: {queue_url}")
    
    def send_retry_message(self, payment_data: dict, retry_count: int = 0) -> bool:
        """Send payment data to retry queue."""
        try:
            message_body = {
                "payment_data": payment_data,
                "retry_count": retry_count,
                "timestamp": str(datetime.utcnow())
            }
            
            response = self.sqs_client.send_message(
                QueueUrl=self.queue_url,
                MessageBody=json.dumps(message_body),
                DelaySeconds=min(retry_count * 30, 900)  # Exponential backoff, max 15 min
            )
            
            logger.info(f"Retry message sent for transaction: {payment_data.get('transaction_id')}")
            return True
        except ClientError as e:
            logger.error(f"SQS send message failed: {e}")
            return False
    
    def receive_retry_messages(self, max_messages: int = 10) -> List[Dict[str, Any]]:
        """Receive messages from retry queue."""
        try:
            response = self.sqs_client.receive_message(
                QueueUrl=self.queue_url,
                MaxNumberOfMessages=max_messages,
                WaitTimeSeconds=20,  # Long polling
                MessageAttributeNames=['All']
            )
            
            messages = response.get('Messages', [])
            logger.info(f"Received {len(messages)} retry messages")
            return messages
        except ClientError as e:
            logger.error(f"SQS receive message failed: {e}")
            return []
    
    def delete_message(self, receipt_handle: str) -> bool:
        """Delete processed message from queue."""
        try:
            self.sqs_client.delete_message(
                QueueUrl=self.queue_url,
                ReceiptHandle=receipt_handle
            )
            logger.info("Retry message deleted from queue")
            return True
        except ClientError as e:
            logger.error(f"SQS delete message failed: {e}")
            return False
    
    def get_queue_attributes(self) -> Optional[Dict[str, str]]:
        """Get queue attributes for monitoring."""
        try:
            response = self.sqs_client.get_queue_attributes(
                QueueUrl=self.queue_url,
                AttributeNames=['All']
            )
            return response.get('Attributes', {})
        except ClientError as e:
            logger.error(f"SQS get attributes failed: {e}")
            return None
