import type { ConversationGroupData } from "./ConversationHeader";

/**
 * Trend direction for a single cache token field, comparing the current log
 * to the previous log in the same conversation group.
 */
export type CacheTrend = { direction: "up" | "down"; delta: number };

/**
 * Per-log trend entry. `creation` covers `cacheCreationInputTokens`,
 * `read` covers `cacheReadInputTokens`. Each field is `null` when there is
 * no previous log to compare against, when the current log has no value for
 * the field, or when the values are equal (no visual change).
 */
export type CacheTrendEntry = { creation: CacheTrend | null; read: CacheTrend | null };

/**
 * Build a `logId -> CacheTrendEntry` map for every log that has a previous
 * log in its conversation group. Pure: does not mutate `groups`. Walks each
 * group in array order (which is the timestamp-sorted order produced by
 * `groupLogsByConversation`), so "previous log" is the adjacent entry in
 * that order.
 */
export function computeCacheTrends(groups: ConversationGroupData[]): Map<number, CacheTrendEntry> {
  const result = new Map<number, CacheTrendEntry>();

  for (const group of groups) {
    const logs = group.logs;
    for (let i = 1; i < logs.length; i++) {
      const prev = logs[i - 1];
      const curr = logs[i];
      if (prev === undefined || curr === undefined) continue;

      result.set(curr.id, {
        creation: compareField(prev.cacheCreationInputTokens, curr.cacheCreationInputTokens),
        read: compareField(prev.cacheReadInputTokens, curr.cacheReadInputTokens),
      });
    }
  }

  return result;
}

function compareField(previous: number | null, current: number | null): CacheTrend | null {
  if (current === null) return null;
  if (previous === null) return null;
  if (current > previous) return { direction: "up", delta: current - previous };
  if (current < previous) return { direction: "down", delta: previous - current };
  return null;
}
