
import os
from ..blender_export import ExportContext, reportWarning
import bpy

from ..utils_debug import debug_err, debug_log, debug_warn
from ..utils import getWebProjectPath
from ..utils_web_project import getAssetsDirectory

def getTargetPath(filepath:str, filename:str, assetsDir:str|None=None):
    # we only try to get the web directory path if we don't have a output directory yet
    # we could potentially do this smarter by checking if the directory contains a needle.config.file to be more flexible
    # but this would again maybe be too much magic/indirection
    if assetsDir is None:
        webProject = getWebProjectPath()
        assetsDir = getAssetsDirectory(webProject)
    if assetsDir is None:
        return None
    if len(filepath) > 0:
        return assetsDir + "/" + os.path.basename(filepath)
    if len(filename) > 0:
        return assetsDir + "/" + filename

def exportAsset(obj:object, exportContext:ExportContext):
    try:
        filepath = getattr(obj, 'filepath', None)
        filepath = bpy.path.abspath(filepath)
        
        # if the export is done via a file dialogue we just want to put all referenced assets next to the currently exported glTf file
        directory = None
        if exportContext.isFileDialogueExport():
            directory = exportContext.getExportDirectory()
        targetpath = getTargetPath(filepath, getattr(obj, 'name', None), directory)
        assetName = os.path.basename(targetpath)

        if not os.path.exists(filepath):   
            if os.path.exists(targetpath):
                return assetName
                     
            if isinstance(obj, bpy.types.Image):
                obj.save_render(targetpath)
                return assetName
            elif isinstance(obj, bpy.types.Sound):
                packed_file = obj.packed_file
                if packed_file and packed_file.data:
                    debug_log("Asset export from packed data → " + assetName)
                    with open(targetpath, 'wb') as f:
                        f.write(packed_file.data)
                    return assetName
            
            reportWarning("Asset export failed because the file does not exist")
            debug_warn("Asset export failed because the file does not exist", filepath)
            return None
        
        if not os.path.exists(targetpath):
            import shutil
            shutil.copyfile(filepath, targetpath)
        else:
            debug_log("Asset already exists, skipping copy", targetpath)
        return assetName
    except Exception as e:
        debug_err("Failed to export asset", filepath, e)
        return None
