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

import yaml
import json
import os
import hashlib
from datetime import datetime

from django.http import HttpResponse, FileResponse
from django.forms.models import model_to_dict
from django.conf import settings

#from .data import get_classes

from .data import Instance

# export JSON / YAML / CSV instances


# --------------------------------------------------------
#  Exporter 
# --------------------------------------------------------


# from cli
def listdict_class_export(classes=None, keyname=None, first=0, last=9999999999):

    datalist = []

    if not classes:
        classes = Schema.listall_names()
        #classes = get_classes()

    for classname in classes:
        
        if keyname:
            instance = Instance.from_keyname(classname=classname, keyname=keyname)
            if instance:
                data = instance.get_dict_for_export()
                datalist.append(data)
        else:
            for instance in Instance.iterate_classname(classname=classname, first=first, last=last):
                data = instance.get_dict_for_export()
                datalist.append(data)


    return datalist


# --------------------------------------------------------
#  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 = getattr(settings, 'CAVALIBA_EXPORT_FOLDER', '/app/files/export/')

    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(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 = getattr(settings, 'CAVALIBA_EXPORT_FOLDER', '/app/files/export/')
    filepath = os.path.join(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 as e:
        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 = getattr(settings, 'CAVALIBA_EXPORT_FOLDER', '/app/files/export/')
    filepath = os.path.join(export_folder, filename)

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

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


