import { networkInterfaces, userInfo, hostname } from 'node:os';
import { PostHog } from 'posthog-node';
import { execSync } from 'node:child_process';
import { inspect } from 'node:util';

// src/platform/analytics/posthog.ts
function runGitCommand(rootDir, command) {
  return execSync(command, {
    cwd: rootDir,
    encoding: "utf8",
    maxBuffer: 1024 * 1024 * 20,
    stdio: ["ignore", "pipe", "pipe"]
  }).trim();
}
function isGitRepository(rootDir) {
  try {
    runGitCommand(rootDir, "git rev-parse --show-toplevel");
    return true;
  } catch {
    return false;
  }
}
function stringifyUnknown(value) {
  if (value === void 0 || value === null) {
    return "";
  }
  if (typeof value === "string") {
    return value;
  }
  if (Buffer.isBuffer(value)) {
    return value.toString("utf8");
  }
  if (value instanceof Error) {
    return value.stack || value.message;
  }
  return inspect(value, { depth: 6, breakLength: 120 });
}
function getErrorSummary(error) {
  if (error instanceof Error) {
    return `${error.name}: ${error.message}`;
  }
  return stringifyUnknown(error) || "Unknown error";
}

// src/platform/analytics/posthog.ts
var POSTHOG_API_KEY = "phc_MX929Nca94SLcOo7b5Mdvhv9KQi7lSESFNKRhAJRKi9";
var POSTHOG_HOST = "https://us.i.posthog.com";
var POSTHOG_SHUTDOWN_TIMEOUT_MS = 5e3;
var telemetryRuntimeState = globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ ?? (globalThis.__JU_HONG_E_POSTHOG_RUNTIME_STATE__ = {});
function getPostHogClient() {
  if (!telemetryRuntimeState.posthogClient) {
    telemetryRuntimeState.posthogClient = new PostHog(POSTHOG_API_KEY, {
      host: POSTHOG_HOST
    });
  }
  return telemetryRuntimeState.posthogClient;
}
function readGitConfigValue(rootDir, configKey) {
  if (!isGitRepository(rootDir)) {
    return null;
  }
  try {
    return runGitCommand(rootDir, `git config --get ${configKey}`) || null;
  } catch {
    return null;
  }
}
function resolveDistinctId(gitUserName, gitUserEmail) {
  if (gitUserEmail) {
    return `git-email:${gitUserEmail}`;
  }
  if (gitUserName) {
    return `git-name:${gitUserName}`;
  }
  try {
    const currentUser = userInfo();
    return `os-user:${currentUser.username}@${hostname()}`;
  } catch {
    return `host:${hostname()}`;
  }
}
function resolveGitTelemetryMetadata(rootDir) {
  const gitUserName = readGitConfigValue(rootDir, "user.name");
  const gitUserEmail = readGitConfigValue(rootDir, "user.email");
  return {
    distinctId: resolveDistinctId(gitUserName, gitUserEmail),
    gitUserEmail,
    gitUserName
  };
}
function resolveUserIpAddressValue() {
  const ipAddresses = /* @__PURE__ */ new Set();
  Object.values(networkInterfaces()).forEach((records) => {
    records?.forEach((record) => {
      if (!record || record.internal) {
        return;
      }
      ipAddresses.add(record.address);
    });
  });
  return [...ipAddresses].join(", ");
}
function buildCommandParameterProperties(args) {
  const parameterProperties = {};
  if (args.length === 0) {
    parameterProperties["\uBA85\uB839\uC5B4\uC5D0\uC0AC\uC6A9\uB41C\uD30C\uB77C\uBBF8\uD1301"] = null;
    return parameterProperties;
  }
  args.forEach((arg, index) => {
    parameterProperties[`\uBA85\uB839\uC5B4\uC5D0\uC0AC\uC6A9\uB41C\uD30C\uB77C\uBBF8\uD130${index + 1}`] = arg;
  });
  return parameterProperties;
}
function beginSlashCommandTelemetryInputCollection(initialArgs) {
  telemetryRuntimeState.slashCommandTelemetryInputValues = [...initialArgs];
}
function appendSlashCommandTelemetryInputValue(value) {
  if (!telemetryRuntimeState.slashCommandTelemetryInputValues) {
    return;
  }
  telemetryRuntimeState.slashCommandTelemetryInputValues.push(...normalizeSlashCommandTelemetryValues(value));
}
function endSlashCommandTelemetryInputCollection() {
  const values = [...telemetryRuntimeState.slashCommandTelemetryInputValues || []];
  telemetryRuntimeState.slashCommandTelemetryInputValues = void 0;
  return values;
}
function normalizeSlashCommandTelemetryValues(value) {
  if (value === void 0) {
    return [];
  }
  if (value === null) {
    return [null];
  }
  if (Array.isArray(value)) {
    return value.flatMap((item) => normalizeSlashCommandTelemetryValues(item));
  }
  if (typeof value === "string") {
    return [value];
  }
  if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
    return [String(value)];
  }
  if (typeof value === "object") {
    const objectValue = value;
    if (typeof objectValue.url === "string" && objectValue.url) {
      return [objectValue.url];
    }
    if (typeof objectValue.hash === "string" && objectValue.hash) {
      return [objectValue.hash];
    }
    if (typeof objectValue.name === "string" && objectValue.name) {
      return [objectValue.name];
    }
    if (typeof objectValue.label === "string" && objectValue.label) {
      return [objectValue.label];
    }
    try {
      return [JSON.stringify(objectValue)];
    } catch {
      return ["[object]"];
    }
  }
  return [String(value)];
}
function trackSlashCommandExecution(options) {
  try {
    const gitMetadata = resolveGitTelemetryMetadata(options.rootDir);
    getPostHogClient().capture({
      distinctId: gitMetadata.distinctId,
      event: options.command,
      properties: {
        "userinfo-git-user-email": gitMetadata.gitUserEmail,
        "userinfo-git-user-name": gitMetadata.gitUserName,
        "userinfo-ip": resolveUserIpAddressValue(),
        "command-kind": options.kind,
        "command-service": options.service,
        "command-status": options.status,
        ...buildCommandParameterProperties(options.args)
      }
    });
    options.trace?.("posthog:slash-command:capture", `${options.command} status=${options.status}`);
  } catch (error) {
    options.trace?.("posthog:slash-command:skip", getErrorSummary(error));
  }
}
async function shutdownPostHogClient() {
  if (!telemetryRuntimeState.posthogClient) {
    return;
  }
  if (!telemetryRuntimeState.shutdownPromise) {
    const client = telemetryRuntimeState.posthogClient;
    telemetryRuntimeState.shutdownPromise = Promise.resolve(client.shutdown(POSTHOG_SHUTDOWN_TIMEOUT_MS)).catch(() => void 0).finally(() => {
      telemetryRuntimeState.posthogClient = void 0;
      telemetryRuntimeState.shutdownPromise = void 0;
    });
  }
  await telemetryRuntimeState.shutdownPromise;
}

export { appendSlashCommandTelemetryInputValue, beginSlashCommandTelemetryInputCollection, endSlashCommandTelemetryInputCollection, shutdownPostHogClient, trackSlashCommandExecution };
