/*
 * Priority Forge — blocker derivation
 *
 * Pure function: given the local task store and the local agentId, derive
 * cross-agent BlockerEdges that should be mirrored into the team memory
 * hub as `derived_blocker` events.
 *
 * "Cross-agent" means the blocked task and the blocking task have
 * different owning agents. Same-agent dependencies are local concerns
 * and don't belong in team memory.
 *
 * Today this returns edges for the local agent only — Phase 2 wires it
 * into the subscriber after each task_updated event. The output is
 * deterministic: same input → same edges.
 */

import { BlockerEdge, MinimalTask } from './types';

export type { MinimalTask };

export interface DerivationInput {
  localAgentId: string;
  // Map of taskId → which agent owns/claimed the task. The local store only
  // knows local ownership; cross-forge ownership is learned from team memory
  // events (Phase 2 hydrates this map from the team-activity cache).
  ownership: Map<string, string>;
  tasks: MinimalTask[];
  observedAt?: string;
}

export function deriveBlockerEdges(input: DerivationInput): BlockerEdge[] {
  const observedAt = input.observedAt ?? new Date().toISOString();
  const edges: BlockerEdge[] = [];
  const seen = new Set<string>();

  for (const task of input.tasks) {
    const blockedAgentId = input.ownership.get(task.id) ?? task.claimedBy ?? input.localAgentId;
    const deps = task.dependencies ?? [];
    for (const depId of deps) {
      const blockingAgentId = input.ownership.get(depId);
      if (!blockingAgentId || blockingAgentId === blockedAgentId) continue;
      const key = `${task.id}::${depId}`;
      if (seen.has(key)) continue;
      seen.add(key);
      const blockingStillOpen = !input.tasks.find((t) => t.id === depId && t.status === 'complete');
      edges.push({
        blockedTaskId: task.id,
        blockedAgentId,
        blockingTaskId: depId,
        blockingAgentId,
        status: blockingStillOpen ? 'active' : 'cleared',
        observedAt,
      });
    }
  }

  return edges;
}
