"""
API views for S3 image management
"""
import json
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.views.decorators.csrf import csrf_exempt
from ..services.s3_service import S3Service
import logging

logger = logging.getLogger(__name__)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
@csrf_exempt
def upload_checkin_image(request):
    """
    Upload checkin image to S3
    
    POST /api/upload-checkin-image/
    {
        "event_code": "FC岐阜",
        "team_code": "3432",
        "cp_number": 10,
        "image": <file>
    }
    """
    try:
        # Validate required fields
        event_code = request.data.get('event_code')
        team_code = request.data.get('team_code')
        image_file = request.FILES.get('image')
        cp_number = request.data.get('cp_number')
        
        if not all([event_code, team_code, image_file]):
            return Response({
                'error': 'event_code, team_code, and image are required'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # Initialize S3 service
        s3_service = S3Service()
        
        # Upload image
        s3_url = s3_service.upload_checkin_image(
            image_file=image_file,
            event_code=event_code,
            team_code=team_code,
            cp_number=cp_number
        )
        
        return Response({
            'success': True,
            'image_url': s3_url,
            'message': 'Image uploaded successfully'
        }, status=status.HTTP_201_CREATED)
        
    except Exception as e:
        logger.error(f"Error uploading checkin image: {e}")
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
@csrf_exempt
def upload_standard_image(request):
    """
    Upload standard image (goal, start, etc.) to S3
    
    POST /api/upload-standard-image/
    {
        "event_code": "FC岐阜",
        "image_type": "goal",  # goal, start, checkpoint, etc.
        "image": <file>
    }
    """
    try:
        # Validate required fields
        event_code = request.data.get('event_code')
        image_type = request.data.get('image_type')
        image_file = request.FILES.get('image')
        
        if not all([event_code, image_type, image_file]):
            return Response({
                'error': 'event_code, image_type, and image are required'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # Validate image_type
        valid_types = ['goal', 'start', 'checkpoint', 'finish']
        if image_type not in valid_types:
            return Response({
                'error': f'image_type must be one of: {valid_types}'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # Initialize S3 service
        s3_service = S3Service()
        
        # Upload standard image
        s3_url = s3_service.upload_standard_image(
            image_file=image_file,
            event_code=event_code,
            image_type=image_type
        )
        
        return Response({
            'success': True,
            'image_url': s3_url,
            'message': 'Standard image uploaded successfully'
        }, status=status.HTTP_201_CREATED)
        
    except Exception as e:
        logger.error(f"Error uploading standard image: {e}")
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
def get_standard_image(request):
    """
    Get standard image URL
    
    GET /api/get-standard-image/?event_code=FC岐阜&image_type=goal
    """
    try:
        event_code = request.GET.get('event_code')
        image_type = request.GET.get('image_type')
        
        if not all([event_code, image_type]):
            return Response({
                'error': 'event_code and image_type are required'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # Initialize S3 service
        s3_service = S3Service()
        
        # Get standard image URL
        image_url = s3_service.get_standard_image_url(event_code, image_type)
        
        if image_url:
            return Response({
                'success': True,
                'image_url': image_url
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': False,
                'message': 'Standard image not found',
                'image_url': None
            }, status=status.HTTP_404_NOT_FOUND)
        
    except Exception as e:
        logger.error(f"Error getting standard image: {e}")
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
def list_event_images(request):
    """
    List all images for an event
    
    GET /api/list-event-images/?event_code=FC岐阜&limit=50
    """
    try:
        event_code = request.GET.get('event_code')
        limit = int(request.GET.get('limit', 100))
        
        if not event_code:
            return Response({
                'error': 'event_code is required'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # Initialize S3 service
        s3_service = S3Service()
        
        # List event images
        image_urls = s3_service.list_event_images(event_code, limit)
        
        return Response({
            'success': True,
            'event_code': event_code,
            'image_count': len(image_urls),
            'images': image_urls
        }, status=status.HTTP_200_OK)
        
    except Exception as e:
        logger.error(f"Error listing event images: {e}")
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['DELETE'])
@permission_classes([IsAuthenticated])
@csrf_exempt
def delete_image(request):
    """
    Delete image from S3
    
    DELETE /api/delete-image/
    {
        "image_url": "https://sumasenrogaining.s3.us-west-2.amazonaws.com/FC岐阜/3432/image.jpg"
    }
    """
    try:
        image_url = request.data.get('image_url')
        
        if not image_url:
            return Response({
                'error': 'image_url is required'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        # Initialize S3 service
        s3_service = S3Service()
        
        # Delete image
        success = s3_service.delete_image(image_url)
        
        if success:
            return Response({
                'success': True,
                'message': 'Image deleted successfully'
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': False,
                'message': 'Failed to delete image'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
    except Exception as e:
        logger.error(f"Error deleting image: {e}")
        return Response({
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
