/**
 * Process Registry
 *
 * In-memory registry for tracking managed processes.
 * Provides CRUD operations for process metadata.
 *
 * Note: This is in-memory for now. Phase 2 adds SQLite persistence.
 */

import type { ProcessInfo } from './types.js';

/**
 * Registry for tracking managed processes.
 * Stores process information in memory using a Map.
 */
export class ProcessRegistry {
  private processes: Map<string, ProcessInfo> = new Map();

  /**
   * Register a new process in the registry.
   * @param info - Process information to register
   */
  register(info: ProcessInfo): void {
    this.processes.set(info.id, info);
  }

  /**
   * Remove a process from the registry.
   * @param id - Process ID to unregister
   */
  unregister(id: string): void {
    this.processes.delete(id);
  }

  /**
   * Get a process by its ID.
   * @param id - Process ID to look up
   * @returns Process info if found, undefined otherwise
   */
  get(id: string): ProcessInfo | undefined {
    return this.processes.get(id);
  }

  /**
   * Get all registered processes.
   * @returns Array of all process info objects
   */
  getAll(): ProcessInfo[] {
    return Array.from(this.processes.values());
  }

  /**
   * Find a process by its operating system PID.
   * @param pid - OS process ID to search for
   * @returns Process info if found, undefined otherwise
   */
  getByPid(pid: number): ProcessInfo | undefined {
    for (const process of this.processes.values()) {
      if (process.pid === pid) {
        return process;
      }
    }
    return undefined;
  }

  /**
   * Clear all processes from the registry.
   */
  clear(): void {
    this.processes.clear();
  }

  /**
   * Update a process's status in the registry.
   * @param id - Process ID to update
   * @param status - New status value
   * @returns true if process was found and updated, false otherwise
   */
  updateStatus(id: string, status: ProcessInfo['status']): boolean {
    const process = this.processes.get(id);
    if (process) {
      process.status = status;
      return true;
    }
    return false;
  }

  /**
   * Get the count of registered processes.
   * @returns Number of processes in the registry
   */
  get size(): number {
    return this.processes.size;
  }
}
