/**
 * DispatcherAgent — validates the SupportIncidentBrief, fills in defaults,
 * and decides which downstream agents to activate.
 */

import { randomUUID } from 'node:crypto';
import type { SupportIncidentBrief, DispatchDecision, RunContext } from '../types.js';

/** Default look-back when no timeWindow provided — 24 hours */
const DEFAULT_LOOKBACK_MS = 24 * 60 * 60 * 1000;

export function dispatch(
  brief: SupportIncidentBrief,
  opts: { runId: string; requestId?: string; initiatedBy?: string }
): DispatchDecision {
  const stepId = `step_dispatch_${randomUUID().slice(0, 8)}`;

  const runContext: RunContext = {
    runId: opts.runId,
    stepId,
    productId: brief.productId,
    requestId: opts.requestId,
    initiatedBy: opts.initiatedBy,
  };

  // Resolve time window — default to last 24 h if not provided
  const now = new Date();
  const resolvedTimeWindow = {
    to: brief.timeWindow.to ?? now.toISOString(),
    from: brief.timeWindow.from ?? new Date(now.getTime() - DEFAULT_LOOKBACK_MS).toISOString(),
  };

  // Decide which agents to run
  const steps: DispatchDecision['steps'] = ['telemetry_analyst'];

  const hasTarget = !!(brief.userReport.userId || brief.userReport.anonymousInstallId);
  if (brief.openDiagnosticsSession && hasTarget) {
    steps.push('diagnostics_orchestrator');
  }

  steps.push('report_writer');

  return { runContext, brief, steps, resolvedTimeWindow };
}
