"""Slides API for TV dashboard slideshow."""

import os
from flask import Blueprint, current_app
from shopdb.utils.responses import success_response, error_response, ErrorCodes

slides_bp = Blueprint('slides', __name__)

# Valid image extensions
VALID_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp'}


@slides_bp.route('', methods=['GET'])
def get_slides():
    """
    Get list of slides for TV dashboard.

    Returns image files from the static/slides directory.
    """
    # Look for slides in static folder
    static_folder = current_app.static_folder
    if not static_folder:
        static_folder = os.path.join(current_app.root_path, 'static')

    slides_folder = os.path.join(static_folder, 'slides')

    # Also check frontend public folder
    frontend_slides = os.path.join(
        os.path.dirname(os.path.dirname(os.path.dirname(current_app.root_path))),
        'frontend', 'public', 'slides'
    )

    # Try multiple possible locations
    possible_paths = [
        slides_folder,
        frontend_slides,
        '/home/camp/projects/shopdb-flask/shopdb/static/slides',
        '/home/camp/projects/shopdb-flask/frontend/public/slides',
    ]

    slides_path = None
    for path in possible_paths:
        if os.path.isdir(path):
            slides_path = path
            break

    if not slides_path:
        return success_response({
            'slides': [],
            'basepath': '/static/slides/',
            'message': 'Slides folder not found'
        })

    # Get list of image files
    slides = []
    try:
        for filename in sorted(os.listdir(slides_path)):
            ext = os.path.splitext(filename)[1].lower()
            if ext in VALID_EXTENSIONS:
                slides.append({'filename': filename})
    except Exception as e:
        return error_response(
            ErrorCodes.SERVER_ERROR,
            f'Error reading slides: {str(e)}',
            http_code=500
        )

    # Determine base path for serving files
    basepath = '/static/slides/'

    return success_response({
        'slides': slides,
        'basepath': basepath
    })
