"""Secrets Manager service for API keys."""

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

logger = logging.getLogger(__name__)


class SecretFetcher:
    """Secrets Manager service for retrieving API keys."""
    
    def __init__(self, region: str = "us-east-1"):
        self.region = region
        self.secrets_client = boto3.client("secretsmanager", region_name=region)
        logger.info("SecretFetcher initialized")
    
    def get_secret(self, secret_name: str) -> Optional[str]:
        """Retrieve secret value from Secrets Manager."""
        try:
            response = self.secrets_client.get_secret_value(SecretId=secret_name)
            
            if 'SecretString' in response:
                secret = response['SecretString']
                logger.info(f"Secret retrieved: {secret_name}")
                return secret
            else:
                logger.error(f"Secret {secret_name} is not a string")
                return None
                
        except ClientError as e:
            error_code = e.response['Error']['Code']
            if error_code == 'ResourceNotFoundException':
                logger.error(f"Secret not found: {secret_name}")
            elif error_code == 'InvalidRequestException':
                logger.error(f"Invalid request for secret: {secret_name}")
            elif error_code == 'InvalidParameterException':
                logger.error(f"Invalid parameter for secret: {secret_name}")
            else:
                logger.error(f"Error retrieving secret {secret_name}: {e}")
            return None
    
    def get_secret_dict(self, secret_name: str) -> Optional[Dict[str, Any]]:
        """Retrieve secret as dictionary (for JSON secrets)."""
        secret_string = self.get_secret(secret_name)
        if secret_string:
            try:
                return json.loads(secret_string)
            except json.JSONDecodeError:
                logger.error(f"Secret {secret_name} is not valid JSON")
                return None
        return None
    
    def get_api_key(self, secret_name: str) -> Optional[str]:
        """Retrieve API key from secret (expects JSON with 'api_key' field)."""
        secret_dict = self.get_secret_dict(secret_name)
        if secret_dict and 'api_key' in secret_dict:
            logger.info(f"API key retrieved from secret: {secret_name}")
            return secret_dict['api_key']
        else:
            logger.error(f"API key not found in secret: {secret_name}")
            return None
