#ifndef EDITSCENE_FORMULA_HPP
#define EDITSCENE_FORMULA_HPP
#pragma once

#include <Ogre.h>
#include <string>
#include <unordered_map>

/**
 * Lightweight expression evaluator for RPG formulas.
 *
 * Supports:
 *   Variables: level, current, base, value
 *   Operators: +, -, *, /, ^, ()
 *   Functions: floor(x), ceil(x), min(a,b), max(a,b), clamp(x,lo,hi)
 *
 * Example: "level * level * 100 + floor(current / 10)"
 */
class Formula {
public:
	Formula() = default;
	explicit Formula(const Ogre::String &expr);

	bool isValid() const { return m_valid; }
	const Ogre::String &getExpression() const { return m_expression; }

	/**
	 * Evaluate the formula with given variable bindings.
	 *
	 * @param vars  Map of variable names to values.
	 * @return The computed result. Returns 0.0 if formula is invalid.
	 */
	double evaluate(const std::unordered_map<std::string, double> &vars) const;

	/**
	 * Convenience: evaluate with just a level.
	 */
	double evaluate(int level) const;

	/**
	 * Convenience: evaluate with level and current value.
	 */
	double evaluate(int level, double current) const;

private:
	Ogre::String m_expression;
	bool m_valid = false;

	// Recursive descent parser
	struct Parser {
		const char *s;
		const std::unordered_map<std::string, double> *vars;

		double parseExpression();
		double parseTerm();
		double parsePower();
		double parseUnary();
		double parsePrimary();

		void skipWhitespace();
		bool consume(char c);
	};
};

#endif // EDITSCENE_FORMULA_HPP
