/**
 * SkillRegistry.js
 * Loads and manages skill definitions from JSON files.
 * @class
 */
export class SkillRegistry {
  constructor() {
    /** @type {Map<string, Object>} */
    this.skills = new Map();
    /** @type {Promise<void> | null} */
    this.loadPromise = null;
  }

  /**
   * Loads all skill definitions from the assets/skills directory.
   * @returns {Promise<void>}
   */
  async loadAll() {
    // If already loaded, return immediately
    if (this.skills.size > 0) {
      return Promise.resolve();
    }
    
    // If already loading, wait for the existing promise
    if (this.loadPromise) {
      return this.loadPromise;
    }
    
    // Create and cache the load promise
    this.loadPromise = this._doLoadAll().finally(() => {
      // Clear the promise after loading completes (success or failure)
      // so we can retry if needed, but prevent concurrent loads
      this.loadPromise = null;
    });
    
    return this.loadPromise;
  }

  /**
   * Internal method to perform the actual loading.
   * @private
   * @returns {Promise<void>}
   */
  async _doLoadAll() {
    // List of all skill files (could be auto-generated in the future)
    const skillFiles = [
      "skill_breach_move",
      "skill_chain_lightning",
      "skill_deploy_turret",
      "skill_execute",
      "skill_fireball",
      "skill_flashbang",
      "skill_grapple_hook",
      "skill_grenade",
      "skill_ice_wall",
      "skill_intercept",
      "skill_mend",
      "skill_purify",
      "skill_repair_bot",
      "skill_shield_bash",
      "skill_shock_grenade",
      "skill_sprint",
      "skill_stealth",
      "skill_taunt",
      "skill_teleport",
      "skill_ward_corruption",
      "skill_warp_strike",
    ];

    const loadPromises = skillFiles.map(async (filename) => {
      try {
        const response = await fetch(`assets/skills/${filename}.json`);
        if (!response.ok) {
          console.warn(`Failed to load skill: ${filename}`);
          return null;
        }
        const skillData = await response.json();
        this.skills.set(skillData.id, skillData);
        return skillData;
      } catch (error) {
        console.error(`Error loading skill ${filename}:`, error);
        return null;
      }
    });

    await Promise.all(loadPromises);
    console.log(`Loaded ${this.skills.size} skills`);
  }

  /**
   * Gets a skill definition by ID.
   * @param {string} skillId - Skill ID
   * @returns {Object | undefined} - Skill definition
   */
  get(skillId) {
    return this.skills.get(skillId);
  }

  /**
   * Gets all registered skills.
   * @returns {Map<string, Object>} - Map of skill ID to skill definition
   */
  getAll() {
    return this.skills;
  }
}

// Singleton instance
export const skillRegistry = new SkillRegistry();

