#!/usr/bin/env node
import {
  CONFIG_DIR_NAME
} from "./chunk-KRU4DFRH.js";

// src/diagnostics/tool-stats.ts
import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync } from "fs";
import { join, dirname } from "path";
import { homedir } from "os";
var STATS_FILE_NAME = "tool-stats.json";
var STATS_VERSION = 1;
var FLUSH_EVERY_N = 50;
var state = null;
var dirty = false;
var pendingWrites = 0;
var configDirOverride;
function statsFilePath() {
  const base = configDirOverride ?? join(homedir(), CONFIG_DIR_NAME);
  return join(base, STATS_FILE_NAME);
}
function load() {
  const path = statsFilePath();
  if (!existsSync(path)) {
    return { version: STATS_VERSION, startedAt: (/* @__PURE__ */ new Date()).toISOString(), entries: {} };
  }
  try {
    const raw = JSON.parse(readFileSync(path, "utf-8"));
    if (raw.version !== STATS_VERSION || !raw.entries) {
      return { version: STATS_VERSION, startedAt: (/* @__PURE__ */ new Date()).toISOString(), entries: {} };
    }
    return raw;
  } catch {
    return { version: STATS_VERSION, startedAt: (/* @__PURE__ */ new Date()).toISOString(), entries: {} };
  }
}
function ensureLoaded() {
  if (state === null) state = load();
  return state;
}
function recordToolCall(name, durationMs, ok, errorMessage) {
  const s = ensureLoaded();
  const now = (/* @__PURE__ */ new Date()).toISOString();
  let entry = s.entries[name];
  if (!entry) {
    entry = {
      name,
      calls: 0,
      failures: 0,
      totalDurationMs: 0,
      firstSeenAt: now,
      lastUsedAt: now
    };
    s.entries[name] = entry;
  }
  entry.calls += 1;
  entry.totalDurationMs += Math.max(0, Math.round(durationMs));
  entry.lastUsedAt = now;
  if (!ok) {
    entry.failures += 1;
    entry.lastFailureAt = now;
    if (errorMessage) entry.lastFailureMessage = errorMessage.slice(0, 300);
  }
  dirty = true;
  pendingWrites += 1;
  if (pendingWrites >= FLUSH_EVERY_N) {
    flush();
  }
}
async function runTool(tool, args, name) {
  const start = Date.now();
  try {
    const result = await tool.execute(args);
    recordToolCall(name, Date.now() - start, true);
    return result;
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    recordToolCall(name, Date.now() - start, false, msg);
    throw err;
  }
}
function flush() {
  if (!dirty || state === null) return;
  const path = statsFilePath();
  try {
    mkdirSync(dirname(path), { recursive: true });
    const tmp = path + ".tmp";
    writeFileSync(tmp, JSON.stringify(state, null, 2), "utf-8");
    renameSync(tmp, path);
    dirty = false;
    pendingWrites = 0;
  } catch {
  }
}
function getStatsSnapshot() {
  const s = ensureLoaded();
  return Object.values(s.entries).map((e) => ({ ...e }));
}
function getTopFailingTools(limit = 5) {
  return getStatsSnapshot().filter((e) => e.failures > 0).sort((a, b) => {
    const rateA = a.failures / Math.max(1, a.calls);
    const rateB = b.failures / Math.max(1, b.calls);
    if (rateB !== rateA) return rateB - rateA;
    return b.failures - a.failures;
  }).slice(0, limit);
}
function getTopUsedTools(limit = 5) {
  return getStatsSnapshot().sort((a, b) => b.calls - a.calls).slice(0, limit);
}
function resetStats() {
  state = { version: STATS_VERSION, startedAt: (/* @__PURE__ */ new Date()).toISOString(), entries: {} };
  dirty = true;
  flush();
}
var exitHookInstalled = false;
function installFlushOnExit() {
  if (exitHookInstalled) return;
  exitHookInstalled = true;
  process.on("exit", () => flush());
}

export {
  runTool,
  getStatsSnapshot,
  getTopFailingTools,
  getTopUsedTools,
  resetStats,
  installFlushOnExit
};
