import { StatsD } from "hot-shots";
import type { Logger } from "pino";
import type { Metrics, MetricTags } from "./types.js";

const PREFIX = "hu_agent.";

export class DatadogMetrics implements Metrics {
  private readonly client: StatsD;

  constructor(host: string, port: number, env: string, provider: string, logger: Logger) {
    this.client = new StatsD({
      host,
      port,
      prefix: PREFIX,
      // `provider` tags every metric with the active agent backend (cursor | claude)
      // so dashboards can be segmented during/after the provider migration.
      globalTags: { env, service: "hu-agent", provider },
      errorHandler: (err) => logger.warn({ error: err.message }, "metrics_emit_failed"),
    });
  }

  increment(name: string, tags?: MetricTags): void {
    this.client.increment(name, this.toTags(tags));
  }
  count(name: string, value: number, tags?: MetricTags): void {
    this.client.increment(name, value, this.toTags(tags));
  }
  gauge(name: string, value: number, tags?: MetricTags): void {
    this.client.gauge(name, value, this.toTags(tags));
  }
  histogram(name: string, value: number, tags?: MetricTags): void {
    this.client.histogram(name, value, this.toTags(tags));
  }
  timing(name: string, ms: number, tags?: MetricTags): void {
    this.client.timing(name, ms, this.toTags(tags));
  }

  private toTags(tags?: MetricTags): string[] {
    if (!tags) return [];
    return Object.entries(tags).map(([k, v]) => `${k}:${v}`);
  }
}
