/**
 * Foliko ID 生成器 - 统一 ID 生成
 * 支持 UUID、ULID、雪花ID、自定义前缀
 */

const crypto = require('crypto');

/**
 * 生成标准 UUID v4
 * @returns {string}
 */
function uuid() {
  if (crypto.randomUUID) {
    return crypto.randomUUID();
  }
  // 回退实现 (Node.js < 14.17)
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
    (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
  );
}

/**
 * 生成带前缀的 UUID
 * @param {string} prefix - 前缀，如 'agent', 'session', 'task'
 * @returns {string}
 */
function prefixedId(prefix = 'id') {
  return `${prefix}_${uuid()}`;
}

/**
 * 生成短 ID (无连字符)
 * @param {number} length - 长度，默认 12
 * @returns {string}
 */
function shortId(length = 12) {
  return uuid().replace(/-/g, '').slice(0, length);
}

/**
 * 生成雪花 ID (Twitter Snowflake 简化版)
 * @returns {string}
 */
let snowflakeEpoch = 1609459200000; // 2021-01-01
let snowflakeSequence = 0;
let snowflakeLastTime = 0;

function snowflake() {
  const now = Date.now();

  if (now === snowflakeLastTime) {
    snowflakeSequence = (snowflakeSequence + 1) & 4095;
  } else {
    snowflakeSequence = 0;
    snowflakeLastTime = now;
  }

  const timestamp = now - snowflakeEpoch;
  const workerId = 1;

  const id = (BigInt(timestamp) << 22n) | (BigInt(workerId) << 12n) | BigInt(snowflakeSequence);

  return id.toString();
}

/**
 * 生成任务 ID (向后兼容原有格式)
 * @param {string} [prefix] - 可选前缀
 * @returns {string}
 */
function taskId(prefix) {
  const suffix = crypto.randomBytes(8).toString('base64url');
  return prefix ? `${prefix}_${suffix}` : suffix;
}

/**
 * 生成目标 ID (向后兼容原有格式)
 * @returns {string}
 */
function goalId() {
  const random = crypto.randomBytes(8).toString('base64url');
  return `goal_${Date.now()}_${random}`;
}

/**
 * 生成会话 ID (向后兼容原有格式)
 * @returns {string}
 */
function sessionId() {
  const random = crypto.randomBytes(8).toString('base64url');
  return `session_${Date.now()}_${random}`;
}

/**
 * 生成邮箱消息 ID
 * @returns {string}
 */
function messageId() {
  const timestamp = Date.now();
  const random = crypto.randomBytes(10).toString('base64url');
  return `<${timestamp}.${random}@foliko>`;
}

/**
 * 生成规则 ID
 * @returns {string}
 */
function ruleId() {
  const random = crypto.randomBytes(8).toString('base64url');
  return `rule_${Date.now()}_${random}`;
}

/**
 * 重置雪花 ID 计数器 (用于测试)
 */
function resetSnowflake() {
  snowflakeSequence = 0;
  snowflakeLastTime = 0;
}

// 导出所有函数
module.exports = {
  uuid,
  prefixedId,
  shortId,
  snowflake,
  taskId,
  goalId,
  sessionId,
  messageId,
  ruleId,
  resetSnowflake,
};
