# (c) cavaliba.com - data - exporter.py

import hashlib
import os
from datetime import datetime

from django.conf import settings
from django.http import FileResponse

# TODO: refactor



# --------------------------------------------------------
#  list_export_folder - List files in export folder
# --------------------------------------------------------
# 3.24

def list_export_folder():
    """
    List all files in the export folder, sorted by filename.

    Returns:
        list: List of dicts with keys: filename, size (bytes), creation_date (ISO format)
    """
    export_folder = settings.CAVALIBA_EXPORT_FOLDER

    files_list = []

    if not os.path.exists(export_folder):
        return files_list

    for filename in os.listdir(export_folder):
        # Ignore dot files
        if filename.startswith('.'):
            continue

        filepath = os.path.join(str(export_folder), filename)

        # Only include files, not directories
        if os.path.isfile(filepath):
            stat_info = os.stat(filepath)
            creation_date = datetime.fromtimestamp(stat_info.st_ctime).strftime("%Y-%m-%d  %H:%M:%S")

            # Calculate md5sum of filename
            filename_md5 = hashlib.md5(filename.encode()).hexdigest()

            files_list.append({
                'filename': filename,
                'size': stat_info.st_size,
                'creation_date': creation_date,
                'filename_md5': filename_md5
            })

    # Sort by filename
    files_list.sort(key=lambda x: x['filename'])

    return files_list


# --------------------------------------------------------
#  send_file - Send file as response
# --------------------------------------------------------

def send_file(filename):
    """
    Send a file from the export folder as a downloadable response.

    Parameters:
        filename (str): Name of the file to send

    Returns:
        FileResponse: Response object for downloading the file, or None if file not found
    """
    export_folder = settings.CAVALIBA_EXPORT_FOLDER
    filepath = os.path.join(str(export_folder), filename)

    # Verify file exists and is a file (not directory)
    if not os.path.isfile(filepath):
        return None

    try:
        response = FileResponse(open(filepath, 'rb'))
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        return response
    except Exception:
        return None


# --------------------------------------------------------
#  get_file_content - Get raw file content
# --------------------------------------------------------

def get_file_content(filename):
    """
    Read and return the raw content of a file from the export folder.

    Parameters:
        filename (str): Name of the file to read

    Returns:
        str: Raw content of the file, or None if file not found or error reading
    """
    export_folder = settings.CAVALIBA_EXPORT_FOLDER
    filepath = os.path.join(str(export_folder), filename)

    # Verify file exists and is a file (not directory)
    if not os.path.isfile(filepath):
        return None

    try:
        with open(filepath, encoding='utf-8') as f:
            content = f.read()
        if content:
            return content
        return "<empty"
    except Exception:
        return None


