/**
 * Token metric contract shared by analytics_summary, analytics_models and analytics_timeseries.
 *
 * observed_tokens = input + cache_write + output: every token the model processed that was not a
 * cache hit. Adapters store input without cache reads (Codex subtracts cached_input_tokens from the
 * OpenAI input); Anthropic reports newly cached prompt tokens as cache_creation_input_tokens instead
 * of input_tokens, so cache writes are counted to keep Claude comparable with Codex, whose uncached
 * input already contains the tokens it caches. Cache reads and reasoning stay separate.
 *
 * Token metrics measure consumption, so they cover main sessions, subagent sessions (with or
 * without user messages) and `task` containers (usage imported without a local conversation, e.g.
 * unmatched Cursor dashboard export events); session and message KPIs keep the main-session scope. Sessions of
 * unknown kind and main rows without user messages (legacy telemetry-only or token-only groups,
 * possibly ghost projections of tokens already counted elsewhere) stay technical for tokens too.
 */
export function observedTokensSql(alias = "mm"): string {
  return `(COALESCE(${alias}.input_tokens,0)+COALESCE(${alias}.cache_write_tokens,0)+COALESCE(${alias}.output_tokens,0))`;
}

/** SQL predicate of the non-main sessions whose tokens are counted. */
export function tokenOnlySessionSql(alias?: string): string {
  const prefix = alias ? `${alias}.` : "";
  return `${prefix}session_kind IN ('subagent','task')`;
}

/** SQL predicate of the sessions whose tokens are counted: KPI main sessions, subagents, task containers. */
export function tokenSessionSql(alias?: string): string {
  return `(${mainSessionSql(alias)} OR ${tokenOnlySessionSql(alias)})`;
}

/** SQL predicate of the main-session KPI scope used by session and message counts. */
export function mainSessionSql(alias?: string): string {
  const prefix = alias ? `${alias}.` : "";
  return `(COALESCE(${prefix}session_kind, 'main') = 'main' AND ${prefix}user_message_count > 0)`;
}

export const OBSERVED_TOKENS_NOTE = "observed_tokens = input_tokens + cache_write_tokens + output_tokens (tokens not served from cache); cache reads and reasoning are reported separately, never estimated";
export const TOKEN_SCOPE_NOTE = "token metrics cover main, subagent and task (imported usage) sessions; session and message counts cover main sessions only";
