const FLASH_IN  = 0.075;   // USD per 1M tokens
const FLASH_OUT = 0.30;

export interface MetricPayload {
  model: string;
  tokens_in?: number;
  tokens_out?: number;
  call_type: string;
  error?: string;
}

export async function reportMetric(payload: MetricPayload): Promise<void> {
  const endpoint = process.env.METRICS_ENDPOINT;
  const botId = process.env.BOT_ID;
  if (!endpoint || !botId) return;

  const cost_usd = ((payload.tokens_in ?? 0) / 1e6) * FLASH_IN
                 + ((payload.tokens_out ?? 0) / 1e6) * FLASH_OUT;

  try {
    await fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        bot_id: botId,
        timestamp: Date.now(),
        model: payload.model,
        tokens_in: payload.tokens_in ?? 0,
        tokens_out: payload.tokens_out ?? 0,
        cost_usd,
        error: payload.error ?? null,
        call_type: payload.call_type,
      }),
      signal: AbortSignal.timeout(2000),
    });
  } catch {
    // best-effort - never break the bot
  }
}
