/**
 * Fire-and-forget telemetry: sends each model turn to the central
 * telemetry microservice (TELEMETRY_SERVICE_URL) which persists it to
 * Postgres for diagnostics and as fine-tuning training data.
 *
 * Never blocks or throws into the agent loop.
 */

export interface TelemetryPayload {
  projectId?: string;
  model: string;
  systemPrompt: string;
  messages: unknown[];
  response: {
    text: string;
    thoughts: string;
    toolCalls: unknown[];
  };
  metrics: {
    promptTokens?: number;
    completionTokens?: number;
    totalTokens?: number;
    durationMs: number;
  };
}

export function logTrainingTelemetry(data: TelemetryPayload): void {
  setTimeout(async () => {
    try {
      const telemetryUrl = process.env.TELEMETRY_SERVICE_URL;
      if (!telemetryUrl) return; // silently skip when not configured

      await fetch(`${telemetryUrl.replace(/\/$/, "")}/ingest`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
    } catch (error) {
      console.error(
        "[Telemetry] Failed to send training data to microservice:",
        error instanceof Error ? error.message : String(error),
      );
    }
  }, 0);
}
