import logging
import os
from datetime import datetime
from pathlib import Path

from common.status import HTTP_404_NOT_FOUND, HTTP_200_OK
from flask import Blueprint
from flask_jwt_extended import jwt_required

reporting_blueprint = Blueprint('reporting', __name__)

logger = logging.getLogger('median')


@reporting_blueprint.route('', methods=['GET'])
@jwt_required()
def get_all():
    """
    Retrieve the liste of the PDF file, group by date
    """
    cr_folder = os.environ.get('REPORTING_FOLDER', '.')
    try:
        result = []
        p = Path(cr_folder)
        if not p.exists():
            return {
                'message': 'Folder does not exists!',
                'folder': cr_folder,
            }, HTTP_404_NOT_FOUND

        nb_files = 0
        files = __get_files(('*.csv', '*.pdf', '*.xls', '*.xlsx', '*.odt', '*.ods', '*.doc', '*.docx'),
                            cr_folder)

        for f in files:
            try:
                dtf = datetime.fromtimestamp(os.path.getmtime(f)).strftime('%Y-%m-%d')
                file_stats = os.stat(f)
                result.append({
                    'date': dtf,
                    'extension': Path(f.name).suffix,
                    'name': f.name,
                    'size': file_stats.st_size,
                    'file': '/download/%s' % f.name,
                    'timestamp': os.path.getmtime(f)
                })
                nb_files += 1
            except (OSError, ValueError) as e:
                logger.error(f"Error processing file {f}: {str(e)}")
                continue

        return result, HTTP_200_OK

    except Exception as e:
        logger.error(f"Unexpected error in get_all: {str(e)}")
        return {
            'message': 'Internal server error',
            'error': str(e)
        }, 500


def __get_files(extensions, folder):
    all_files = []
    for ext in extensions:
        all_files.extend(Path(folder).glob(ext))
    return all_files
