/**
 * DiagnosticsOrchestratorAgent — optionally opens a live remote diagnostics
 * session for the affected user / install ID based on TelemetryFindings.
 */

import { randomUUID } from 'node:crypto';
import { diagnosticsCreateSession, type DebugSession } from '../../../lib/platform-client.js';
import type { DispatchDecision, TelemetryFindings, DiagnosticsSessionResult } from '../types.js';

export async function orchestrate(
  decision: DispatchDecision,
  findings: TelemetryFindings,
  opts: { token?: string }
): Promise<DiagnosticsSessionResult> {
  const stepId = `step_diag_${randomUUID().slice(0, 8)}`;
  const ctx = { ...findings.runContext, stepId };

  const { brief } = decision;
  const hasTarget = !!(brief.userReport.userId || brief.userReport.anonymousInstallId);

  // Skip if not requested or no target
  if (!brief.openDiagnosticsSession || !hasTarget) {
    return {
      runContext: ctx,
      skipped: true,
      skipReason: brief.openDiagnosticsSession
        ? 'No userId or anonymousInstallId provided — cannot target a diagnostics session'
        : 'openDiagnosticsSession is false — skipping session creation',
    };
  }

  // Choose collection level based on findings severity
  const hasFatal = findings.clusters.some(c => c.severity === 'fatal');
  const collectionLevel = hasFatal ? 'trace' : 'debug';

  try {
    const session: DebugSession = await diagnosticsCreateSession(
      {
        productId: brief.productId,
        targetUserId: brief.userReport.userId,
        targetAnonymousId: brief.userReport.anonymousInstallId,
        collectionLevel,
        captureLogs: true,
        captureNetwork: true,
        maxDurationMinutes: 30,
      },
      { token: opts.token, requestId: findings.runContext.requestId, productId: brief.productId }
    );

    return {
      runContext: ctx,
      skipped: false,
      session: {
        id: session.id,
        status: session.status,
        expiresAt: session.expiresAt,
        collectionLevel: session.collectionLevel ?? collectionLevel,
        targetUserId: brief.userReport.userId,
        targetAnonymousId: brief.userReport.anonymousInstallId,
      },
    };
  } catch (err) {
    return {
      runContext: ctx,
      skipped: false,
      sessionError: err instanceof Error ? err.message : String(err),
    };
  }
}
