/**
 * Module Registry — maps component names to module definitions.
 *
 * Used by the import resolution pipeline and ManagedRouter to look up
 * module definitions by their component name (e.g., "HomePage", "ProfilePage").
 */

import type { HypenModuleDefinition } from "./app.js";
import { createLogger } from "./logger.js";

const log = createLogger("ModuleRegistry");

export class ModuleRegistry {
  private definitions = new Map<string, HypenModuleDefinition>();

  /**
   * Register a module definition under a component name.
   */
  register(name: string, definition: HypenModuleDefinition): void {
    if (this.definitions.has(name)) {
      log.warn(`Module "${name}" is already registered. Overwriting.`);
    }
    this.definitions.set(name, definition);
    log.debug(`Registered module definition: ${name}`);
  }

  /**
   * Get a module definition by component name.
   */
  get(name: string): HypenModuleDefinition | undefined {
    return this.definitions.get(name);
  }

  /**
   * Check if a module definition exists.
   */
  has(name: string): boolean {
    return this.definitions.has(name);
  }

  /**
   * Get all registered definitions.
   */
  getAll(): Map<string, HypenModuleDefinition> {
    return new Map(this.definitions);
  }

  /**
   * Get all registered component names.
   */
  getNames(): string[] {
    return Array.from(this.definitions.keys());
  }

  /**
   * Unregister a module definition.
   */
  unregister(name: string): void {
    this.definitions.delete(name);
    log.debug(`Unregistered module definition: ${name}`);
  }

  /**
   * Number of registered definitions.
   */
  get size(): number {
    return this.definitions.size;
  }

  /**
   * Clear all registered definitions.
   */
  clear(): void {
    this.definitions.clear();
  }
}
