import {
  resolveHomeDir
} from "./chunk-MARWOCVP.js";

// src/tokens.ts
import fs from "fs";
import path from "path";
import { randomBytes } from "crypto";
var TOKEN_PREFIXES = {
  "openclaw": "remnic_oc_",
  "claude-code": "remnic_cc_",
  "codex-cli": "remnic_cx_",
  "codex": "remnic_cx_",
  "hermes": "remnic_hm_",
  "replit": "remnic_rl_",
  "cursor": "remnic_cu_",
  "cline": "remnic_cl_",
  "github-copilot": "remnic_gh_",
  "roo-code": "remnic_rc_",
  "windsurf": "remnic_ws_",
  "amp": "remnic_am_",
  "generic-mcp": "remnic_gm_"
};
function defaultTokensPath() {
  return path.join(resolveHomeDir(), ".remnic", "tokens.json");
}
function legacyTokensPath() {
  return path.join(resolveHomeDir(), ".engram", "tokens.json");
}
function resolveReadPath(tokensPath) {
  const primary = tokensPath ?? defaultTokensPath();
  if (tokensPath) return primary;
  if (fs.existsSync(primary)) return primary;
  const legacy = legacyTokensPath();
  return fs.existsSync(legacy) ? legacy : primary;
}
function ensureDir(filePath) {
  const dir = path.dirname(filePath);
  fs.mkdirSync(dir, { recursive: true });
}
function loadTokenStore(tokensPath) {
  const p = resolveReadPath(tokensPath);
  try {
    const raw = JSON.parse(fs.readFileSync(p, "utf8"));
    if (Array.isArray(raw.tokens)) {
      return { tokens: raw.tokens };
    }
    if (typeof raw === "object" && raw !== null && !Array.isArray(raw)) {
      const migrated = [];
      for (const [key, value] of Object.entries(raw)) {
        if (key === "tokens") continue;
        if (typeof value === "string" && value.length > 0) {
          migrated.push({ token: value, connector: key, createdAt: (/* @__PURE__ */ new Date()).toISOString() });
        }
      }
      if (migrated.length > 0) {
        const store = { tokens: migrated };
        try {
          saveTokenStore(store, tokensPath);
        } catch {
        }
        return store;
      }
    }
    return { tokens: [] };
  } catch {
    return { tokens: [] };
  }
}
function saveTokenStore(store, tokensPath) {
  const p = tokensPath ?? defaultTokensPath();
  ensureDir(p);
  fs.writeFileSync(p, JSON.stringify(store, null, 2) + "\n", { mode: 384 });
  try {
    fs.chmodSync(p, 384);
  } catch {
  }
}
function buildTokenEntry(connector) {
  const prefix = TOKEN_PREFIXES[connector] ?? "remnic_xx_";
  const token = prefix + randomBytes(24).toString("hex");
  return {
    token,
    connector,
    createdAt: (/* @__PURE__ */ new Date()).toISOString()
  };
}
function commitTokenEntry(entry, tokensPath) {
  const store = loadTokenStore(tokensPath);
  store.tokens = store.tokens.filter((t) => t.connector !== entry.connector);
  store.tokens.push(entry);
  saveTokenStore(store, tokensPath);
}
function generateToken(connector, tokensPath) {
  const store = loadTokenStore(tokensPath);
  store.tokens = store.tokens.filter((t) => t.connector !== connector);
  const entry = buildTokenEntry(connector);
  store.tokens.push(entry);
  saveTokenStore(store, tokensPath);
  return entry;
}
function listTokens(tokensPath) {
  return loadTokenStore(tokensPath).tokens;
}
function revokeToken(connector, tokensPath) {
  const store = loadTokenStore(tokensPath);
  const before = store.tokens.length;
  store.tokens = store.tokens.filter((t) => t.connector !== connector);
  if (store.tokens.length < before) {
    saveTokenStore(store, tokensPath);
    return true;
  }
  return false;
}
function getAllValidTokens(tokensPath) {
  return loadTokenStore(tokensPath).tokens.map((t) => t.token);
}
var TOKEN_CACHE_TTL_MS = 5e3;
var _cachedTokens = [];
var _cachedAt = 0;
var _cachedPath;
function getAllValidTokensCached(tokensPath) {
  const now = Date.now();
  if (now - _cachedAt < TOKEN_CACHE_TTL_MS && tokensPath === _cachedPath) return _cachedTokens;
  _cachedTokens = getAllValidTokens(tokensPath);
  _cachedAt = now;
  _cachedPath = tokensPath;
  return _cachedTokens;
}
function resolveConnectorFromToken(token, tokensPath) {
  return loadTokenStore(tokensPath).tokens.find((t) => t.token === token)?.connector;
}

export {
  loadTokenStore,
  saveTokenStore,
  buildTokenEntry,
  commitTokenEntry,
  generateToken,
  listTokens,
  revokeToken,
  getAllValidTokens,
  getAllValidTokensCached,
  resolveConnectorFromToken
};
//# sourceMappingURL=chunk-VTU2B4VF.js.map