#ifndef EDITSCENE_GOAP_RUNNER_SYSTEM_HPP
#define EDITSCENE_GOAP_RUNNER_SYSTEM_HPP
#pragma once

#include <flecs.h>
#include <Ogre.h>
#include <unordered_set>

// Forward declarations
class SmartObjectSystem;
class BehaviorTreeSystem;
class EditorApp;
class AnimationTreeSystem;
class NavMeshSystem;

/**
 * System that executes GOAP plans from GoapPlannerComponent's plan queue.
 *
 * For each entity with GoapPlannerComponent + GoapRunnerComponent:
 * 1. If no active plan, pop the cheapest plan from planner.planQueue
 * 2. Normal actions: run via BehaviorTreeSystem (using ActionDebug)
 * 3. Smart object actions: pathfind to smart object using NavMeshSystem,
 *    store path in PathFollowingComponent, then execute on arrival
 * 4. Advance to next action when current completes
 * 5. When plan finishes, pop next plan. If queue empty, mark planner dirty.
 */
class GoapRunnerSystem {
public:
	GoapRunnerSystem(flecs::world &world, Ogre::SceneManager *sceneMgr,
			 SmartObjectSystem *soSystem,
			 BehaviorTreeSystem *btSystem,
			 NavMeshSystem *navSystem);
	~GoapRunnerSystem();

	void update(float deltaTime);

	void setAnimationTreeSystem(AnimationTreeSystem *system)
	{
		m_animTreeSystem = system;
	}

	/**
	 * Set the EditorApp for game mode detection.
	 */
	void setEditorApp(EditorApp *app)
	{
		m_editorApp = app;
	}

private:
	bool startNextAction(flecs::entity e);
	flecs::entity findNearestSmartObject(flecs::entity character,
					     const Ogre::String &actionName,
					     float maxDistance);

	flecs::world &m_world;
	Ogre::SceneManager *m_sceneMgr;
	SmartObjectSystem *m_soSystem;
	BehaviorTreeSystem *m_btSystem;
	NavMeshSystem *m_navSystem;
	AnimationTreeSystem *m_animTreeSystem = nullptr;
	EditorApp *m_editorApp = nullptr;

	// Track which entities we set up ActionDebug for
	std::unordered_set<flecs::entity_t> m_managedActionDebugs;
};

#endif // EDITSCENE_GOAP_RUNNER_SYSTEM_HPP
