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

// Turn-level governor summary: emitted once per user turn so we can
// diagnose orchestration problems (premature stops, loop cut-offs).
// `stopReason` is the key field — it records WHY the agent loop ended.
export interface TurnSummaryPayload {
  recordType: "turn_summary";
  projectId?: string;
  sessionId?: string;
  userMessage?: string;
  model?: string;
  response?: { text: string; thoughts: string; toolCalls: any[] };
  toolResults?: any[];
  stopReason?: string;
  rounds?: number;
  toolCallCount?: number;
  turnIntent?: string;
  chatMode?: string;
  metrics?: { durationMs: number };
}

function postTelemetry(body: unknown) {
  setTimeout(async () => {
    try {
      const telemetryUrl = process.env.TELEMETRY_SERVICE_URL;
      if (!telemetryUrl) return; // silently skip when unconfigured

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

// Fire and forget: one row per LLM call (training data).
export function logTrainingTelemetryDb(data: TelemetryPayload) {
  postTelemetry(data);
}

// Fire and forget: one row per user turn (orchestration diagnostics).
export function logTurnSummary(data: Omit<TurnSummaryPayload, "recordType">) {
  postTelemetry({ recordType: "turn_summary", ...data });
}
