/**
 * A2A Pipeline Runner — executes the incident pipeline in sequence:
 *   DispatcherAgent → TelemetryAnalystAgent → DiagnosticsOrchestratorAgent → ReportWriterAgent
 *
 * Every step transition is logged with runId + stepId for full audit tracing.
 * Phase 1: handoffs are persisted via structured req.log entries.
 * Phase 2+: handoffs will additionally be written to a Cosmos container.
 */

import { randomUUID } from 'node:crypto';
import type { McpLogger } from '../tools/types.js';
import type { SupportIncidentBrief, FinalIncidentReport } from './types.js';
import { dispatch } from './agents/dispatcher.js';
import { analyze } from './agents/telemetry-analyst.js';
import { orchestrate } from './agents/diagnostics-orchestrator.js';
import { writeReport } from './agents/report-writer.js';

export interface PipelineOptions {
  token?: string;
  requestId?: string;
  initiatedBy?: string;
  log: McpLogger;
}

export async function runIncidentPipeline(
  brief: SupportIncidentBrief,
  opts: PipelineOptions
): Promise<FinalIncidentReport> {
  const runId = `run_${randomUUID()}`;
  const { log } = opts;

  log.info(
    { runId, productId: brief.productId, a2aStep: 'pipeline.start' },
    'A2A pipeline started'
  );

  // ── Step 1: Dispatcher ──────────────────────────────────────────────────
  const decision = dispatch(brief, {
    runId,
    requestId: opts.requestId,
    initiatedBy: opts.initiatedBy,
  });

  log.info(
    {
      runId,
      stepId: decision.runContext.stepId,
      a2aStep: 'dispatcher.complete',
      steps: decision.steps,
      resolvedTimeWindow: decision.resolvedTimeWindow,
    },
    'Dispatcher decided pipeline steps'
  );

  // ── Step 2: Telemetry Analyst ───────────────────────────────────────────
  const findings = await analyze(decision, { token: opts.token });

  log.info(
    {
      runId,
      stepId: findings.runContext.stepId,
      a2aStep: 'telemetry_analyst.complete',
      clusterCount: findings.clusters.length,
      hypothesisCount: findings.topHypotheses.length,
      queryError: findings.queryError,
    },
    'Telemetry analyst completed'
  );

  // ── Step 3: Diagnostics Orchestrator (conditional) ─────────────────────
  let diagResult = null;
  if (decision.steps.includes('diagnostics_orchestrator')) {
    diagResult = await orchestrate(decision, findings, { token: opts.token });

    log.info(
      {
        runId,
        stepId: diagResult.runContext.stepId,
        a2aStep: 'diagnostics_orchestrator.complete',
        skipped: diagResult.skipped,
        sessionId: diagResult.session?.id,
        sessionError: diagResult.sessionError,
      },
      'Diagnostics orchestrator completed'
    );
  }

  // ── Step 4: Report Writer ───────────────────────────────────────────────
  const report = writeReport(decision, findings, diagResult);

  log.info(
    {
      runId,
      a2aStep: 'pipeline.complete',
      productId: brief.productId,
      clusterCount: report.clusterCount,
      hasSession: !!report.diagnosticsSession,
    },
    'A2A pipeline completed'
  );

  return report;
}
