"""
Utility helper functions
"""

from flask import current_app, make_response, jsonify
from app.models.database import PetPicture


def allowed_file(filename):
    """Check if file extension is allowed"""
    return ('.' in filename and 
            filename.rsplit('.', 1)[1].lower() in current_app.config['ALLOWED_EXTENSIONS'])


def get_liked_pictures_from_cookie(request):
    """Extract liked picture IDs from cookie"""
    liked_pictures = request.cookies.get('liked_pictures', '')
    return liked_pictures.split(',') if liked_pictures else []


def add_liked_status_to_pictures(pictures, liked_list):
    """Add user_liked status to picture records"""
    pictures_with_likes = []
    for picture in pictures:
        picture_dict = dict(picture)
        picture_dict['user_liked'] = str(picture['id']) in liked_list
        pictures_with_likes.append(picture_dict)
    return pictures_with_likes


def handle_like_action(picture_id, request):
    """Handle like/unlike action and return JSON response"""
    # Get existing likes from cookie
    liked_list = get_liked_pictures_from_cookie(request)
    picture_id_str = str(picture_id)
    
    if picture_id_str in liked_list:
        # Unlike: remove from cookie and decrement count
        liked_list.remove(picture_id_str)
        PetPicture.update_likes(picture_id, increment=False)
        liked = False
    else:
        # Like: add to cookie and increment count
        liked_list.append(picture_id_str)
        PetPicture.update_likes(picture_id, increment=True)
        liked = True
    
    # Get updated like count
    like_count = PetPicture.get_like_count(picture_id)
    
    # Create response with updated cookie
    response = make_response(jsonify({
        'liked': liked,
        'like_count': like_count
    }))
    
    # Update cookie (expires in 1 year)
    response.set_cookie('liked_pictures', ','.join(liked_list), max_age=365*24*60*60)
    
    return response