#ifndef EDITSCENE_PREFABSYSTEM_HPP
#define EDITSCENE_PREFABSYSTEM_HPP
#pragma once
#include <flecs.h>
#include <Ogre.h>
#include <string>

// Forward declarations
class EditorUISystem;
class SceneSerializer;

/**
 * @brief System for managing prefab instances.
 *
 * Prefabs are reusable entity subtrees stored in external JSON files.
 * Entities with PrefabInstanceComponent are lightweight proxies that
 * reference a prefab file.  Their children are created at runtime and
 * are NOT serialized with the main scene.
 */
class PrefabSystem {
public:
	PrefabSystem(flecs::world &world, Ogre::SceneManager *sceneMgr);

	/**
	 * @brief Instantiate all unloaded prefab instances.
	 *
	 * Should be called once after scene load.
	 */
	void resolveInstances();

	/**
	 * @brief Create a new prefab instance entity and instantiate it.
	 * @param prefabPath Path to the prefab JSON file.
	 * @param parent flecs parent entity (null for root).
	 * @param position World-space position for the instance.
	 * @param name Display name for the instance entity.
	 * @param uiSystem Optional UI system for entity registration.
	 * @return The instance entity.
	 */
	flecs::entity createInstance(const std::string &prefabPath,
				     flecs::entity parent,
				     const Ogre::Vector3 &position,
				     const std::string &name,
				     EditorUISystem *uiSystem = nullptr);

	/**
	 * @brief Save an entity subtree as a prefab file.
	 * @param rootEntity Root of the subtree to save.
	 * @param prefabPath Destination file path.
	 * @return true on success.
	 */
	bool savePrefab(flecs::entity rootEntity,
			const std::string &prefabPath);

	/**
	 * @brief Delete a prefab JSON file.
	 * @param prefabPath Path to the prefab file to delete.
	 * @return true on success.
	 */
	bool deletePrefab(const std::string &prefabPath);

	/**
	 * @brief Get the directory where prefabs are stored.
	 */
	static std::string getPrefabsDirectory();

	/**
	 * @brief Get last error message.
	 */
	const std::string &getLastError() const
	{
		return m_lastError;
	}

private:
	flecs::world &m_world;
	Ogre::SceneManager *m_sceneMgr;
	std::string m_lastError;
};

#endif // EDITSCENE_PREFABSYSTEM_HPP
