/**
 * Record OTel metrics for an LLM call made by Decopilot.
 *
 * Uses the same metric names (tool.execution.count / tool.execution.duration)
 * and attribute keys (connection.id / tool.name) as recordToolExecutionMetrics
 * so that the NDJSONMetricExporter stores them under connection_id = "decopilot"
 * and the existing MONITORING_STATS query (filtering by connectionIds) works.
 *
 * Cache tokens are emitted on a separate counter (`tool.execution.cache_tokens`)
 * with attribute `kind` ∈ {"read", "write"} so dashboards can compute
 * cost savings and hit ratios. A counter is only emitted for non-zero kinds.
 */

import type { StudioContext } from "@/core/studio-context";
import { DECOPILOT_CONNECTION_ID } from "./schema";

export function recordLlmCallMetrics(params: {
  ctx: StudioContext;
  organizationId: string;
  modelId: string;
  durationMs: number;
  isError: boolean;
  errorType?: string;
  inputTokens?: number;
  outputTokens?: number;
  cacheReadTokens?: number;
  cacheWriteTokens?: number;
}): void {
  const {
    ctx,
    organizationId,
    modelId,
    durationMs,
    isError,
    inputTokens,
    outputTokens,
    cacheReadTokens,
    cacheWriteTokens,
  } = params;

  if (!organizationId || !modelId) return;

  const attributes = {
    "connection.id": DECOPILOT_CONNECTION_ID,
    "tool.name": modelId,
    "organization.id": organizationId,
    status: isError ? "error" : "success",
    "error.type": isError ? params.errorType || "Error" : "",
  };

  ctx.meter
    .createHistogram("tool.execution.duration", {
      description: "Duration of tool executions in milliseconds",
      unit: "ms",
    })
    .record(durationMs, attributes);

  ctx.meter
    .createCounter("tool.execution.count", {
      description: "Number of tool executions",
    })
    .add(1, attributes);

  if (inputTokens != null || outputTokens != null) {
    ctx.meter
      .createCounter("tool.execution.tokens", {
        description: "Number of tokens used by LLM calls",
      })
      .add((inputTokens ?? 0) + (outputTokens ?? 0), attributes);
  }

  if ((cacheReadTokens ?? 0) > 0) {
    ctx.meter
      .createCounter("tool.execution.cache_tokens", {
        description: "LLM cache tokens by kind (read/write)",
      })
      .add(cacheReadTokens!, { ...attributes, kind: "read" });
  }
  if ((cacheWriteTokens ?? 0) > 0) {
    ctx.meter
      .createCounter("tool.execution.cache_tokens", {
        description: "LLM cache tokens by kind (read/write)",
      })
      .add(cacheWriteTokens!, { ...attributes, kind: "write" });
  }
}
