import { LLMMessage } from '../plugins/plugin_entry.js';

/** 每个 token 约 4 个字符 */
const CHARS_PER_TOKEN = 4;

/** 每条消息的固定开销 token */
const MSG_OVERHEAD = 4;

/** 估算单条消息的 token 数 */
export function estimateMessageTokens(msg: LLMMessage): number {
  let chars = (msg.content ?? '').length;
  if (msg.toolCalls) {
    for (const tc of msg.toolCalls) {
      chars += (tc.arguments ?? '').length;
      chars += (tc.name ?? '').length;
      chars += (tc.id ?? '').length;
    }
  }
  if (msg.toolCallId) {
    chars += msg.toolCallId.length;
  }
  return Math.ceil(chars / CHARS_PER_TOKEN) + MSG_OVERHEAD;
}

/** 估算整个历史的 token 数 */
export function estimateHistoryTokens(messages: LLMMessage[]): number {
  return messages.reduce((sum, m) => sum + estimateMessageTokens(m), 0);
}

/** 计算上下文占用百分比 */
export function contextPercent(usedTokens: number, maxTokens: number): number {
  if (maxTokens <= 0) return 0;
  return Math.min(100, Math.round((usedTokens / maxTokens) * 100));
}
