/**
 * ShardAllocator - Shard allocation for browser runtimes
 *
 * ARCHITECTURAL FIX (Issue #2 from critique):
 * Previous design tried to allocate unique shards per-tab, but:
 * - Each tab has its own allocator (cannot coordinate)
 * - sessionStorage is per-tab, so storage doesn't help
 * - Shard uniqueness requires global coordination we don't have
 *
 * NEW DESIGN: Single-shard model
 * - All browser runtimes use shard "00"
 * - Tab isolation is achieved via tab realm suffix (e.g., flowpad.tab-abc)
 * - Multi-shard scenarios require a coordination service (future work)
 *
 * This is simpler and WORKS, unlike the previous broken approach.
 */

/**
 * Default shard for all browser runtimes.
 * In single-shard model, everyone uses "00".
 */
export const DEFAULT_SHARD = '00';

export class ShardAllocator {
  private _shards: Map<string, string> = new Map();

  /**
   * Allocate a shard for a realm.
   *
   * ARCHITECTURAL FIX: Always returns DEFAULT_SHARD ("00").
   * Tab isolation uses tab realm suffix, not shard differentiation.
   */
  allocate(_root: string): string {
    return DEFAULT_SHARD;
  }

  /**
   * Get the allocated shard for a realm.
   * Always returns DEFAULT_SHARD in single-shard model.
   */
  get(_root: string): string {
    return DEFAULT_SHARD;
  }

  /**
   * Release a shard allocation (no-op in single-shard model).
   */
  release(_root: string): void {
    // No-op: single-shard model doesn't track allocations
  }

  /**
   * Get all allocated shards.
   */
  allocations(): Map<string, string> {
    return new Map(this._shards);
  }
}

// Singleton for browser context
let _globalAllocator: ShardAllocator | null = null;

export function getGlobalShardAllocator(): ShardAllocator {
  if (!_globalAllocator) {
    _globalAllocator = new ShardAllocator();
  }
  return _globalAllocator;
}

/**
 * Get shard for the current runtime.
 *
 * ARCHITECTURAL FIX: Always returns DEFAULT_SHARD ("00").
 * Tab isolation is achieved via tab realm suffix, not shard allocation.
 */
export function allocateShardForTab(_root: string): string {
  return DEFAULT_SHARD;
}
