"""Functions for exporting objects to external files."""

from pathlib import Path
from typing import Literal

import bpy

from rizomuvbridge_ultimate import constants


def export_to_file(path: Path, format: Literal["OBJ", "FBX", "USD"], apply_modifiers: bool):
    """Export selected objects to a temporary file."""
    if format == "OBJ":
        obj_path = str(Path(path) / constants.OBJ)

        if bpy.app.version >= (3, 3, 0):
            bpy.ops.wm.obj_export(
                filepath=obj_path,
                export_selected_objects=True,
                export_materials=False,
                export_smooth_groups=True,
                apply_modifiers=apply_modifiers,
            )
        else:
            bpy.ops.export_scene.obj(
                filepath=obj_path,
                use_selection=True,
                use_mesh_modifiers=False,
                use_smooth_groups=True,
                use_normals=True,
                use_materials=False,
                apply_modifiers=apply_modifiers,
            )
    elif format == "FBX":
        fbx_path = str(Path(path) / constants.FBX)

        bpy.ops.export_scene.fbx(
            filepath=fbx_path,
            use_selection=True,
            use_visible=False,
            object_types={"MESH"},
            use_mesh_edges=False,
            use_custom_props=False,
            apply_scale_options="FBX_SCALE_NONE",
            bake_space_transform=True,
            apply_unit_scale=True,
            use_mesh_modifiers=apply_modifiers,
        )

    elif format == "USD":
        usd_path = str(Path(path) / constants.USD)
        if bpy.app.version >= (4, 2, 0):
            bpy.ops.wm.usd_export(
                filepath=usd_path,
                check_existing=False,
                selected_objects_only=True,
                export_uvmaps=True,
                export_mesh_colors=True,
                export_normals=True,
                export_materials=True,
                export_textures=False,
                rename_uvmaps=False,
            )
        else:
            bpy.ops.wm.usd_export(
                filepath=usd_path,
                check_existing=False,
                selected_objects_only=True,
                export_uvmaps=True,
                export_mesh_colors=True,
                export_normals=True,
                export_materials=True,
                export_textures=False,
            )
