/**
 * Persistent per-tactic XP pools for heroes.
 * XP accumulates only on the active path; switching tactics restores that path's pool.
 * Keys: eco, att, def, building, research, base.
 */

function HeroPathXp() {}

HeroPathXp.prototype.Schema = "<empty/>";

/** Known tactic suffixes; longer names first so "building" wins over shorter tokens. */
const HERO_PATH_SUFFIXES = ["building", "research", "eco", "att", "def"];

/**
 * @param {string} templateName - Full or basename template (e.g. units/cart/hero_maharbal_a_eco).
 * @returns {string} Path id.
 */
function GetHeroPathFromTemplateName(templateName)
{
	if (!templateName)
		return "base";

	const name = templateName.includes("/") ?
		templateName.substring(templateName.lastIndexOf("/") + 1) :
		templateName;

	for (const path of HERO_PATH_SUFFIXES)
		if (name.endsWith("_" + path))
			return path;

	return "base";
}

HeroPathXp.prototype.Init = function()
{
	this.pathXp = {};
};

/**
 * @returns {string} Active path derived from this entity's current template.
 */
HeroPathXp.prototype.GetActivePath = function()
{
	const cmpTemplateManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_TemplateManager);
	return GetHeroPathFromTemplateName(cmpTemplateManager.GetCurrentTemplateName(this.entity));
};

/**
 * @returns {Object} Shallow copy of path → XP map.
 */
HeroPathXp.prototype.GetPathStore = function()
{
	return clone(this.pathXp);
};

/**
 * @param {Object} store - path → XP map to adopt.
 */
HeroPathXp.prototype.SetPathStore = function(store)
{
	this.pathXp = store ? clone(store) : {};
};

/**
 * @param {string} path
 * @returns {number} Stored XP for path, or 0.
 */
HeroPathXp.prototype.GetPathXp = function(path)
{
	return this.pathXp[path] || 0;
};

/**
 * @param {string} path
 * @param {number} xp
 */
HeroPathXp.prototype.SetPathXp = function(path, xp)
{
	this.pathXp[path] = +xp;
};

/**
 * Write live Promotion XP into the store under the active path.
 */
HeroPathXp.prototype.SaveCurrentPathXp = function()
{
	const cmpPromotion = Engine.QueryInterface(this.entity, IID_Promotion);
	if (!cmpPromotion)
		return;

	this.SetPathXp(this.GetActivePath(), cmpPromotion.GetCurrentXp());
};

Engine.RegisterGlobal("GetHeroPathFromTemplateName", GetHeroPathFromTemplateName);
Engine.RegisterComponentType(IID_HeroPathXp, "HeroPathXp", HeroPathXp);
